blob: fd3f266c9a08ef32088a332884c92ed4a45e8d50 [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
Simon Pilgrim2c518802017-03-30 14:13:19 +0000470 // sufficient, and if neither is local, then they are in the same scope.)
Richard Smithc7d48d12015-05-20 17:50:35 +0000471 continue;
472 }
473
Nico Webera6916892016-06-10 18:53:04 +0000474 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
Richard Smithafe4aa82017-02-10 02:19:05 +0000650 // FIXME: It's not clear what should happen if multiple declarations of a
651 // deduction guide have different explicitness. For now at least we simply
652 // reject any case where the explicitness changes.
Richard Smithbc491202017-02-17 20:05:37 +0000653 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
654 if (NewGuide && NewGuide->isExplicitSpecified() !=
655 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
Richard Smithafe4aa82017-02-10 02:19:05 +0000656 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
Richard Smithbc491202017-02-17 20:05:37 +0000657 << NewGuide->isExplicitSpecified();
Richard Smithafe4aa82017-02-10 02:19:05 +0000658 Diag(Old->getLocation(), diag::note_previous_declaration);
659 }
660
David Majnemer502b0ed2013-06-25 23:09:30 +0000661 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000662 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000663 // the only declaration of the function or function template in the
664 // translation unit.
665 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
666 functionDeclHasDefaultArgument(Old)) {
667 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
668 Diag(Old->getLocation(), diag::note_previous_declaration);
669 Invalid = true;
670 }
671
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000672 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000673}
674
Richard Smith7873de02016-08-11 22:25:46 +0000675NamedDecl *
676Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
677 MultiTemplateParamsArg TemplateParamLists) {
678 assert(D.isDecompositionDeclarator());
679 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
680
681 // The syntax only allows a decomposition declarator as a simple-declaration
682 // or a for-range-declaration, but we parse it in more cases than that.
683 if (!D.mayHaveDecompositionDeclarator()) {
684 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
685 << Decomp.getSourceRange();
686 return nullptr;
687 }
688
689 if (!TemplateParamLists.empty()) {
690 // FIXME: There's no rule against this, but there are also no rules that
691 // would actually make it usable, so we reject it for now.
692 Diag(TemplateParamLists.front()->getTemplateLoc(),
693 diag::err_decomp_decl_template);
694 return nullptr;
695 }
696
697 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
698 ? diag::warn_cxx14_compat_decomp_decl
699 : diag::ext_decomp_decl)
700 << Decomp.getSourceRange();
701
702 // The semantic context is always just the current context.
703 DeclContext *const DC = CurContext;
704
705 // C++1z [dcl.dcl]/8:
706 // The decl-specifier-seq shall contain only the type-specifier auto
707 // and cv-qualifiers.
708 auto &DS = D.getDeclSpec();
709 {
710 SmallVector<StringRef, 8> BadSpecifiers;
711 SmallVector<SourceLocation, 8> BadSpecifierLocs;
712 if (auto SCS = DS.getStorageClassSpec()) {
713 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
714 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
715 }
716 if (auto TSCS = DS.getThreadStorageClassSpec()) {
717 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
718 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
719 }
720 if (DS.isConstexprSpecified()) {
721 BadSpecifiers.push_back("constexpr");
722 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
723 }
724 if (DS.isInlineSpecified()) {
725 BadSpecifiers.push_back("inline");
726 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
727 }
728 if (!BadSpecifiers.empty()) {
729 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
730 Err << (int)BadSpecifiers.size()
731 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
732 // Don't add FixItHints to remove the specifiers; we do still respect
733 // them when building the underlying variable.
734 for (auto Loc : BadSpecifierLocs)
735 Err << SourceRange(Loc, Loc);
736 }
737 // We can't recover from it being declared as a typedef.
738 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
739 return nullptr;
740 }
741
742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
743 QualType R = TInfo->getType();
744
745 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
746 UPPC_DeclarationType))
747 D.setInvalidType();
748
749 // The syntax only allows a single ref-qualifier prior to the decomposition
750 // declarator. No other declarator chunks are permitted. Also check the type
751 // specifier here.
752 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
753 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
754 (D.getNumTypeObjects() == 1 &&
755 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
756 Diag(Decomp.getLSquareLoc(),
757 (D.hasGroupingParens() ||
758 (D.getNumTypeObjects() &&
759 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
760 ? diag::err_decomp_decl_parens
761 : diag::err_decomp_decl_type)
762 << R;
763
764 // In most cases, there's no actual problem with an explicitly-specified
765 // type, but a function type won't work here, and ActOnVariableDeclarator
766 // shouldn't be called for such a type.
767 if (R->isFunctionType())
768 D.setInvalidType();
769 }
770
771 // Build the BindingDecls.
772 SmallVector<BindingDecl*, 8> Bindings;
773
774 // Build the BindingDecls.
775 for (auto &B : D.getDecompositionDeclarator().bindings()) {
776 // Check for name conflicts.
777 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
778 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
779 ForRedeclaration);
780 LookupName(Previous, S,
781 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
782
783 // It's not permitted to shadow a template parameter name.
784 if (Previous.isSingleResult() &&
785 Previous.getFoundDecl()->isTemplateParameter()) {
786 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
787 Previous.getFoundDecl());
788 Previous.clear();
789 }
790
791 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
792 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
793 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
794 /*AllowInlineNamespace*/false);
795 if (!Previous.empty()) {
796 auto *Old = Previous.getRepresentativeDecl();
797 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
798 Diag(Old->getLocation(), diag::note_previous_definition);
799 }
800
Richard Smith32cb8c92016-08-12 00:53:41 +0000801 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000802 PushOnScopeChains(BD, S, true);
803 Bindings.push_back(BD);
804 ParsingInitForAutoVars.insert(BD);
805 }
806
807 // There are no prior lookup results for the variable itself, because it
808 // is unnamed.
809 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
810 Decomp.getLSquareLoc());
811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
812
813 // Build the variable that holds the non-decomposed object.
814 bool AddToScope = true;
815 NamedDecl *New =
816 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
817 MultiTemplateParamsArg(), AddToScope, Bindings);
818 CurContext->addHiddenDecl(New);
819
820 if (isInOpenMPDeclareTargetContext())
821 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
822
823 return New;
824}
825
826static bool checkSimpleDecomposition(
827 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000828 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000829 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
830 if ((int64_t)Bindings.size() != NumElems) {
831 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
832 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
833 << (NumElems < Bindings.size());
834 return true;
835 }
836
837 unsigned I = 0;
838 for (auto *B : Bindings) {
839 SourceLocation Loc = B->getLocation();
840 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
841 if (E.isInvalid())
842 return true;
843 E = GetInit(Loc, E.get(), I++);
844 if (E.isInvalid())
845 return true;
846 B->setBinding(ElemType, E.get());
847 }
848
849 return false;
850}
851
852static bool checkArrayLikeDecomposition(Sema &S,
853 ArrayRef<BindingDecl *> Bindings,
854 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000855 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000856 QualType ElemType) {
857 return checkSimpleDecomposition(
858 S, Bindings, Src, DecompType, NumElems, ElemType,
859 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
860 ExprResult E = S.ActOnIntegerConstant(Loc, I);
861 if (E.isInvalid())
862 return ExprError();
863 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
864 });
865}
866
867static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
868 ValueDecl *Src, QualType DecompType,
869 const ConstantArrayType *CAT) {
870 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
871 llvm::APSInt(CAT->getSize()),
872 CAT->getElementType());
873}
874
875static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
876 ValueDecl *Src, QualType DecompType,
877 const VectorType *VT) {
878 return checkArrayLikeDecomposition(
879 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
880 S.Context.getQualifiedType(VT->getElementType(),
881 DecompType.getQualifiers()));
882}
883
884static bool checkComplexDecomposition(Sema &S,
885 ArrayRef<BindingDecl *> Bindings,
886 ValueDecl *Src, QualType DecompType,
887 const ComplexType *CT) {
888 return checkSimpleDecomposition(
889 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
890 S.Context.getQualifiedType(CT->getElementType(),
891 DecompType.getQualifiers()),
892 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
893 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
894 });
895}
896
897static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
898 TemplateArgumentListInfo &Args) {
899 SmallString<128> SS;
900 llvm::raw_svector_ostream OS(SS);
901 bool First = true;
902 for (auto &Arg : Args.arguments()) {
903 if (!First)
904 OS << ", ";
905 Arg.getArgument().print(PrintingPolicy, OS);
906 First = false;
907 }
908 return OS.str();
909}
910
911static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
912 SourceLocation Loc, StringRef Trait,
913 TemplateArgumentListInfo &Args,
914 unsigned DiagID) {
915 auto DiagnoseMissing = [&] {
916 if (DiagID)
917 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
918 Args);
919 return true;
920 };
921
922 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
923 NamespaceDecl *Std = S.getStdNamespace();
924 if (!Std)
925 return DiagnoseMissing();
926
927 // Look up the trait itself, within namespace std. We can diagnose various
928 // problems with this lookup even if we've been asked to not diagnose a
929 // missing specialization, because this can only fail if the user has been
930 // declaring their own names in namespace std or we don't support the
931 // standard library implementation in use.
932 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
933 Loc, Sema::LookupOrdinaryName);
934 if (!S.LookupQualifiedName(Result, Std))
935 return DiagnoseMissing();
936 if (Result.isAmbiguous())
937 return true;
938
939 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
940 if (!TraitTD) {
941 Result.suppressDiagnostics();
942 NamedDecl *Found = *Result.begin();
943 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
944 S.Diag(Found->getLocation(), diag::note_declared_at);
945 return true;
946 }
947
948 // Build the template-id.
949 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
950 if (TraitTy.isNull())
951 return true;
952 if (!S.isCompleteType(Loc, TraitTy)) {
953 if (DiagID)
954 S.RequireCompleteType(
955 Loc, TraitTy, DiagID,
956 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
957 return true;
958 }
959
960 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
961 assert(RD && "specialization of class template is not a class?");
962
963 // Look up the member of the trait type.
964 S.LookupQualifiedName(TraitMemberLookup, RD);
965 return TraitMemberLookup.isAmbiguous();
966}
967
968static TemplateArgumentLoc
969getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
970 uint64_t I) {
971 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
972 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
973}
974
975static TemplateArgumentLoc
976getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
977 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
978}
979
980namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
981
982static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
983 llvm::APSInt &Size) {
Faisal Valid143a0c2017-04-01 21:30:49 +0000984 EnterExpressionEvaluationContext ContextRAII(
985 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smith7873de02016-08-11 22:25:46 +0000986
987 DeclarationName Value = S.PP.getIdentifierInfo("value");
988 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
989
990 // Form template argument list for tuple_size<T>.
991 TemplateArgumentListInfo Args(Loc, Loc);
992 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
993
994 // If there's no tuple_size specialization, it's not tuple-like.
995 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
996 return IsTupleLike::NotTupleLike;
997
Richard Smith208732e2016-12-08 03:24:55 +0000998 // If we get this far, we've committed to the tuple interpretation, but
999 // we can still fail if there actually isn't a usable ::value.
Richard Smith7873de02016-08-11 22:25:46 +00001000
1001 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1002 LookupResult &R;
1003 TemplateArgumentListInfo &Args;
1004 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1005 : R(R), Args(Args) {}
1006 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1007 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1008 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1009 }
1010 } Diagnoser(R, Args);
1011
1012 if (R.empty()) {
1013 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1014 return IsTupleLike::Error;
1015 }
1016
1017 ExprResult E =
1018 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1019 if (E.isInvalid())
1020 return IsTupleLike::Error;
1021
1022 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1023 if (E.isInvalid())
1024 return IsTupleLike::Error;
1025
1026 return IsTupleLike::TupleLike;
1027}
1028
1029/// \return std::tuple_element<I, T>::type.
1030static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1031 unsigned I, QualType T) {
1032 // Form template argument list for tuple_element<I, T>.
1033 TemplateArgumentListInfo Args(Loc, Loc);
1034 Args.addArgument(
1035 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1036 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1037
1038 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1039 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1040 if (lookupStdTypeTraitMember(
1041 S, R, Loc, "tuple_element", Args,
1042 diag::err_decomp_decl_std_tuple_element_not_specialized))
1043 return QualType();
1044
1045 auto *TD = R.getAsSingle<TypeDecl>();
1046 if (!TD) {
1047 R.suppressDiagnostics();
1048 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1049 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1050 if (!R.empty())
1051 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1052 return QualType();
1053 }
1054
1055 return S.Context.getTypeDeclType(TD);
1056}
1057
1058namespace {
1059struct BindingDiagnosticTrap {
1060 Sema &S;
1061 DiagnosticErrorTrap Trap;
1062 BindingDecl *BD;
1063
1064 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1065 : S(S), Trap(S.Diags), BD(BD) {}
1066 ~BindingDiagnosticTrap() {
1067 if (Trap.hasErrorOccurred())
1068 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1069 }
1070};
1071}
1072
Richard Smith3997b1b2016-08-12 01:55:21 +00001073static bool checkTupleLikeDecomposition(Sema &S,
1074 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001075 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001076 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001077 if ((int64_t)Bindings.size() != TupleSize) {
1078 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1079 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1080 << (TupleSize < Bindings.size());
1081 return true;
1082 }
1083
1084 if (Bindings.empty())
1085 return false;
1086
1087 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1088
1089 // [dcl.decomp]p3:
1090 // The unqualified-id get is looked up in the scope of E by class member
1091 // access lookup
1092 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1093 bool UseMemberGet = false;
1094 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1095 if (auto *RD = DecompType->getAsCXXRecordDecl())
1096 S.LookupQualifiedName(MemberGet, RD);
1097 if (MemberGet.isAmbiguous())
1098 return true;
1099 UseMemberGet = !MemberGet.empty();
1100 S.FilterAcceptableTemplateNames(MemberGet);
1101 }
1102
1103 unsigned I = 0;
1104 for (auto *B : Bindings) {
1105 BindingDiagnosticTrap Trap(S, B);
1106 SourceLocation Loc = B->getLocation();
1107
1108 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1109 if (E.isInvalid())
1110 return true;
1111
1112 // e is an lvalue if the type of the entity is an lvalue reference and
1113 // an xvalue otherwise
1114 if (!Src->getType()->isLValueReferenceType())
1115 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1116 E.get(), nullptr, VK_XValue);
1117
1118 TemplateArgumentListInfo Args(Loc, Loc);
1119 Args.addArgument(
1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121
1122 if (UseMemberGet) {
1123 // if [lookup of member get] finds at least one declaration, the
1124 // initializer is e.get<i-1>().
1125 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1126 CXXScopeSpec(), SourceLocation(), nullptr,
1127 MemberGet, &Args, nullptr);
1128 if (E.isInvalid())
1129 return true;
1130
1131 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1132 } else {
1133 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1134 // in the associated namespaces.
1135 Expr *Get = UnresolvedLookupExpr::Create(
1136 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1137 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1138 UnresolvedSetIterator(), UnresolvedSetIterator());
1139
1140 Expr *Arg = E.get();
1141 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1142 }
1143 if (E.isInvalid())
1144 return true;
1145 Expr *Init = E.get();
1146
1147 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1148 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1149 if (T.isNull())
1150 return true;
1151
1152 // each vi is a variable of type "reference to T" initialized with the
1153 // initializer, where the reference is an lvalue reference if the
1154 // initializer is an lvalue and an rvalue reference otherwise
1155 QualType RefType =
1156 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1157 if (RefType.isNull())
1158 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001159 auto *RefVD = VarDecl::Create(
1160 S.Context, Src->getDeclContext(), Loc, Loc,
1161 B->getDeclName().getAsIdentifierInfo(), RefType,
1162 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1163 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1164 RefVD->setTSCSpec(Src->getTSCSpec());
1165 RefVD->setImplicit();
1166 if (Src->isInlineSpecified())
1167 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001168 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001169
Richard Smith97fcf4b2016-08-14 23:15:52 +00001170 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001171 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1172 InitializationSequence Seq(S, Entity, Kind, Init);
1173 E = Seq.Perform(S, Entity, Kind, Init);
1174 if (E.isInvalid())
1175 return true;
Richard Smithda383632016-08-15 01:33:41 +00001176 E = S.ActOnFinishFullExpr(E.get(), Loc);
1177 if (E.isInvalid())
1178 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001179 RefVD->setInit(E.get());
1180 RefVD->checkInitIsICE();
1181
Richard Smith97fcf4b2016-08-14 23:15:52 +00001182 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1183 DeclarationNameInfo(B->getDeclName(), Loc),
1184 RefVD);
1185 if (E.isInvalid())
1186 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001187
1188 B->setBinding(T, E.get());
1189 I++;
1190 }
1191
1192 return false;
1193}
1194
1195/// Find the base class to decompose in a built-in decomposition of a class type.
1196/// This base class search is, unfortunately, not quite like any other that we
1197/// perform anywhere else in C++.
1198static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1199 SourceLocation Loc,
1200 const CXXRecordDecl *RD,
1201 CXXCastPath &BasePath) {
1202 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1203 CXXBasePath &Path) {
1204 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1205 };
1206
1207 const CXXRecordDecl *ClassWithFields = nullptr;
1208 if (RD->hasDirectFields())
1209 // [dcl.decomp]p4:
1210 // Otherwise, all of E's non-static data members shall be public direct
1211 // members of E ...
1212 ClassWithFields = RD;
1213 else {
1214 // ... or of ...
1215 CXXBasePaths Paths;
1216 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1217 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1218 // If no classes have fields, just decompose RD itself. (This will work
1219 // if and only if zero bindings were provided.)
1220 return RD;
1221 }
1222
1223 CXXBasePath *BestPath = nullptr;
1224 for (auto &P : Paths) {
1225 if (!BestPath)
1226 BestPath = &P;
1227 else if (!S.Context.hasSameType(P.back().Base->getType(),
1228 BestPath->back().Base->getType())) {
1229 // ... the same ...
1230 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1231 << false << RD << BestPath->back().Base->getType()
1232 << P.back().Base->getType();
1233 return nullptr;
1234 } else if (P.Access < BestPath->Access) {
1235 BestPath = &P;
1236 }
1237 }
1238
1239 // ... unambiguous ...
1240 QualType BaseType = BestPath->back().Base->getType();
1241 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1242 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1243 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1244 return nullptr;
1245 }
1246
1247 // ... public base class of E.
1248 if (BestPath->Access != AS_public) {
1249 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1250 << RD << BaseType;
1251 for (auto &BS : *BestPath) {
1252 if (BS.Base->getAccessSpecifier() != AS_public) {
1253 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1254 << (BS.Base->getAccessSpecifier() == AS_protected)
1255 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1256 break;
1257 }
1258 }
1259 return nullptr;
1260 }
1261
1262 ClassWithFields = BaseType->getAsCXXRecordDecl();
1263 S.BuildBasePathArray(Paths, BasePath);
1264 }
1265
1266 // The above search did not check whether the selected class itself has base
1267 // classes with fields, so check that now.
1268 CXXBasePaths Paths;
1269 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1270 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1271 << (ClassWithFields == RD) << RD << ClassWithFields
1272 << Paths.front().back().Base->getType();
1273 return nullptr;
1274 }
1275
1276 return ClassWithFields;
1277}
1278
1279static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1280 ValueDecl *Src, QualType DecompType,
1281 const CXXRecordDecl *RD) {
1282 CXXCastPath BasePath;
1283 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1284 if (!RD)
1285 return true;
1286 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1287 DecompType.getQualifiers());
1288
1289 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001290 unsigned NumFields =
1291 std::count_if(RD->field_begin(), RD->field_end(),
1292 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001293 assert(Bindings.size() != NumFields);
1294 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1295 << DecompType << (unsigned)Bindings.size() << NumFields
1296 << (NumFields < Bindings.size());
1297 return true;
1298 };
1299
1300 // all of E's non-static data members shall be public [...] members,
1301 // E shall not have an anonymous union member, ...
1302 unsigned I = 0;
1303 for (auto *FD : RD->fields()) {
1304 if (FD->isUnnamedBitfield())
1305 continue;
1306
1307 if (FD->isAnonymousStructOrUnion()) {
1308 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1309 << DecompType << FD->getType()->isUnionType();
1310 S.Diag(FD->getLocation(), diag::note_declared_at);
1311 return true;
1312 }
1313
1314 // We have a real field to bind.
1315 if (I >= Bindings.size())
1316 return DiagnoseBadNumberOfBindings();
1317 auto *B = Bindings[I++];
1318
1319 SourceLocation Loc = B->getLocation();
1320 if (FD->getAccess() != AS_public) {
1321 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1322
1323 // Determine whether the access specifier was explicit.
1324 bool Implicit = true;
1325 for (const auto *D : RD->decls()) {
1326 if (declaresSameEntity(D, FD))
1327 break;
1328 if (isa<AccessSpecDecl>(D)) {
1329 Implicit = false;
1330 break;
1331 }
1332 }
1333
1334 S.Diag(FD->getLocation(), diag::note_access_natural)
1335 << (FD->getAccess() == AS_protected) << Implicit;
1336 return true;
1337 }
1338
1339 // Initialize the binding to Src.FD.
1340 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1341 if (E.isInvalid())
1342 return true;
1343 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1344 VK_LValue, &BasePath);
1345 if (E.isInvalid())
1346 return true;
1347 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1348 CXXScopeSpec(), FD,
1349 DeclAccessPair::make(FD, FD->getAccess()),
1350 DeclarationNameInfo(FD->getDeclName(), Loc));
1351 if (E.isInvalid())
1352 return true;
1353
1354 // If the type of the member is T, the referenced type is cv T, where cv is
1355 // the cv-qualification of the decomposition expression.
1356 //
1357 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1358 // 'const' to the type of the field.
1359 Qualifiers Q = DecompType.getQualifiers();
1360 if (FD->isMutable())
1361 Q.removeConst();
1362 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1363 }
1364
1365 if (I != Bindings.size())
1366 return DiagnoseBadNumberOfBindings();
1367
1368 return false;
1369}
1370
Richard Smith3997b1b2016-08-12 01:55:21 +00001371void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001372 QualType DecompType = DD->getType();
1373
1374 // If the type of the decomposition is dependent, then so is the type of
1375 // each binding.
1376 if (DecompType->isDependentType()) {
1377 for (auto *B : DD->bindings())
1378 B->setType(Context.DependentTy);
1379 return;
1380 }
1381
1382 DecompType = DecompType.getNonReferenceType();
1383 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1384
1385 // C++1z [dcl.decomp]/2:
1386 // If E is an array type [...]
1387 // As an extension, we also support decomposition of built-in complex and
1388 // vector types.
1389 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1390 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1391 DD->setInvalidDecl();
1392 return;
1393 }
1394 if (auto *VT = DecompType->getAs<VectorType>()) {
1395 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1396 DD->setInvalidDecl();
1397 return;
1398 }
1399 if (auto *CT = DecompType->getAs<ComplexType>()) {
1400 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1401 DD->setInvalidDecl();
1402 return;
1403 }
1404
1405 // C++1z [dcl.decomp]/3:
1406 // if the expression std::tuple_size<E>::value is a well-formed integral
1407 // constant expression, [...]
1408 llvm::APSInt TupleSize(32);
1409 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1410 case IsTupleLike::Error:
1411 DD->setInvalidDecl();
1412 return;
1413
1414 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001415 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001416 DD->setInvalidDecl();
1417 return;
1418
1419 case IsTupleLike::NotTupleLike:
1420 break;
1421 }
1422
1423 // C++1z [dcl.dcl]/8:
1424 // [E shall be of array or non-union class type]
1425 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1426 if (!RD || RD->isUnion()) {
1427 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1428 << DD << !RD << DecompType;
1429 DD->setInvalidDecl();
1430 return;
1431 }
1432
1433 // C++1z [dcl.decomp]/4:
1434 // all of E's non-static data members shall be [...] direct members of
1435 // E or of the same unambiguous public base class of E, ...
1436 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1437 DD->setInvalidDecl();
1438}
1439
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001440/// \brief Merge the exception specifications of two variable declarations.
1441///
1442/// This is called when there's a redeclaration of a VarDecl. The function
1443/// checks if the redeclaration might have an exception specification and
1444/// validates compatibility and merges the specs if necessary.
1445void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1446 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001448 return;
1449
1450 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1451 "Should only be called if types are otherwise the same.");
1452
1453 QualType NewType = New->getType();
1454 QualType OldType = Old->getType();
1455
1456 // We're only interested in pointers and references to functions, as well
1457 // as pointers to member functions.
1458 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1459 NewType = R->getPointeeType();
1460 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1461 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1462 NewType = P->getPointeeType();
1463 OldType = OldType->getAs<PointerType>()->getPointeeType();
1464 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1465 NewType = M->getPointeeType();
1466 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1467 }
1468
1469 if (!NewType->isFunctionProtoType())
1470 return;
1471
1472 // There's lots of special cases for functions. For function pointers, system
1473 // libraries are hopefully not as broken so that we don't need these
1474 // workarounds.
1475 if (CheckEquivalentExceptionSpec(
1476 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1477 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1478 New->setInvalidDecl();
1479 }
1480}
1481
Chris Lattner199abbc2008-04-08 05:04:30 +00001482/// CheckCXXDefaultArguments - Verify that the default arguments for a
1483/// function declaration are well-formed according to C++
1484/// [dcl.fct.default].
1485void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1486 unsigned NumParams = FD->getNumParams();
1487 unsigned p;
1488
1489 // Find first parameter with a default argument
1490 for (p = 0; p < NumParams; ++p) {
1491 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001492 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001493 break;
1494 }
1495
Benjamin Kramerfe257592015-03-27 13:58:41 +00001496 // C++11 [dcl.fct.default]p4:
1497 // In a given function declaration, each parameter subsequent to a parameter
1498 // with a default argument shall have a default argument supplied in this or
1499 // a previous declaration or shall be a function parameter pack. A default
1500 // argument shall not be redefined by a later declaration (not even to the
1501 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001502 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001503 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001504 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001505 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001506 if (Param->isInvalidDecl())
1507 /* We already complained about this parameter. */;
1508 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001509 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001510 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001511 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001512 else
Mike Stump11289f42009-09-09 15:08:12 +00001513 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001514 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattner199abbc2008-04-08 05:04:30 +00001516 LastMissingDefaultArg = p;
1517 }
1518 }
1519
1520 if (LastMissingDefaultArg > 0) {
1521 // Some default arguments were missing. Clear out all of the
1522 // default arguments up to (and including) the last missing
1523 // default argument, so that we leave the function parameters
1524 // in a semantically valid state.
1525 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1526 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001527 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001528 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001529 }
1530 }
1531 }
1532}
Douglas Gregor556877c2008-04-13 21:30:24 +00001533
Richard Smitheb3c10c2011-10-01 02:31:28 +00001534// CheckConstexprParameterTypes - Check whether a function's parameter types
1535// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001536// diagnostic and return false.
1537static bool CheckConstexprParameterTypes(Sema &SemaRef,
1538 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001539 unsigned ArgIndex = 0;
1540 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001541 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1542 e = FT->param_type_end();
1543 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001544 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1545 SourceLocation ParamLoc = PD->getLocation();
1546 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001547 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001548 diag::err_constexpr_non_literal_param,
1549 ArgIndex+1, PD->getSourceRange(),
1550 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001551 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001552 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001553 return true;
1554}
1555
1556/// \brief Get diagnostic %select index for tag kind for
1557/// record diagnostic message.
1558/// WARNING: Indexes apply to particular diagnostics only!
1559///
1560/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001561static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001562 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001563 case TTK_Struct: return 0;
1564 case TTK_Interface: return 1;
1565 case TTK_Class: return 2;
1566 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001567 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001568}
1569
1570// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1571// the requirements of a constexpr function definition or a constexpr
1572// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001573// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001574//
Richard Smith3607ffe2012-02-13 03:54:03 +00001575// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1576bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001577 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1578 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001579 // C++11 [dcl.constexpr]p4:
1580 // The definition of a constexpr constructor shall satisfy the following
1581 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001582 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001583 const CXXRecordDecl *RD = MD->getParent();
1584 if (RD->getNumVBases()) {
1585 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1586 << isa<CXXConstructorDecl>(NewFD)
1587 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001588 for (const auto &I : RD->vbases())
1589 Diag(I.getLocStart(),
1590 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001591 return false;
1592 }
Richard Smith7971b692012-01-13 04:54:00 +00001593 }
1594
1595 if (!isa<CXXConstructorDecl>(NewFD)) {
1596 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001597 // The definition of a constexpr function shall satisfy the following
1598 // constraints:
1599 // - it shall not be virtual;
1600 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1601 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001602 Method = Method->getCanonicalDecl();
1603 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001604
Richard Smith3607ffe2012-02-13 03:54:03 +00001605 // If it's not obvious why this function is virtual, find an overridden
1606 // function which uses the 'virtual' keyword.
1607 const CXXMethodDecl *WrittenVirtual = Method;
1608 while (!WrittenVirtual->isVirtualAsWritten())
1609 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1610 if (WrittenVirtual != Method)
1611 Diag(WrittenVirtual->getLocation(),
1612 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001613 return false;
1614 }
1615
1616 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001617 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001618 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001619 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001620 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001621 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001622 }
1623
Richard Smith7971b692012-01-13 04:54:00 +00001624 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001625 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001626 return false;
1627
Richard Smitheb3c10c2011-10-01 02:31:28 +00001628 return true;
1629}
1630
1631/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001632/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001633///
Richard Smithd9f663b2013-04-22 15:31:51 +00001634/// \return true if the body is OK (maybe only as an extension), false if we
1635/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001636static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001637 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1638 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001639 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1640 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001641 for (const auto *DclIt : DS->decls()) {
1642 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001643 case Decl::StaticAssert:
1644 case Decl::Using:
1645 case Decl::UsingShadow:
1646 case Decl::UsingDirective:
1647 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001648 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001649 // - static_assert-declarations
1650 // - using-declarations,
1651 // - using-directives,
1652 continue;
1653
1654 case Decl::Typedef:
1655 case Decl::TypeAlias: {
1656 // - typedef declarations and alias-declarations that do not define
1657 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001658 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001659 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1660 // Don't allow variably-modified types in constexpr functions.
1661 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1662 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1663 << TL.getSourceRange() << TL.getType()
1664 << isa<CXXConstructorDecl>(Dcl);
1665 return false;
1666 }
1667 continue;
1668 }
1669
1670 case Decl::Enum:
1671 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001672 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001673 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001674 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001675 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001676 ? diag::warn_cxx11_compat_constexpr_type_definition
1677 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001678 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001679 continue;
1680
Richard Smithd9f663b2013-04-22 15:31:51 +00001681 case Decl::EnumConstant:
1682 case Decl::IndirectField:
1683 case Decl::ParmVar:
1684 // These can only appear with other declarations which are banned in
1685 // C++11 and permitted in C++1y, so ignore them.
1686 continue;
1687
Richard Smithdca60b42016-08-12 00:39:32 +00001688 case Decl::Var:
1689 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001690 // C++1y [dcl.constexpr]p3 allows anything except:
1691 // a definition of a variable of non-literal type or of static or
1692 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001693 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001694 if (VD->isThisDeclarationADefinition()) {
1695 if (VD->isStaticLocal()) {
1696 SemaRef.Diag(VD->getLocation(),
1697 diag::err_constexpr_local_var_static)
1698 << isa<CXXConstructorDecl>(Dcl)
1699 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1700 return false;
1701 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001702 if (!VD->getType()->isDependentType() &&
1703 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001704 VD->getLocation(), VD->getType(),
1705 diag::err_constexpr_local_var_non_literal_type,
1706 isa<CXXConstructorDecl>(Dcl)))
1707 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001708 if (!VD->getType()->isDependentType() &&
1709 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001710 SemaRef.Diag(VD->getLocation(),
1711 diag::err_constexpr_local_var_no_init)
1712 << isa<CXXConstructorDecl>(Dcl);
1713 return false;
1714 }
1715 }
1716 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001717 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001718 ? diag::warn_cxx11_compat_constexpr_local_var
1719 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001720 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001721 continue;
1722 }
1723
1724 case Decl::NamespaceAlias:
1725 case Decl::Function:
1726 // These are disallowed in C++11 and permitted in C++1y. Allow them
1727 // everywhere as an extension.
1728 if (!Cxx1yLoc.isValid())
1729 Cxx1yLoc = DS->getLocStart();
1730 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001731
1732 default:
1733 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1734 << isa<CXXConstructorDecl>(Dcl);
1735 return false;
1736 }
1737 }
1738
1739 return true;
1740}
1741
1742/// Check that the given field is initialized within a constexpr constructor.
1743///
1744/// \param Dcl The constexpr constructor being checked.
1745/// \param Field The field being checked. This may be a member of an anonymous
1746/// struct or union nested within the class being checked.
1747/// \param Inits All declarations, including anonymous struct/union members and
1748/// indirect members, for which any initialization was provided.
1749/// \param Diagnosed Set to true if an error is produced.
1750static void CheckConstexprCtorInitializer(Sema &SemaRef,
1751 const FunctionDecl *Dcl,
1752 FieldDecl *Field,
1753 llvm::SmallSet<Decl*, 16> &Inits,
1754 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001755 if (Field->isInvalidDecl())
1756 return;
1757
Douglas Gregor556e5862011-10-10 17:22:13 +00001758 if (Field->isUnnamedBitfield())
1759 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001760
Richard Smithab44d5b2013-12-10 08:25:00 +00001761 // Anonymous unions with no variant members and empty anonymous structs do not
1762 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1763 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001764 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001765 (Field->getType()->isUnionType()
1766 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1767 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001768 return;
1769
Richard Smitheb3c10c2011-10-01 02:31:28 +00001770 if (!Inits.count(Field)) {
1771 if (!Diagnosed) {
1772 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1773 Diagnosed = true;
1774 }
1775 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1776 } else if (Field->isAnonymousStructOrUnion()) {
1777 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001778 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001779 // If an anonymous union contains an anonymous struct of which any member
1780 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001781 if (!RD->isUnion() || Inits.count(I))
1782 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001783 }
1784}
1785
Richard Smithd9f663b2013-04-22 15:31:51 +00001786/// Check the provided statement is allowed in a constexpr function
1787/// definition.
1788static bool
1789CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001790 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001791 SourceLocation &Cxx1yLoc) {
1792 // - its function-body shall be [...] a compound-statement that contains only
1793 switch (S->getStmtClass()) {
1794 case Stmt::NullStmtClass:
1795 // - null statements,
1796 return true;
1797
1798 case Stmt::DeclStmtClass:
1799 // - static_assert-declarations
1800 // - using-declarations,
1801 // - using-directives,
1802 // - typedef declarations and alias-declarations that do not define
1803 // classes or enumerations,
1804 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1805 return false;
1806 return true;
1807
1808 case Stmt::ReturnStmtClass:
1809 // - and exactly one return statement;
1810 if (isa<CXXConstructorDecl>(Dcl)) {
1811 // C++1y allows return statements in constexpr constructors.
1812 if (!Cxx1yLoc.isValid())
1813 Cxx1yLoc = S->getLocStart();
1814 return true;
1815 }
1816
1817 ReturnStmts.push_back(S->getLocStart());
1818 return true;
1819
1820 case Stmt::CompoundStmtClass: {
1821 // C++1y allows compound-statements.
1822 if (!Cxx1yLoc.isValid())
1823 Cxx1yLoc = S->getLocStart();
1824
1825 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001826 for (auto *BodyIt : CompStmt->body()) {
1827 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001828 Cxx1yLoc))
1829 return false;
1830 }
1831 return true;
1832 }
1833
1834 case Stmt::AttributedStmtClass:
1835 if (!Cxx1yLoc.isValid())
1836 Cxx1yLoc = S->getLocStart();
1837 return true;
1838
1839 case Stmt::IfStmtClass: {
1840 // C++1y allows if-statements.
1841 if (!Cxx1yLoc.isValid())
1842 Cxx1yLoc = S->getLocStart();
1843
1844 IfStmt *If = cast<IfStmt>(S);
1845 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1846 Cxx1yLoc))
1847 return false;
1848 if (If->getElse() &&
1849 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1850 Cxx1yLoc))
1851 return false;
1852 return true;
1853 }
1854
1855 case Stmt::WhileStmtClass:
1856 case Stmt::DoStmtClass:
1857 case Stmt::ForStmtClass:
1858 case Stmt::CXXForRangeStmtClass:
1859 case Stmt::ContinueStmtClass:
1860 // C++1y allows all of these. We don't allow them as extensions in C++11,
1861 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001862 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001863 break;
1864 if (!Cxx1yLoc.isValid())
1865 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001866 for (Stmt *SubStmt : S->children())
1867 if (SubStmt &&
1868 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001869 Cxx1yLoc))
1870 return false;
1871 return true;
1872
1873 case Stmt::SwitchStmtClass:
1874 case Stmt::CaseStmtClass:
1875 case Stmt::DefaultStmtClass:
1876 case Stmt::BreakStmtClass:
1877 // C++1y allows switch-statements, and since they don't need variable
1878 // mutation, we can reasonably allow them in C++11 as an extension.
1879 if (!Cxx1yLoc.isValid())
1880 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001881 for (Stmt *SubStmt : S->children())
1882 if (SubStmt &&
1883 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001884 Cxx1yLoc))
1885 return false;
1886 return true;
1887
1888 default:
1889 if (!isa<Expr>(S))
1890 break;
1891
1892 // C++1y allows expression-statements.
1893 if (!Cxx1yLoc.isValid())
1894 Cxx1yLoc = S->getLocStart();
1895 return true;
1896 }
1897
1898 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1899 << isa<CXXConstructorDecl>(Dcl);
1900 return false;
1901}
1902
Richard Smitheb3c10c2011-10-01 02:31:28 +00001903/// Check the body for the given constexpr function declaration only contains
1904/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1905///
1906/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001907bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001908 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001909 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001910 // The definition of a constexpr function shall satisfy the following
1911 // constraints: [...]
1912 // - its function-body shall be = delete, = default, or a
1913 // compound-statement
1914 //
Richard Smith74388b42012-02-04 00:33:54 +00001915 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001916 // In the definition of a constexpr constructor, [...]
1917 // - its function-body shall not be a function-try-block;
1918 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1919 << isa<CXXConstructorDecl>(Dcl);
1920 return false;
1921 }
1922
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001923 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001924
1925 // - its function-body shall be [...] a compound-statement that contains only
1926 // [... list of cases ...]
1927 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1928 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001929 for (auto *BodyIt : CompBody->body()) {
1930 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001931 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001932 }
1933
Richard Smithd9f663b2013-04-22 15:31:51 +00001934 if (Cxx1yLoc.isValid())
1935 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001936 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001937 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1938 : diag::ext_constexpr_body_invalid_stmt)
1939 << isa<CXXConstructorDecl>(Dcl);
1940
Richard Smitheb3c10c2011-10-01 02:31:28 +00001941 if (const CXXConstructorDecl *Constructor
1942 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1943 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001944 // DR1359:
1945 // - every non-variant non-static data member and base class sub-object
1946 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001947 // DR1460:
1948 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001949 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001950 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001951 if (Constructor->getNumCtorInitializers() == 0 &&
1952 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001953 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1954 return false;
1955 }
Richard Smithf368fb42011-10-10 16:38:04 +00001956 } else if (!Constructor->isDependentContext() &&
1957 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001958 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1959
1960 // Skip detailed checking if we have enough initializers, and we would
1961 // allow at most one initializer per member.
1962 bool AnyAnonStructUnionMembers = false;
1963 unsigned Fields = 0;
1964 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1965 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001966 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001967 AnyAnonStructUnionMembers = true;
1968 break;
1969 }
1970 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001971 // DR1460:
1972 // - if the class is a union-like class, but is not a union, for each of
1973 // its anonymous union members having variant members, exactly one of
1974 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001975 if (AnyAnonStructUnionMembers ||
1976 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1977 // Check initialization of non-static data members. Base classes are
1978 // always initialized so do not need to be checked. Dependent bases
1979 // might not have initializers in the member initializer list.
1980 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001981 for (const auto *I: Constructor->inits()) {
1982 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001983 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001984 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001985 Inits.insert(ID->chain_begin(), ID->chain_end());
1986 }
1987
1988 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001989 for (auto *I : RD->fields())
1990 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001991 if (Diagnosed)
1992 return false;
1993 }
1994 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001995 } else {
1996 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001997 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001998 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001999 // otherwise if there's no return statement, the function cannot
2000 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002001 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00002002 (Dcl->getReturnType()->isVoidType() ||
2003 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00002004 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00002005 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2006 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00002007 if (!OK)
2008 return false;
2009 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002010 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002011 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002012 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2013 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002014 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2015 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002016 }
2017 }
2018
Richard Smith74388b42012-02-04 00:33:54 +00002019 // C++11 [dcl.constexpr]p5:
2020 // if no function argument values exist such that the function invocation
2021 // substitution would produce a constant expression, the program is
2022 // ill-formed; no diagnostic required.
2023 // C++11 [dcl.constexpr]p3:
2024 // - every constructor call and implicit conversion used in initializing the
2025 // return value shall be one of those allowed in a constant expression.
2026 // C++11 [dcl.constexpr]p4:
2027 // - every constructor involved in initializing non-static data members and
2028 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002029 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002030 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002031 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002032 << isa<CXXConstructorDecl>(Dcl);
2033 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2034 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002035 // Don't return false here: we allow this for compatibility in
2036 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002037 }
2038
Richard Smitheb3c10c2011-10-01 02:31:28 +00002039 return true;
2040}
2041
Douglas Gregor61956c42008-10-31 09:07:45 +00002042/// isCurrentClassName - Determine whether the identifier II is the
2043/// name of the class type currently being defined. In the case of
2044/// nested classes, this will only return true if II is the name of
2045/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002046bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2047 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002048 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002049
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002050 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002051 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002052 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002053 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2054 } else
2055 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2056
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002057 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002058 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002059 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002060}
2061
Richard Smithfb8b7b92013-10-15 00:00:26 +00002062/// \brief Determine whether the identifier II is a typo for the name of
2063/// the class type currently being defined. If so, update it to the identifier
2064/// that should have been used.
2065bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2066 assert(getLangOpts().CPlusPlus && "No class names in C!");
2067
2068 if (!getLangOpts().SpellChecking)
2069 return false;
2070
2071 CXXRecordDecl *CurDecl;
2072 if (SS && SS->isSet() && !SS->isInvalid()) {
2073 DeclContext *DC = computeDeclContext(*SS, true);
2074 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2075 } else
2076 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2077
2078 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2079 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2080 < II->getLength()) {
2081 II = CurDecl->getIdentifier();
2082 return true;
2083 }
2084
2085 return false;
2086}
2087
Douglas Gregordc974572012-11-10 07:24:09 +00002088/// \brief Determine whether the given class is a base class of the given
2089/// class, including looking at dependent bases.
2090static bool findCircularInheritance(const CXXRecordDecl *Class,
2091 const CXXRecordDecl *Current) {
2092 SmallVector<const CXXRecordDecl*, 8> Queue;
2093
2094 Class = Class->getCanonicalDecl();
2095 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002096 for (const auto &I : Current->bases()) {
2097 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002098 if (!Base)
2099 continue;
2100
2101 Base = Base->getDefinition();
2102 if (!Base)
2103 continue;
2104
2105 if (Base->getCanonicalDecl() == Class)
2106 return true;
2107
2108 Queue.push_back(Base);
2109 }
2110
2111 if (Queue.empty())
2112 return false;
2113
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002114 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002115 }
2116
2117 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002118}
2119
Mike Stump11289f42009-09-09 15:08:12 +00002120/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002121///
2122/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2123/// and returns NULL otherwise.
2124CXXBaseSpecifier *
2125Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2126 SourceRange SpecifierRange,
2127 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002128 TypeSourceInfo *TInfo,
2129 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002130 QualType BaseType = TInfo->getType();
2131
Douglas Gregor463421d2009-03-03 04:44:36 +00002132 // C++ [class.union]p1:
2133 // A union shall not have base classes.
2134 if (Class->isUnion()) {
2135 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2136 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002137 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002138 }
2139
Douglas Gregor752a5952011-01-03 22:36:02 +00002140 if (EllipsisLoc.isValid() &&
2141 !TInfo->getType()->containsUnexpandedParameterPack()) {
2142 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2143 << TInfo->getTypeLoc().getSourceRange();
2144 EllipsisLoc = SourceLocation();
2145 }
Douglas Gregor62004702012-11-10 01:18:17 +00002146
2147 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2148
2149 if (BaseType->isDependentType()) {
2150 // Make sure that we don't have circular inheritance among our dependent
2151 // bases. For non-dependent bases, the check for completeness below handles
2152 // this.
2153 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2154 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2155 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002156 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002157 Diag(BaseLoc, diag::err_circular_inheritance)
2158 << BaseType << Context.getTypeDeclType(Class);
2159
2160 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2161 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2162 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002163
2164 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002165 }
2166 }
2167
Mike Stump11289f42009-09-09 15:08:12 +00002168 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002169 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002170 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002171 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002172
2173 // Base specifiers must be record types.
2174 if (!BaseType->isRecordType()) {
2175 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002176 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002177 }
2178
2179 // C++ [class.union]p1:
2180 // A union shall not be used as a base class.
2181 if (BaseType->isUnionType()) {
2182 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002183 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002184 }
2185
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002186 // For the MS ABI, propagate DLL attributes to base class templates.
2187 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2188 if (Attr *ClassAttr = getDLLAttr(Class)) {
2189 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2190 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002191 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2192 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002193 }
2194 }
2195 }
2196
Douglas Gregor463421d2009-03-03 04:44:36 +00002197 // C++ [class.derived]p2:
2198 // The class-name in a base-specifier shall not be an incompletely
2199 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002200 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002201 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002202 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002203 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002204 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002205
Eli Friedmanc96d4962009-08-15 21:55:26 +00002206 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002207 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002208 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002209 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002210 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002211 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002212 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002213
David Majnemer9b1754d2013-11-02 12:00:36 +00002214 // A class which contains a flexible array member is not suitable for use as a
2215 // base class:
2216 // - If the layout determines that a base comes before another base,
2217 // the flexible array member would index into the subsequent base.
2218 // - If the layout determines that base comes before the derived class,
2219 // the flexible array member would index into the derived class.
2220 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2221 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2222 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002223 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002224 }
2225
Anders Carlsson65c76d32011-03-25 14:55:14 +00002226 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002227 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002228 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002229 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002230 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002231 << CXXBaseDecl->getDeclName()
2232 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002233 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2234 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002235 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002236 }
2237
John McCall3696dcb2010-08-17 07:23:57 +00002238 if (BaseDecl->isInvalidDecl())
2239 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002240
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002241 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002242 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002243 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002244 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002245}
2246
Douglas Gregor556877c2008-04-13 21:30:24 +00002247/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2248/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002249/// example:
2250/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002251/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002252BaseResult
John McCall48871652010-08-21 09:40:31 +00002253Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002254 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002255 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002256 ParsedType basetype, SourceLocation BaseLoc,
2257 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002258 if (!classdecl)
2259 return true;
2260
Douglas Gregorc40290e2009-03-09 23:48:35 +00002261 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002262 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002263 if (!Class)
2264 return true;
2265
David Majnemer5ef4fe72014-06-13 06:43:46 +00002266 // We haven't yet attached the base specifiers.
2267 Class->setIsParsingBaseSpecifiers();
2268
Richard Smith4c96e992013-02-19 23:47:15 +00002269 // We do not support any C++11 attributes on base-specifiers yet.
2270 // Diagnose any attributes we see.
2271 if (!Attributes.empty()) {
2272 for (AttributeList *Attr = Attributes.getList(); Attr;
2273 Attr = Attr->getNext()) {
2274 if (Attr->isInvalid() ||
2275 Attr->getKind() == AttributeList::IgnoredAttribute)
2276 continue;
2277 Diag(Attr->getLoc(),
2278 Attr->getKind() == AttributeList::UnknownAttribute
2279 ? diag::warn_unknown_attribute_ignored
2280 : diag::err_base_specifier_attribute)
2281 << Attr->getName();
2282 }
2283 }
2284
Craig Topperc3ec1492014-05-26 06:22:03 +00002285 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002286 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002287
Douglas Gregor752a5952011-01-03 22:36:02 +00002288 if (EllipsisLoc.isInvalid() &&
2289 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002290 UPPC_BaseType))
2291 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002292
Douglas Gregor463421d2009-03-03 04:44:36 +00002293 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002294 Virtual, Access, TInfo,
2295 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002296 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002297 else
2298 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002299
Douglas Gregor463421d2009-03-03 04:44:36 +00002300 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002301}
Douglas Gregor556877c2008-04-13 21:30:24 +00002302
Nathan Sidwell44b21742015-01-19 01:44:02 +00002303/// Use small set to collect indirect bases. As this is only used
2304/// locally, there's no need to abstract the small size parameter.
2305typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2306
2307/// \brief Recursively add the bases of Type. Don't add Type itself.
2308static void
2309NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2310 const QualType &Type)
2311{
2312 // Even though the incoming type is a base, it might not be
2313 // a class -- it could be a template parm, for instance.
2314 if (auto Rec = Type->getAs<RecordType>()) {
2315 auto Decl = Rec->getAsCXXRecordDecl();
2316
2317 // Iterate over its bases.
2318 for (const auto &BaseSpec : Decl->bases()) {
2319 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2320 .getUnqualifiedType();
2321 if (Set.insert(Base).second)
2322 // If we've not already seen it, recurse.
2323 NoteIndirectBases(Context, Set, Base);
2324 }
2325 }
2326}
2327
Douglas Gregor463421d2009-03-03 04:44:36 +00002328/// \brief Performs the actual work of attaching the given base class
2329/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002330bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2331 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2332 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002333 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002334
2335 // Used to keep track of which base types we have already seen, so
2336 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002337 // that the key is always the unqualified canonical type of the base
2338 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002339 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2340
Nathan Sidwell44b21742015-01-19 01:44:02 +00002341 // Used to track indirect bases so we can see if a direct base is
2342 // ambiguous.
2343 IndirectBaseSet IndirectBaseTypes;
2344
Douglas Gregor29a92472008-10-22 17:49:05 +00002345 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002346 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002347 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002348 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002349 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002350 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002351 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002352
2353 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2354 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002355 // C++ [class.mi]p3:
2356 // A class shall not be specified as a direct base class of a
2357 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002358 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002359 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002360 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002361 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002362
2363 // Delete the duplicate base class specifier; we're going to
2364 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002365 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002366
2367 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002368 } else {
2369 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002370 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002371 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002372
2373 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002374 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002375 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2376
John McCalldb632ac2012-09-25 07:32:39 +00002377 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2378 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2379 if (Class->isInterface() &&
2380 (!RD->isInterface() ||
2381 KnownBase->getAccessSpecifier() != AS_public)) {
2382 // The Microsoft extension __interface does not permit bases that
2383 // are not themselves public interfaces.
2384 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2385 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2386 << RD->getSourceRange();
2387 Invalid = true;
2388 }
2389 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002390 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002391 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002392 }
2393 }
2394
2395 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002396 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002397
2398 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2399 // Check whether this direct base is inaccessible due to ambiguity.
2400 QualType BaseType = Bases[idx]->getType();
2401 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2402 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002403
Nathan Sidwell44b21742015-01-19 01:44:02 +00002404 if (IndirectBaseTypes.count(CanonicalBase)) {
2405 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2406 /*DetectVirtual=*/true);
2407 bool found
2408 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2409 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002410 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002411
2412 if (Paths.isAmbiguous(CanonicalBase))
2413 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2414 << BaseType << getAmbiguousPathsDisplayString(Paths)
2415 << Bases[idx]->getSourceRange();
2416 else
2417 assert(Bases[idx]->isVirtual());
2418 }
2419
2420 // Delete the base class specifier, since its data has been copied
2421 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002422 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002423 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002424
2425 return Invalid;
2426}
2427
2428/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2429/// class, after checking whether there are any duplicate base
2430/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002431void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2432 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2433 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002434 return;
2435
2436 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002437 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002438}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002439
Douglas Gregor36d1b142009-10-06 17:59:45 +00002440/// \brief Determine whether the type \p Derived is a C++ class that is
2441/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002442bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002444 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002445
Douglas Gregor45bb4832013-03-26 23:36:30 +00002446 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002447 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002448 return false;
2449
Douglas Gregor45bb4832013-03-26 23:36:30 +00002450 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002451 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002452 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002453
2454 // If either the base or the derived type is invalid, don't try to
2455 // check whether one is derived from the other.
2456 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2457 return false;
2458
Richard Smithdb0ac552015-12-18 22:40:25 +00002459 // FIXME: In a modules build, do we need the entire path to be visible for us
2460 // to be able to use the inheritance relationship?
2461 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2462 return false;
2463
Richard Smith0f59cb32015-12-18 21:45:41 +00002464 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002465}
2466
2467/// \brief Determine whether the type \p Derived is a C++ class that is
2468/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002469bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2470 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002471 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002472 return false;
2473
Douglas Gregor45bb4832013-03-26 23:36:30 +00002474 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002475 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002476 return false;
2477
Douglas Gregor45bb4832013-03-26 23:36:30 +00002478 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002479 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002480 return false;
2481
Richard Smithdb0ac552015-12-18 22:40:25 +00002482 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2483 return false;
2484
Douglas Gregor36d1b142009-10-06 17:59:45 +00002485 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2486}
2487
Anders Carlssona70cff62010-04-24 19:06:50 +00002488void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002489 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002490 assert(BasePathArray.empty() && "Base path array must be empty!");
2491 assert(Paths.isRecordingPaths() && "Must record paths!");
2492
2493 const CXXBasePath &Path = Paths.front();
2494
2495 // We first go backward and check if we have a virtual base.
2496 // FIXME: It would be better if CXXBasePath had the base specifier for
2497 // the nearest virtual base.
2498 unsigned Start = 0;
2499 for (unsigned I = Path.size(); I != 0; --I) {
2500 if (Path[I - 1].Base->isVirtual()) {
2501 Start = I - 1;
2502 break;
2503 }
2504 }
2505
2506 // Now add all bases.
2507 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002508 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002509}
2510
Douglas Gregor36d1b142009-10-06 17:59:45 +00002511/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2512/// conversion (where Derived and Base are class types) is
2513/// well-formed, meaning that the conversion is unambiguous (and
2514/// that all of the base classes are accessible). Returns true
2515/// and emits a diagnostic if the code is ill-formed, returns false
2516/// otherwise. Loc is the location where this routine should point to
2517/// if there is an error, and Range is the source range to highlight
2518/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002519///
2520/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2521/// diagnostic for the respective type of error will be suppressed, but the
2522/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002523bool
2524Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002525 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002526 unsigned AmbigiousBaseConvID,
2527 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002528 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002529 CXXCastPath *BasePath,
2530 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002531 // First, determine whether the path from Derived to Base is
2532 // ambiguous. This is slightly more expensive than checking whether
2533 // the Derived to Base conversion exists, because here we need to
2534 // explore multiple paths to determine if there is an ambiguity.
2535 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2536 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002537 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002538 assert(DerivationOkay &&
2539 "Can only be used with a derived-to-base conversion");
2540 (void)DerivationOkay;
2541
2542 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002543 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002544 // Check that the base class can be accessed.
2545 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2546 InaccessibleBaseID)) {
2547 case AR_inaccessible:
2548 return true;
2549 case AR_accessible:
2550 case AR_dependent:
2551 case AR_delayed:
2552 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002553 }
John McCall5b0829a2010-02-10 09:31:12 +00002554 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002555
2556 // Build a base path if necessary.
2557 if (BasePath)
2558 BuildBasePathArray(Paths, *BasePath);
2559 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002560 }
2561
David Majnemer626032f2013-06-22 06:43:58 +00002562 if (AmbigiousBaseConvID) {
2563 // We know that the derived-to-base conversion is ambiguous, and
2564 // we're going to produce a diagnostic. Perform the derived-to-base
2565 // search just one more time to compute all of the possible paths so
2566 // that we can print them out. This is more expensive than any of
2567 // the previous derived-to-base checks we've done, but at this point
2568 // performance isn't as much of an issue.
2569 Paths.clear();
2570 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002571 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002572 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2573 (void)StillOkay;
2574
2575 // Build up a textual representation of the ambiguous paths, e.g.,
2576 // D -> B -> A, that will be used to illustrate the ambiguous
2577 // conversions in the diagnostic. We only print one of the paths
2578 // to each base class subobject.
2579 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2580
2581 Diag(Loc, AmbigiousBaseConvID)
2582 << Derived << Base << PathDisplayStr << Range << Name;
2583 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002584 return true;
2585}
2586
2587bool
2588Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002589 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002590 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002591 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002592 return CheckDerivedToBaseConversion(
2593 Derived, Base, diag::err_upcast_to_inaccessible_base,
2594 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2595 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002596}
2597
2598
2599/// @brief Builds a string representing ambiguous paths from a
2600/// specific derived class to different subobjects of the same base
2601/// class.
2602///
2603/// This function builds a string that can be used in error messages
2604/// to show the different paths that one can take through the
2605/// inheritance hierarchy to go from the derived class to different
2606/// subobjects of a base class. The result looks something like this:
2607/// @code
2608/// struct D -> struct B -> struct A
2609/// struct D -> struct C -> struct A
2610/// @endcode
2611std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2612 std::string PathDisplayStr;
2613 std::set<unsigned> DisplayedPaths;
2614 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2615 Path != Paths.end(); ++Path) {
2616 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2617 // We haven't displayed a path to this particular base
2618 // class subobject yet.
2619 PathDisplayStr += "\n ";
2620 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2621 for (CXXBasePath::const_iterator Element = Path->begin();
2622 Element != Path->end(); ++Element)
2623 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2624 }
2625 }
2626
2627 return PathDisplayStr;
2628}
2629
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002630//===----------------------------------------------------------------------===//
2631// C++ class member Handling
2632//===----------------------------------------------------------------------===//
2633
Abramo Bagnarad7340582010-06-05 05:09:32 +00002634/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002635bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2636 SourceLocation ASLoc,
2637 SourceLocation ColonLoc,
2638 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002639 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002640 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002641 ASLoc, ColonLoc);
2642 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002643 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002644}
2645
Richard Smith18f07db2012-08-06 03:25:17 +00002646/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002647void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002648 if (D->isInvalidDecl())
2649 return;
2650
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002651 // We only care about "override" and "final" declarations.
2652 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2653 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002654
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002655 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002656
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002657 // We can't check dependent instance methods.
2658 if (MD && MD->isInstance() &&
2659 (MD->getParent()->hasAnyDependentBases() ||
2660 MD->getType()->isDependentType()))
2661 return;
2662
2663 if (MD && !MD->isVirtual()) {
2664 // If we have a non-virtual method, check if if hides a virtual method.
2665 // (In that case, it's most likely the method has the wrong type.)
2666 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2667 FindHiddenVirtualMethods(MD, OverloadedMethods);
2668
2669 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002670 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2671 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002672 diag::override_keyword_hides_virtual_member_function)
2673 << "override" << (OverloadedMethods.size() > 1);
2674 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002675 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002676 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002677 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2678 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002679 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002680 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2681 MD->setInvalidDecl();
2682 return;
2683 }
2684 // Fall through into the general case diagnostic.
2685 // FIXME: We might want to attempt typo correction here.
2686 }
2687
2688 if (!MD || !MD->isVirtual()) {
2689 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2690 Diag(OA->getLocation(),
2691 diag::override_keyword_only_allowed_on_virtual_member_functions)
2692 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2693 D->dropAttr<OverrideAttr>();
2694 }
2695 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2696 Diag(FA->getLocation(),
2697 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002698 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2699 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002700 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002701 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002702 return;
2703 }
Richard Smith18f07db2012-08-06 03:25:17 +00002704
Richard Smith18f07db2012-08-06 03:25:17 +00002705 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002706 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002707 // does not override a member function of a base class, the program is
2708 // ill-formed.
2709 bool HasOverriddenMethods =
2710 MD->begin_overridden_methods() != MD->end_overridden_methods();
2711 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2712 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2713 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002714}
2715
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002716void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2717 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2718 return;
2719 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Richard Trieu07c93382017-03-01 03:07:55 +00002720 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002721 return;
2722
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002723 SourceLocation Loc = MD->getLocation();
2724 SourceLocation SpellingLoc = Loc;
2725 if (getSourceManager().isMacroArgExpansion(Loc))
2726 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2727 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2728 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002729 return;
Richard Trieu07c93382017-03-01 03:07:55 +00002730
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002731 if (MD->size_overridden_methods() > 0) {
Richard Trieu07c93382017-03-01 03:07:55 +00002732 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2733 ? diag::warn_destructor_marked_not_override_overriding
2734 : diag::warn_function_marked_not_override_overriding;
2735 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002736 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2737 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2738 }
2739}
2740
Richard Smith18f07db2012-08-06 03:25:17 +00002741/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002742/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002743/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002744bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2745 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002746 FinalAttr *FA = Old->getAttr<FinalAttr>();
2747 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002748 return false;
2749
2750 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002751 << New->getDeclName()
2752 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002753 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2754 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002755}
2756
Daniel Jasper0baec5492012-06-06 08:32:04 +00002757static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002758 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2759 // FIXME: Destruction of ObjC lifetime types has side-effects.
2760 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2761 return !RD->isCompleteDefinition() ||
2762 !RD->hasTrivialDefaultConstructor() ||
2763 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002764 return false;
2765}
2766
John McCall5e77d762013-04-16 07:28:30 +00002767static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002768 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002769 if (it->isDeclspecPropertyAttribute())
2770 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002771 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002772}
2773
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00002774// Check if there is a field shadowing.
2775void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2776 DeclarationName FieldName,
2777 const CXXRecordDecl *RD) {
2778 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2779 return;
2780
2781 // To record a shadowed field in a base
2782 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2783 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2784 CXXBasePath &Path) {
2785 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2786 // Record an ambiguous path directly
2787 if (Bases.find(Base) != Bases.end())
2788 return true;
2789 for (const auto Field : Base->lookup(FieldName)) {
2790 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2791 Field->getAccess() != AS_private) {
2792 assert(Field->getAccess() != AS_none);
2793 assert(Bases.find(Base) == Bases.end());
2794 Bases[Base] = Field;
2795 return true;
2796 }
2797 }
2798 return false;
2799 };
2800
2801 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2802 /*DetectVirtual=*/true);
2803 if (!RD->lookupInBases(FieldShadowed, Paths))
2804 return;
2805
2806 for (const auto &P : Paths) {
2807 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2808 auto It = Bases.find(Base);
2809 // Skip duplicated bases
2810 if (It == Bases.end())
2811 continue;
2812 auto BaseField = It->second;
2813 assert(BaseField->getAccess() != AS_private);
2814 if (AS_none !=
2815 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2816 Diag(Loc, diag::warn_shadow_field)
2817 << FieldName.getAsString() << RD->getName() << Base->getName();
2818 Diag(BaseField->getLocation(), diag::note_shadow_field);
2819 Bases.erase(It);
2820 }
2821 }
2822}
2823
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002824/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2825/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002826/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002827/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2828/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002829NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002830Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002831 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002832 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002833 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002834 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002835 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2836 DeclarationName Name = NameInfo.getName();
2837 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002838
2839 // For anonymous bitfields, the location should point to the type.
2840 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002841 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002842
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002843 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002844
John McCallb1cd7da2010-06-04 08:34:12 +00002845 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002846 assert(!DS.isFriendSpecified());
2847
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002848 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002849
John McCalldb632ac2012-09-25 07:32:39 +00002850 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2851 // The Microsoft extension __interface only permits public member functions
2852 // and prohibits constructors, destructors, operators, non-public member
2853 // functions, static methods and data members.
2854 unsigned InvalidDecl;
2855 bool ShowDeclName = true;
2856 if (!isFunc)
2857 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2858 else if (AS != AS_public)
2859 InvalidDecl = 2;
2860 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2861 InvalidDecl = 3;
2862 else switch (Name.getNameKind()) {
2863 case DeclarationName::CXXConstructorName:
2864 InvalidDecl = 4;
2865 ShowDeclName = false;
2866 break;
2867
2868 case DeclarationName::CXXDestructorName:
2869 InvalidDecl = 5;
2870 ShowDeclName = false;
2871 break;
2872
2873 case DeclarationName::CXXOperatorName:
2874 case DeclarationName::CXXConversionFunctionName:
2875 InvalidDecl = 6;
2876 break;
2877
2878 default:
2879 InvalidDecl = 0;
2880 break;
2881 }
2882
2883 if (InvalidDecl) {
2884 if (ShowDeclName)
2885 Diag(Loc, diag::err_invalid_member_in_interface)
2886 << (InvalidDecl-1) << Name;
2887 else
2888 Diag(Loc, diag::err_invalid_member_in_interface)
2889 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002891 }
2892 }
2893
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002894 // C++ 9.2p6: A member shall not be declared to have automatic storage
2895 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002896 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2897 // data members and cannot be applied to names declared const or static,
2898 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002899 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002900 case DeclSpec::SCS_unspecified:
2901 case DeclSpec::SCS_typedef:
2902 case DeclSpec::SCS_static:
2903 break;
2904 case DeclSpec::SCS_mutable:
2905 if (isFunc) {
2906 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002907
Richard Smithb4a9e862013-04-12 22:46:28 +00002908 // FIXME: It would be nicer if the keyword was ignored only for this
2909 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002910 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002911 }
2912 break;
2913 default:
2914 Diag(DS.getStorageClassSpecLoc(),
2915 diag::err_storageclass_invalid_for_member);
2916 D.getMutableDeclSpec().ClearStorageClassSpecs();
2917 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002918 }
2919
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002920 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2921 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002922 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002923
David Blaikie35506f82013-01-30 01:22:18 +00002924 if (DS.isConstexprSpecified() && isInstField) {
2925 SemaDiagnosticBuilder B =
2926 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2927 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2928 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002929 B << 0 << 0;
2930 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2931 B << FixItHint::CreateRemoval(ConstexprLoc);
2932 else {
2933 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2934 D.getMutableDeclSpec().ClearConstexprSpec();
2935 const char *PrevSpec;
2936 unsigned DiagID;
2937 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2938 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2939 (void)Failed;
2940 assert(!Failed && "Making a constexpr member const shouldn't fail");
2941 }
David Blaikie35506f82013-01-30 01:22:18 +00002942 } else {
2943 B << 1;
2944 const char *PrevSpec;
2945 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002946 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002947 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2948 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002949 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002950 "This is the only DeclSpec that should fail to be applied");
2951 B << 1;
2952 } else {
2953 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2954 isInstField = false;
2955 }
2956 }
2957 }
2958
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002959 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002960 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002961 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002962
2963 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002964 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002965 Diag(Loc, diag::err_bad_variable_name)
2966 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002967 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002968 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002969
Benjamin Kramer365082d2012-05-19 16:34:46 +00002970 IdentifierInfo *II = Name.getAsIdentifierInfo();
2971
Douglas Gregor7c26c042011-09-21 14:40:46 +00002972 // Member field could not be with "template" keyword.
2973 // So TemplateParameterLists should be empty in this case.
2974 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002975 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002976 if (TemplateParams->size()) {
2977 // There is no such thing as a member field template.
2978 Diag(D.getIdentifierLoc(), diag::err_template_member)
2979 << II
2980 << SourceRange(TemplateParams->getTemplateLoc(),
2981 TemplateParams->getRAngleLoc());
2982 } else {
2983 // There is an extraneous 'template<>' for this member.
2984 Diag(TemplateParams->getTemplateLoc(),
2985 diag::err_template_member_noparams)
2986 << II
2987 << SourceRange(TemplateParams->getTemplateLoc(),
2988 TemplateParams->getRAngleLoc());
2989 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002990 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002991 }
2992
Douglas Gregora007d362010-10-13 22:19:53 +00002993 if (SS.isSet() && !SS.isInvalid()) {
2994 // The user provided a superfluous scope specifier inside a class
2995 // definition:
2996 //
2997 // class X {
2998 // int X::member;
2999 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003000 if (DeclContext *DC = computeDeclContext(SS, false))
3001 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00003002 else
3003 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3004 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00003005
Douglas Gregora007d362010-10-13 22:19:53 +00003006 SS.clear();
3007 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00003008
John McCall5e77d762013-04-16 07:28:30 +00003009 AttributeList *MSPropertyAttr =
3010 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003011 if (MSPropertyAttr) {
3012 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3013 BitWidth, InitStyle, AS, MSPropertyAttr);
3014 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003015 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003016 isInstField = false;
3017 } else {
3018 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3019 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00003020 if (!Member)
3021 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003022 }
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00003023
Saleem Abdulrasoolb893ed22017-02-11 17:24:04 +00003024 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003025 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003026 Member = HandleDeclarator(S, D, TemplateParameterLists);
3027 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003028 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003029
3030 // Non-instance-fields can't have a bitfield.
3031 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003032 if (Member->isInvalidDecl()) {
3033 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00003034 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003035 // C++ 9.6p3: A bit-field shall not be a static member.
3036 // "static member 'A' cannot be a bit-field"
3037 Diag(Loc, diag::err_static_not_bitfield)
3038 << Name << BitWidth->getSourceRange();
3039 } else if (isa<TypedefDecl>(Member)) {
3040 // "typedef member 'x' cannot be a bit-field"
3041 Diag(Loc, diag::err_typedef_not_bitfield)
3042 << Name << BitWidth->getSourceRange();
3043 } else {
3044 // A function typedef ("typedef int f(); f a;").
3045 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3046 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00003047 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00003048 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00003049 }
Mike Stump11289f42009-09-09 15:08:12 +00003050
Craig Topperc3ec1492014-05-26 06:22:03 +00003051 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00003052 Member->setInvalidDecl();
3053 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00003054
3055 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00003056
Larisse Voufo39a1e502013-08-06 01:03:05 +00003057 // If we have declared a member function template or static data member
3058 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00003059 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3060 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003061 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3062 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003063 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003064
Richard Smith18f07db2012-08-06 03:25:17 +00003065 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003066 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003067 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003068 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3069 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003070
Douglas Gregorf2f08062011-03-08 17:10:18 +00003071 if (VS.getLastLocation().isValid()) {
3072 // Update the end location of a method that has a virt-specifiers.
3073 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3074 MD->setRangeEnd(VS.getLastLocation());
3075 }
Richard Smith18f07db2012-08-06 03:25:17 +00003076
Anders Carlssonc87f8612011-01-20 06:29:02 +00003077 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003078
Douglas Gregor92751d42008-11-17 22:58:34 +00003079 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003080
Daniel Jasper0baec5492012-06-06 08:32:04 +00003081 if (isInstField) {
3082 FieldDecl *FD = cast<FieldDecl>(Member);
3083 FieldCollector->Add(FD);
3084
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003085 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003086 // Remember all explicit private FieldDecls that have a name, no side
3087 // effects and are not part of a dependent type declaration.
3088 if (!FD->isImplicit() && FD->getDeclName() &&
3089 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003090 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003091 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003092 !InitializationHasSideEffects(*FD))
3093 UnusedPrivateFields.insert(FD);
3094 }
3095 }
3096
John McCall48871652010-08-21 09:40:31 +00003097 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003098}
3099
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003100namespace {
3101 class UninitializedFieldVisitor
3102 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3103 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003104 // List of Decls to generate a warning on. Also remove Decls that become
3105 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003106 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003107 // List of base classes of the record. Classes are removed after their
3108 // initializers.
3109 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003110 // Vector of decls to be removed from the Decl set prior to visiting the
3111 // nodes. These Decls may have been initialized in the prior initializer.
3112 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003113 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003114 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003115 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003116 // InitList is true, special case initialization of FieldDecls matching
3117 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003118 bool InitList;
3119 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003120 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3121
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003122 public:
3123 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003124 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003125 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3126 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3127 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3128 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003129
Richard Trieufa1d0a72014-10-17 20:56:10 +00003130 // Returns true if the use of ME is not an uninitialized use.
3131 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3132 bool CheckReferenceOnly) {
3133 llvm::SmallVector<FieldDecl*, 4> Fields;
3134 bool ReferenceField = false;
3135 while (ME) {
3136 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3137 if (!FD)
3138 return false;
3139 Fields.push_back(FD);
3140 if (FD->getType()->isReferenceType())
3141 ReferenceField = true;
3142 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3143 }
3144
3145 // Binding a reference to an unintialized field is not an
3146 // uninitialized use.
3147 if (CheckReferenceOnly && !ReferenceField)
3148 return true;
3149
3150 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3151 // Discard the first field since it is the field decl that is being
3152 // initialized.
3153 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3154 UsedFieldIndex.push_back((*I)->getFieldIndex());
3155 }
3156
3157 for (auto UsedIter = UsedFieldIndex.begin(),
3158 UsedEnd = UsedFieldIndex.end(),
3159 OrigIter = InitFieldIndex.begin(),
3160 OrigEnd = InitFieldIndex.end();
3161 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3162 if (*UsedIter < *OrigIter)
3163 return true;
3164 if (*UsedIter > *OrigIter)
3165 break;
3166 }
3167
3168 return false;
3169 }
3170
Richard Trieu2d779b92014-10-01 03:44:58 +00003171 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3172 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003173 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3174 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003175
Richard Trieu1bc22c12013-09-13 03:20:53 +00003176 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3177 // or union.
3178 MemberExpr *FieldME = ME;
3179
Richard Trieu2d779b92014-10-01 03:44:58 +00003180 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3181
Richard Trieu1bc22c12013-09-13 03:20:53 +00003182 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003183 while (MemberExpr *SubME =
3184 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003185
Richard Trieufa1d0a72014-10-17 20:56:10 +00003186 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003187 return;
3188
Richard Trieufa1d0a72014-10-17 20:56:10 +00003189 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003190 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003191 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003192
Richard Trieu2d779b92014-10-01 03:44:58 +00003193 if (!FieldME->getType().isPODType(S.Context))
3194 AllPODFields = false;
3195
Richard Trieu3630c392014-11-21 03:10:30 +00003196 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003197 }
3198
Richard Trieu3630c392014-11-21 03:10:30 +00003199 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003200 return;
3201
Richard Trieu2d779b92014-10-01 03:44:58 +00003202 if (AddressOf && AllPODFields)
3203 return;
3204
Richard Trieu406e65c2013-09-20 03:03:06 +00003205 ValueDecl* FoundVD = FieldME->getMemberDecl();
3206
Richard Trieu3630c392014-11-21 03:10:30 +00003207 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3208 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3209 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3210 }
3211
3212 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3213 QualType T = BaseCast->getType();
3214 if (T->isPointerType() &&
3215 BaseClasses.count(T->getPointeeType())) {
3216 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3217 << T->getPointeeType() << FoundVD;
3218 }
3219 }
3220 }
3221
Richard Trieuef64e942013-10-25 00:56:00 +00003222 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003223 return;
3224
Richard Trieuef64e942013-10-25 00:56:00 +00003225 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003226
Richard Trieufa1d0a72014-10-17 20:56:10 +00003227 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3228 // Special checking for initializer lists.
3229 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3230 return;
3231 }
3232 } else {
3233 // Prevent double warnings on use of unbounded references.
3234 if (CheckReferenceOnly && !IsReference)
3235 return;
3236 }
Richard Trieuef64e942013-10-25 00:56:00 +00003237
3238 unsigned diag = IsReference
3239 ? diag::warn_reference_field_is_uninit
3240 : diag::warn_field_is_uninit;
3241 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3242 if (Constructor)
3243 S.Diag(Constructor->getLocation(),
3244 diag::note_uninit_in_this_constructor)
3245 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3246
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003247 }
3248
Richard Trieu2d779b92014-10-01 03:44:58 +00003249 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003250 E = E->IgnoreParens();
3251
3252 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003253 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3254 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003255 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003256 }
3257
3258 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003259 Visit(CO->getCond());
3260 HandleValue(CO->getTrueExpr(), AddressOf);
3261 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003262 return;
3263 }
3264
3265 if (BinaryConditionalOperator *BCO =
3266 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003267 Visit(BCO->getCond());
3268 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003269 return;
3270 }
3271
Richard Trieuabf6ec42014-08-27 22:15:10 +00003272 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003273 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003274 return;
3275 }
3276
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3278 switch (BO->getOpcode()) {
3279 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003280 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003281 case(BO_PtrMemD):
3282 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003283 HandleValue(BO->getLHS(), AddressOf);
3284 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003285 return;
3286 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003287 Visit(BO->getLHS());
3288 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003289 return;
3290 }
3291 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003292
3293 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003294 }
3295
Richard Trieufa1d0a72014-10-17 20:56:10 +00003296 void CheckInitListExpr(InitListExpr *ILE) {
3297 InitFieldIndex.push_back(0);
3298 for (auto Child : ILE->children()) {
3299 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3300 CheckInitListExpr(SubList);
3301 } else {
3302 Visit(Child);
3303 }
3304 ++InitFieldIndex.back();
3305 }
3306 InitFieldIndex.pop_back();
3307 }
3308
Richard Trieu8d08a272014-08-28 03:23:47 +00003309 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003310 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003311 // Remove Decls that may have been initialized in the previous
3312 // initializer.
3313 for (ValueDecl* VD : DeclsToRemove)
3314 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003315 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003316
Richard Trieu8d08a272014-08-28 03:23:47 +00003317 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003318 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3319
3320 if (ILE && Field) {
3321 InitList = true;
3322 InitListFieldDecl = Field;
3323 InitFieldIndex.clear();
3324 CheckInitListExpr(ILE);
3325 } else {
3326 InitList = false;
3327 Visit(E);
3328 }
3329
Richard Trieu8d08a272014-08-28 03:23:47 +00003330 if (Field)
3331 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003332 if (BaseClass)
3333 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003334 }
3335
Richard Trieu1bc22c12013-09-13 03:20:53 +00003336 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003337 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003338 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003339 }
3340
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003341 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003342 if (E->getCastKind() == CK_LValueToRValue) {
3343 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3344 return;
3345 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003346
3347 Inherited::VisitImplicitCastExpr(E);
3348 }
3349
Richard Trieu1bc22c12013-09-13 03:20:53 +00003350 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003351 if (E->getConstructor()->isCopyConstructor()) {
3352 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003353 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3354 if (ILE->getNumInits() == 1)
3355 ArgExpr = ILE->getInit(0);
3356 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3357 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003358 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003359 HandleValue(ArgExpr, false /*AddressOf*/);
3360 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003361 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003362 Inherited::VisitCXXConstructExpr(E);
3363 }
3364
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003365 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3366 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003367 if (isa<MemberExpr>(Callee)) {
3368 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003369 for (auto Arg : E->arguments())
3370 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003371 return;
3372 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003373
3374 Inherited::VisitCXXMemberCallExpr(E);
3375 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003376
Richard Trieu11fd0792014-08-26 04:30:55 +00003377 void VisitCallExpr(CallExpr *E) {
3378 // Treat std::move as a use.
3379 if (E->getNumArgs() == 1) {
3380 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003381 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3382 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003383 HandleValue(E->getArg(0), false /*AddressOf*/);
3384 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003385 }
3386 }
3387 }
3388
3389 Inherited::VisitCallExpr(E);
3390 }
3391
Richard Trieud4a01362014-10-31 21:10:22 +00003392 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3393 Expr *Callee = E->getCallee();
3394
3395 if (isa<UnresolvedLookupExpr>(Callee))
3396 return Inherited::VisitCXXOperatorCallExpr(E);
3397
3398 Visit(Callee);
3399 for (auto Arg : E->arguments())
3400 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3401 }
3402
Richard Trieu406e65c2013-09-20 03:03:06 +00003403 void VisitBinaryOperator(BinaryOperator *E) {
3404 // If a field assignment is detected, remove the field from the
3405 // uninitiailized field set.
3406 if (E->getOpcode() == BO_Assign)
3407 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3408 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003409 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003410 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003411
Richard Trieu52b8b602014-09-25 01:15:40 +00003412 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003413 HandleValue(E->getLHS(), false /*AddressOf*/);
3414 Visit(E->getRHS());
3415 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003416 }
3417
Richard Trieu406e65c2013-09-20 03:03:06 +00003418 Inherited::VisitBinaryOperator(E);
3419 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003420
3421 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003422 if (E->isIncrementDecrementOp()) {
3423 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3424 return;
3425 }
3426 if (E->getOpcode() == UO_AddrOf) {
3427 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3428 HandleValue(ME->getBase(), true /*AddressOf*/);
3429 return;
3430 }
3431 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003432
3433 Inherited::VisitUnaryOperator(E);
3434 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003435 };
Richard Trieuef64e942013-10-25 00:56:00 +00003436
3437 // Diagnose value-uses of fields to initialize themselves, e.g.
3438 // foo(foo)
3439 // where foo is not also a parameter to the constructor.
3440 // Also diagnose across field uninitialized use such as
3441 // x(y), y(x)
3442 // TODO: implement -Wuninitialized and fold this into that framework.
3443 static void DiagnoseUninitializedFields(
3444 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3445
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003446 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3447 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003448 return;
3449 }
3450
3451 if (Constructor->isInvalidDecl())
3452 return;
3453
3454 const CXXRecordDecl *RD = Constructor->getParent();
3455
Richard Trieu353a4b42014-10-22 05:21:59 +00003456 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003457 return;
3458
Richard Trieuef64e942013-10-25 00:56:00 +00003459 // Holds fields that are uninitialized.
3460 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3461
3462 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003463 for (auto *I : RD->decls()) {
3464 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003465 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003466 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003467 UninitializedFields.insert(IFD->getAnonField());
3468 }
3469 }
3470
Richard Trieu3630c392014-11-21 03:10:30 +00003471 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3472 for (auto I : RD->bases())
3473 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3474
3475 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003476 return;
3477
3478 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003479 UninitializedFields,
3480 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003481
Aaron Ballman0ad78302014-03-13 17:34:31 +00003482 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003483 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003484 break;
3485
Aaron Ballman0ad78302014-03-13 17:34:31 +00003486 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003487 if (!InitExpr)
3488 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003489
Richard Trieu8d08a272014-08-28 03:23:47 +00003490 if (CXXDefaultInitExpr *Default =
3491 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3492 InitExpr = Default->getExpr();
3493 if (!InitExpr)
3494 continue;
3495 // In class initializers will point to the constructor.
3496 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003497 FieldInit->getAnyMember(),
3498 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003499 } else {
3500 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003501 FieldInit->getAnyMember(),
3502 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003503 }
Richard Trieuef64e942013-10-25 00:56:00 +00003504 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003505 }
3506} // namespace
3507
Richard Smith74108172014-01-17 03:11:34 +00003508/// \brief Enter a new C++ default initializer scope. After calling this, the
3509/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3510/// parsing or instantiating the initializer failed.
3511void Sema::ActOnStartCXXInClassMemberInitializer() {
3512 // Create a synthetic function scope to represent the call to the constructor
3513 // that notionally surrounds a use of this initializer.
3514 PushFunctionScope();
3515}
3516
3517/// \brief This is invoked after parsing an in-class initializer for a
3518/// non-static C++ class member, and after instantiating an in-class initializer
3519/// in a class template. Such actions are deferred until the class is complete.
3520void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3521 SourceLocation InitLoc,
3522 Expr *InitExpr) {
3523 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003524 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003525
David Majnemer87ff66c2014-12-13 11:34:16 +00003526 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3527 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003528 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003529
3530 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003531 D->setInvalidDecl();
3532 if (FD)
3533 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003534 return;
3535 }
3536
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003537 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3538 FD->setInvalidDecl();
3539 FD->removeInClassInitializer();
3540 return;
3541 }
3542
Richard Smith938f40b2011-06-11 17:19:42 +00003543 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003544 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003545 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003546 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003547 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003548 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003549 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3550 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003551 if (Init.isInvalid()) {
3552 FD->setInvalidDecl();
3553 return;
3554 }
Richard Smith938f40b2011-06-11 17:19:42 +00003555 }
3556
Richard Smith945f8d32013-01-14 22:39:08 +00003557 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003558 // The initialization of each base and member constitutes a
3559 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003561 if (Init.isInvalid()) {
3562 FD->setInvalidDecl();
3563 return;
3564 }
3565
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003566 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003567
3568 FD->setInClassInitializer(InitExpr);
3569}
3570
Douglas Gregor15e77a22009-12-31 09:10:24 +00003571/// \brief Find the direct and/or virtual base specifiers that
3572/// correspond to the given base type, for use in base initialization
3573/// within a constructor.
3574static bool FindBaseInitializer(Sema &SemaRef,
3575 CXXRecordDecl *ClassDecl,
3576 QualType BaseType,
3577 const CXXBaseSpecifier *&DirectBaseSpec,
3578 const CXXBaseSpecifier *&VirtualBaseSpec) {
3579 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003580 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003581 for (const auto &Base : ClassDecl->bases()) {
3582 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003583 // We found a direct base of this type. That's what we're
3584 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003585 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003586 break;
3587 }
3588 }
3589
3590 // Check for a virtual base class.
3591 // FIXME: We might be able to short-circuit this if we know in advance that
3592 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003593 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003594 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3595 // We haven't found a base yet; search the class hierarchy for a
3596 // virtual base class.
3597 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3598 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003599 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3600 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003601 BaseType, Paths)) {
3602 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3603 Path != Paths.end(); ++Path) {
3604 if (Path->back().Base->isVirtual()) {
3605 VirtualBaseSpec = Path->back().Base;
3606 break;
3607 }
3608 }
3609 }
3610 }
3611
3612 return DirectBaseSpec || VirtualBaseSpec;
3613}
3614
Sebastian Redla74948d2011-09-24 17:48:25 +00003615/// \brief Handle a C++ member initializer using braced-init-list syntax.
3616MemInitResult
3617Sema::ActOnMemInitializer(Decl *ConstructorD,
3618 Scope *S,
3619 CXXScopeSpec &SS,
3620 IdentifierInfo *MemberOrBase,
3621 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003622 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003623 SourceLocation IdLoc,
3624 Expr *InitList,
3625 SourceLocation EllipsisLoc) {
3626 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003627 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003628 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003629}
3630
3631/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003632MemInitResult
John McCall48871652010-08-21 09:40:31 +00003633Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003634 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003635 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003636 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003637 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003638 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003639 SourceLocation IdLoc,
3640 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003641 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003642 SourceLocation RParenLoc,
3643 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003644 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003645 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003646 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003647 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003648}
3649
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003650namespace {
3651
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003652// Callback to only accept typo corrections that can be a valid C++ member
3653// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003654class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003655public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003656 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3657 : ClassDecl(ClassDecl) {}
3658
Craig Toppera798a9d2014-03-02 09:32:10 +00003659 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003660 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3661 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3662 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003663 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003664 }
3665 return false;
3666 }
3667
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003668private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003669 CXXRecordDecl *ClassDecl;
3670};
3671
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003672}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003673
Sebastian Redla74948d2011-09-24 17:48:25 +00003674/// \brief Handle a C++ member initializer.
3675MemInitResult
3676Sema::BuildMemInitializer(Decl *ConstructorD,
3677 Scope *S,
3678 CXXScopeSpec &SS,
3679 IdentifierInfo *MemberOrBase,
3680 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003681 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003682 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003683 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003684 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003685 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3686 if (!Res.isUsable())
3687 return true;
3688 Init = Res.get();
3689
Douglas Gregor71a57182009-06-22 23:20:33 +00003690 if (!ConstructorD)
3691 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003693 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003694
3695 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003696 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003697 if (!Constructor) {
3698 // The user wrote a constructor initializer on a function that is
3699 // not a C++ constructor. Ignore the error for now, because we may
3700 // have more member initializers coming; we'll diagnose it just
3701 // once in ActOnMemInitializers.
3702 return true;
3703 }
3704
3705 CXXRecordDecl *ClassDecl = Constructor->getParent();
3706
3707 // C++ [class.base.init]p2:
3708 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003709 // constructor's class and, if not found in that scope, are looked
3710 // up in the scope containing the constructor's definition.
3711 // [Note: if the constructor's class contains a member with the
3712 // same name as a direct or virtual base class of the class, a
3713 // mem-initializer-id naming the member or base class and composed
3714 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003715 // mem-initializer-id for the hidden base class may be specified
3716 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003717 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003718 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003719 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003720 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003721 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003722 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3723 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003724 if (EllipsisLoc.isValid())
3725 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003726 << MemberOrBase
3727 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003728
Sebastian Redla9351792012-02-11 23:51:47 +00003729 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003730 }
Francois Pichetd583da02010-12-04 09:14:42 +00003731 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003732 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003733 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003734 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003735 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003736
3737 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003738 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003739 } else if (DS.getTypeSpecType() == TST_decltype) {
3740 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
Richard Smithef2cd8f2017-02-08 20:39:08 +00003741 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3742 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3743 return true;
John McCallb5a0d312009-12-21 10:41:20 +00003744 } else {
3745 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3746 LookupParsedName(R, S, &SS);
3747
3748 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3749 if (!TyD) {
3750 if (R.isAmbiguous()) return true;
3751
John McCallda6841b2010-04-09 19:01:14 +00003752 // We don't want access-control diagnostics here.
3753 R.suppressDiagnostics();
3754
Douglas Gregora3b624a2010-01-19 06:46:48 +00003755 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3756 bool NotUnknownSpecialization = false;
3757 DeclContext *DC = computeDeclContext(SS, false);
3758 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3759 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3760
3761 if (!NotUnknownSpecialization) {
3762 // When the scope specifier can refer to a member of an unknown
3763 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003764 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3765 SS.getWithLocInContext(Context),
3766 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003767 if (BaseType.isNull())
3768 return true;
3769
Douglas Gregora3b624a2010-01-19 06:46:48 +00003770 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003771 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003772 }
3773 }
3774
Douglas Gregor15e77a22009-12-31 09:10:24 +00003775 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003776 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003777 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003778 (Corr = CorrectTypo(
3779 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3780 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3781 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003782 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003783 // We have found a non-static data member with a similar
3784 // name to what was typed; complain and initialize that
3785 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003786 diagnoseTypo(Corr,
3787 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3788 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003789 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003790 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003791 const CXXBaseSpecifier *DirectBaseSpec;
3792 const CXXBaseSpecifier *VirtualBaseSpec;
3793 if (FindBaseInitializer(*this, ClassDecl,
3794 Context.getTypeDeclType(Type),
3795 DirectBaseSpec, VirtualBaseSpec)) {
3796 // We have found a direct or virtual base class with a
3797 // similar name to what was typed; complain and initialize
3798 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003799 diagnoseTypo(Corr,
3800 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3801 << MemberOrBase << false,
3802 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003803
Richard Smithf9b15102013-08-17 00:46:16 +00003804 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3805 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003806 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003807 diag::note_base_class_specified_here)
3808 << BaseSpec->getType()
3809 << BaseSpec->getSourceRange();
3810
Douglas Gregor15e77a22009-12-31 09:10:24 +00003811 TyD = Type;
3812 }
3813 }
3814 }
3815
Douglas Gregora3b624a2010-01-19 06:46:48 +00003816 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003817 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003818 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003819 return true;
3820 }
John McCallb5a0d312009-12-21 10:41:20 +00003821 }
3822
Douglas Gregora3b624a2010-01-19 06:46:48 +00003823 if (BaseType.isNull()) {
3824 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003825 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003826 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003827 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3828 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003829 TInfo = Context.CreateTypeSourceInfo(BaseType);
3830 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3831 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3832 TL.setElaboratedKeywordLoc(SourceLocation());
3833 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3834 }
John McCallb5a0d312009-12-21 10:41:20 +00003835 }
3836 }
Mike Stump11289f42009-09-09 15:08:12 +00003837
John McCallbcd03502009-12-07 02:54:59 +00003838 if (!TInfo)
3839 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003840
Sebastian Redla9351792012-02-11 23:51:47 +00003841 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003842}
3843
Chandler Carruth599deef2011-09-03 01:14:15 +00003844/// Checks a member initializer expression for cases where reference (or
3845/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003846static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3847 Expr *Init,
3848 SourceLocation IdLoc) {
3849 QualType MemberTy = Member->getType();
3850
3851 // We only handle pointers and references currently.
3852 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3853 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3854 return;
3855
3856 const bool IsPointer = MemberTy->isPointerType();
3857 if (IsPointer) {
3858 if (const UnaryOperator *Op
3859 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3860 // The only case we're worried about with pointers requires taking the
3861 // address.
3862 if (Op->getOpcode() != UO_AddrOf)
3863 return;
3864
3865 Init = Op->getSubExpr();
3866 } else {
3867 // We only handle address-of expression initializers for pointers.
3868 return;
3869 }
3870 }
3871
Richard Smithe3b28bc2013-06-12 21:51:50 +00003872 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003873 // We only warn when referring to a non-reference parameter declaration.
3874 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3875 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003876 return;
3877
3878 S.Diag(Init->getExprLoc(),
3879 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3880 : diag::warn_bind_ref_member_to_parameter)
3881 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003882 } else {
3883 // Other initializers are fine.
3884 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003885 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003886
3887 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3888 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003889}
3890
John McCallfaf5fb42010-08-26 23:41:50 +00003891MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003892Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003893 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003894 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3895 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3896 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003897 "Member must be a FieldDecl or IndirectFieldDecl");
3898
Sebastian Redla9351792012-02-11 23:51:47 +00003899 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003900 return true;
3901
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003902 if (Member->isInvalidDecl())
3903 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003904
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003905 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003906 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003907 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003908 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003909 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003910 } else {
3911 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003912 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003913 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003914
Sebastian Redla9351792012-02-11 23:51:47 +00003915 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003916
Sebastian Redla9351792012-02-11 23:51:47 +00003917 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003918 // Can't check initialization for a member of dependent type or when
3919 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003920 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003921 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003922 bool InitList = false;
3923 if (isa<InitListExpr>(Init)) {
3924 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003925 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003926 }
3927
Chandler Carruthd44c3102010-12-06 09:23:57 +00003928 // Initialize the member.
3929 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3931 : InitializedEntity::InitializeMember(IndirectMember,
3932 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003933 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003934 InitList ? InitializationKind::CreateDirectList(IdLoc)
3935 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3936 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003937
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003938 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003939 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3940 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003941 if (MemberInit.isInvalid())
3942 return true;
3943
Richard Smith736a9472013-06-12 20:42:33 +00003944 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3945
Richard Smith945f8d32013-01-14 22:39:08 +00003946 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003947 // The initialization of each base and member constitutes a
3948 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003949 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003950 if (MemberInit.isInvalid())
3951 return true;
3952
Richard Smithd59b8322012-12-19 01:39:02 +00003953 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003954 }
3955
Chandler Carruthd44c3102010-12-06 09:23:57 +00003956 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003957 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3958 InitRange.getBegin(), Init,
3959 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003960 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003961 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3962 InitRange.getBegin(), Init,
3963 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003964 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003965}
3966
John McCallfaf5fb42010-08-26 23:41:50 +00003967MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003968Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003969 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003970 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003971 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003972 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003973 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003974 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003975
Sebastian Redl0501c632012-02-12 16:37:36 +00003976 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003977 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003978 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3979 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003980 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003981 }
3982
Sebastian Redla9351792012-02-11 23:51:47 +00003983 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003984 // Initialize the object.
3985 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3986 QualType(ClassDecl->getTypeForDecl(), 0));
3987 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003988 InitList ? InitializationKind::CreateDirectList(NameLoc)
3989 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3990 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003991 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003992 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003993 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003994 if (DelegationInit.isInvalid())
3995 return true;
3996
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003997 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3998 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003999
Richard Smith945f8d32013-01-14 22:39:08 +00004000 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00004001 // The initialization of each base and member constitutes a
4002 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004003 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4004 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00004005 if (DelegationInit.isInvalid())
4006 return true;
4007
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004008 // If we are in a dependent context, template instantiation will
4009 // perform this type-checking again. Just save the arguments that we
4010 // received in a ParenListExpr.
4011 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4012 // of the information that we have about the base
4013 // initializer. However, deconstructing the ASTs is a dicey process,
4014 // and this approach is far more likely to get the corner cases right.
4015 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004016 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004017
Sebastian Redla9351792012-02-11 23:51:47 +00004018 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004019 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004020 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004021}
4022
4023MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00004024Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00004025 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004026 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004027 SourceLocation BaseLoc
4028 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00004029
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004030 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4031 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4032 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4033
4034 // C++ [class.base.init]p2:
4035 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00004036 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004037 // of that class, the mem-initializer is ill-formed. A
4038 // mem-initializer-list can initialize a base class using any
4039 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00004040 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004041
Sebastian Redla9351792012-02-11 23:51:47 +00004042 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00004043 if (EllipsisLoc.isValid()) {
4044 // This is a pack expansion.
4045 if (!BaseType->containsUnexpandedParameterPack()) {
4046 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00004047 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00004048
Douglas Gregor44e7df62011-01-04 00:32:56 +00004049 EllipsisLoc = SourceLocation();
4050 }
4051 } else {
4052 // Check for any unexpanded parameter packs.
4053 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4054 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00004055
Sebastian Redla9351792012-02-11 23:51:47 +00004056 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00004057 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004058 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004059
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004060 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00004061 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4062 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004063 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004064 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4065 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004066 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004067
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004068 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4069 VirtualBaseSpec);
4070
4071 // C++ [base.class.init]p2:
4072 // Unless the mem-initializer-id names a nonstatic data member of the
4073 // constructor's class or a direct or virtual base of that class, the
4074 // mem-initializer is ill-formed.
4075 if (!DirectBaseSpec && !VirtualBaseSpec) {
4076 // If the class has any dependent bases, then it's possible that
4077 // one of those types will resolve to the same type as
4078 // BaseType. Therefore, just treat this as a dependent base
4079 // class initialization. FIXME: Should we try to check the
4080 // initialization anyway? It seems odd.
4081 if (ClassDecl->hasAnyDependentBases())
4082 Dependent = true;
4083 else
4084 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4085 << BaseType << Context.getTypeDeclType(ClassDecl)
4086 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4087 }
4088 }
4089
4090 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004091 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004092
Sebastian Redla74948d2011-09-24 17:48:25 +00004093 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4094 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004095 InitRange.getBegin(), Init,
4096 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004097 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004098
4099 // C++ [base.class.init]p2:
4100 // If a mem-initializer-id is ambiguous because it designates both
4101 // a direct non-virtual base class and an inherited virtual base
4102 // class, the mem-initializer is ill-formed.
4103 if (DirectBaseSpec && VirtualBaseSpec)
4104 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004105 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004106
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004107 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004108 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004109 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004110
4111 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004112 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004113 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004114 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004115 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004116 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004117 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004118
4119 InitializedEntity BaseEntity =
4120 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4121 InitializationKind Kind =
4122 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4123 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4124 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004125 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004126 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004127 if (BaseInit.isInvalid())
4128 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004129
Richard Smith945f8d32013-01-14 22:39:08 +00004130 // C++11 [class.base.init]p7:
4131 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004132 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004133 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004134 if (BaseInit.isInvalid())
4135 return true;
4136
4137 // If we are in a dependent context, template instantiation will
4138 // perform this type-checking again. Just save the arguments that we
4139 // received in a ParenListExpr.
4140 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4141 // of the information that we have about the base
4142 // initializer. However, deconstructing the ASTs is a dicey process,
4143 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004144 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004145 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004146
Alexis Hunt1d792652011-01-08 20:30:50 +00004147 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004148 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004149 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004151 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004152}
4153
Sebastian Redl22653ba2011-08-30 19:58:05 +00004154// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004155static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4156 if (T.isNull()) T = E->getType();
4157 QualType TargetType = SemaRef.BuildReferenceType(
4158 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004159 SourceLocation ExprLoc = E->getLocStart();
4160 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4161 TargetType, ExprLoc);
4162
4163 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4164 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004165 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004166}
4167
Anders Carlsson1b00e242010-04-23 03:10:23 +00004168/// ImplicitInitializerKind - How an implicit base or member initializer should
4169/// initialize its base or member.
4170enum ImplicitInitializerKind {
4171 IIK_Default,
4172 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004173 IIK_Move,
4174 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004175};
4176
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004177static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004178BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004179 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004180 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004181 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004182 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004183 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004184 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4185 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004186
John McCalldadc5752010-08-24 06:29:42 +00004187 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004188
4189 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004190 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004191 case IIK_Default: {
4192 InitializationKind InitKind
4193 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004194 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4195 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004196 break;
4197 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004198
Sebastian Redl22653ba2011-08-30 19:58:05 +00004199 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004200 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004201 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004202 ParmVarDecl *Param = Constructor->getParamDecl(0);
4203 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004204
Anders Carlsson1b00e242010-04-23 03:10:23 +00004205 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004206 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004207 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004208 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004209 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004210
Eli Friedmanfa0df832012-02-02 03:46:19 +00004211 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4212
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004213 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004214 QualType ArgTy =
4215 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4216 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004217
Sebastian Redl22653ba2011-08-30 19:58:05 +00004218 if (Moving) {
4219 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4220 }
4221
John McCallcf142162010-08-07 06:22:56 +00004222 CXXCastPath BasePath;
4223 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004224 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4225 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004226 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004227 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004228
Anders Carlsson1b00e242010-04-23 03:10:23 +00004229 InitializationKind InitKind
4230 = InitializationKind::CreateDirect(Constructor->getLocation(),
4231 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004232 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4233 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004234 break;
4235 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004236 }
John McCallb268a282010-08-23 23:25:46 +00004237
Douglas Gregora40433a2010-12-07 00:41:46 +00004238 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004239 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004240 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004241
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004242 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004243 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004244 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4245 SourceLocation()),
4246 BaseSpec->isVirtual(),
4247 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004248 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004249 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004250 SourceLocation());
4251
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004252 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004253}
4254
Sebastian Redl22653ba2011-08-30 19:58:05 +00004255static bool RefersToRValueRef(Expr *MemRef) {
4256 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4257 return Referenced->getType()->isRValueReferenceType();
4258}
4259
Anders Carlsson3c1db572010-04-23 02:15:47 +00004260static bool
4261BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004262 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004263 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004264 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004265 if (Field->isInvalidDecl())
4266 return true;
4267
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004268 SourceLocation Loc = Constructor->getLocation();
4269
Sebastian Redl22653ba2011-08-30 19:58:05 +00004270 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4271 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004272 ParmVarDecl *Param = Constructor->getParamDecl(0);
4273 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004274
4275 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004276 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4277 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004278
Anders Carlsson423f5d82010-04-23 16:04:08 +00004279 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004280 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004281 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004282 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004283
Eli Friedmanfa0df832012-02-02 03:46:19 +00004284 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4285
Sebastian Redl22653ba2011-08-30 19:58:05 +00004286 if (Moving) {
4287 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4288 }
4289
Douglas Gregor94f9a482010-05-05 05:51:00 +00004290 // Build a reference to this field within the parameter.
4291 CXXScopeSpec SS;
4292 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4293 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004294 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4295 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004296 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004297 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004298 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004299 ParamType, Loc,
4300 /*IsArrow=*/false,
4301 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004302 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004303 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004304 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004305 /*TemplateArgs=*/nullptr,
4306 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004307 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004308 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004309
4310 // C++11 [class.copy]p15:
4311 // - if a member m has rvalue reference type T&&, it is direct-initialized
4312 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004313 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004314 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004315 }
4316
Richard Smith30e304e2016-12-14 00:03:17 +00004317 InitializedEntity Entity =
4318 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4319 /*Implicit*/ true)
4320 : InitializedEntity::InitializeMember(Field, nullptr,
4321 /*Implicit*/ true);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004322
Douglas Gregor94f9a482010-05-05 05:51:00 +00004323 // Direct-initialize to use the copy constructor.
4324 InitializationKind InitKind =
4325 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4326
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004327 Expr *CtorArgE = CtorArg.getAs<Expr>();
Richard Smith30e304e2016-12-14 00:03:17 +00004328 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4329 ExprResult MemberInit =
4330 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004331 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004332 if (MemberInit.isInvalid())
4333 return true;
4334
Richard Smith30e304e2016-12-14 00:03:17 +00004335 if (Indirect)
4336 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4337 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4338 else
4339 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4340 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004341 return false;
4342 }
4343
Richard Smithc2bc61b2013-03-18 21:12:30 +00004344 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4345 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004346
Anders Carlsson3c1db572010-04-23 02:15:47 +00004347 QualType FieldBaseElementType =
4348 SemaRef.Context.getBaseElementType(Field->getType());
4349
Anders Carlsson3c1db572010-04-23 02:15:47 +00004350 if (FieldBaseElementType->isRecordType()) {
Richard Smith30e304e2016-12-14 00:03:17 +00004351 InitializedEntity InitEntity =
4352 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4353 /*Implicit*/ true)
4354 : InitializedEntity::InitializeMember(Field, nullptr,
4355 /*Implicit*/ true);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004356 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004357 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004358
4359 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4360 ExprResult MemberInit =
4361 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004362
Douglas Gregora40433a2010-12-07 00:41:46 +00004363 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004364 if (MemberInit.isInvalid())
4365 return true;
4366
Douglas Gregor493627b2011-08-10 15:22:55 +00004367 if (Indirect)
4368 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4369 Indirect, Loc,
4370 Loc,
4371 MemberInit.get(),
4372 Loc);
4373 else
4374 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4375 Field, Loc, Loc,
4376 MemberInit.get(),
4377 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004378 return false;
4379 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004380
Alexis Hunt8b455182011-05-17 00:19:05 +00004381 if (!Field->getParent()->isUnion()) {
4382 if (FieldBaseElementType->isReferenceType()) {
4383 SemaRef.Diag(Constructor->getLocation(),
4384 diag::err_uninitialized_member_in_ctor)
4385 << (int)Constructor->isImplicit()
4386 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4387 << 0 << Field->getDeclName();
4388 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4389 return true;
4390 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004391
Alexis Hunt8b455182011-05-17 00:19:05 +00004392 if (FieldBaseElementType.isConstQualified()) {
4393 SemaRef.Diag(Constructor->getLocation(),
4394 diag::err_uninitialized_member_in_ctor)
4395 << (int)Constructor->isImplicit()
4396 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4397 << 1 << Field->getDeclName();
4398 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4399 return true;
4400 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004401 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004402
Brian Kelley036603a2017-03-29 17:31:42 +00004403 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4404 // ARC and Weak:
John McCall31168b02011-06-15 23:02:42 +00004405 // Default-initialize Objective-C pointers to NULL.
4406 CXXMemberInit
4407 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4408 Loc, Loc,
4409 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4410 Loc);
4411 return false;
4412 }
4413
Anders Carlsson3c1db572010-04-23 02:15:47 +00004414 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004415 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004416 return false;
4417}
John McCallbc83b3f2010-05-20 23:23:51 +00004418
4419namespace {
4420struct BaseAndFieldInfo {
4421 Sema &S;
4422 CXXConstructorDecl *Ctor;
4423 bool AnyErrorsInInits;
4424 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004425 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004426 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004427 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004428
4429 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4430 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004431 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004432 if (Ctor->getInheritedConstructor())
4433 IIK = IIK_Inherit;
4434 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004435 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004436 else if (Generated && Ctor->isMoveConstructor())
4437 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004438 else
4439 IIK = IIK_Default;
4440 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004441
4442 bool isImplicitCopyOrMove() const {
4443 switch (IIK) {
4444 case IIK_Copy:
4445 case IIK_Move:
4446 return true;
4447
4448 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004449 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004450 return false;
4451 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004452
4453 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004454 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004455
4456 bool addFieldInitializer(CXXCtorInitializer *Init) {
4457 AllToInit.push_back(Init);
4458
4459 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004460 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004461 S.UnusedPrivateFields.remove(Init->getAnyMember());
4462
4463 return false;
4464 }
John McCallbc83b3f2010-05-20 23:23:51 +00004465
Richard Smithab44d5b2013-12-10 08:25:00 +00004466 bool isInactiveUnionMember(FieldDecl *Field) {
4467 RecordDecl *Record = Field->getParent();
4468 if (!Record->isUnion())
4469 return false;
4470
Richard Smith8d183852013-12-10 20:56:03 +00004471 if (FieldDecl *Active =
4472 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004473 return Active != Field->getCanonicalDecl();
4474
4475 // In an implicit copy or move constructor, ignore any in-class initializer.
4476 if (isImplicitCopyOrMove())
4477 return true;
4478
4479 // If there's no explicit initialization, the field is active only if it
4480 // has an in-class initializer...
4481 if (Field->hasInClassInitializer())
4482 return false;
4483 // ... or it's an anonymous struct or union whose class has an in-class
4484 // initializer.
4485 if (!Field->isAnonymousStructOrUnion())
4486 return true;
4487 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4488 return !FieldRD->hasInClassInitializer();
4489 }
4490
4491 /// \brief Determine whether the given field is, or is within, a union member
4492 /// that is inactive (because there was an initializer given for a different
4493 /// member of the union, or because the union was not initialized at all).
4494 bool isWithinInactiveUnionMember(FieldDecl *Field,
4495 IndirectFieldDecl *Indirect) {
4496 if (!Indirect)
4497 return isInactiveUnionMember(Field);
4498
Aaron Ballman29c94602014-03-07 18:36:15 +00004499 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004500 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004501 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004502 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004503 }
4504 return false;
4505 }
4506};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004507}
Richard Smithc94ec842011-09-19 13:34:43 +00004508
Douglas Gregor10f939c2011-11-02 23:04:16 +00004509/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4510/// array type.
4511static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4512 if (T->isIncompleteArrayType())
4513 return true;
4514
4515 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4516 if (!ArrayT->getSize())
4517 return true;
4518
4519 T = ArrayT->getElementType();
4520 }
4521
4522 return false;
4523}
4524
Richard Smith938f40b2011-06-11 17:19:42 +00004525static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004526 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004527 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004528 if (Field->isInvalidDecl())
4529 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004530
Chandler Carruth139e9622010-06-30 02:59:29 +00004531 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004532 if (CXXCtorInitializer *Init =
4533 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004534 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004535
Richard Smithab44d5b2013-12-10 08:25:00 +00004536 // C++11 [class.base.init]p8:
4537 // if the entity is a non-static data member that has a
4538 // brace-or-equal-initializer and either
4539 // -- the constructor's class is a union and no other variant member of that
4540 // union is designated by a mem-initializer-id or
4541 // -- the constructor's class is not a union, and, if the entity is a member
4542 // of an anonymous union, no other member of that union is designated by
4543 // a mem-initializer-id,
4544 // the entity is initialized as specified in [dcl.init].
4545 //
4546 // We also apply the same rules to handle anonymous structs within anonymous
4547 // unions.
4548 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4549 return false;
4550
Douglas Gregor7db3e952011-11-28 20:03:15 +00004551 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004552 ExprResult DIE =
4553 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4554 if (DIE.isInvalid())
4555 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004556 CXXCtorInitializer *Init;
4557 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004558 Init = new (SemaRef.Context)
4559 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4560 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004561 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004562 Init = new (SemaRef.Context)
4563 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4564 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004565 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004566 }
4567
Douglas Gregor10f939c2011-11-02 23:04:16 +00004568 // Don't initialize incomplete or zero-length arrays.
4569 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4570 return false;
4571
John McCallbc83b3f2010-05-20 23:23:51 +00004572 // Don't try to build an implicit initializer if there were semantic
4573 // errors in any of the initializers (and therefore we might be
4574 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004575 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004576 return false;
4577
Craig Topperc3ec1492014-05-26 06:22:03 +00004578 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004579 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4580 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004581 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004582
Richard Smith0a8cfc72012-08-07 21:30:42 +00004583 if (!Init)
4584 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004585
Richard Smith0a8cfc72012-08-07 21:30:42 +00004586 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004587}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004588
4589bool
4590Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4591 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004592 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004593 Constructor->setNumCtorInitializers(1);
4594 CXXCtorInitializer **initializer =
4595 new (Context) CXXCtorInitializer*[1];
4596 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4597 Constructor->setCtorInitializers(initializer);
4598
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004599 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004600 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004601 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4602 }
4603
Alexis Hunte2622992011-05-05 00:05:47 +00004604 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004605
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004606 DiagnoseUninitializedFields(*this, Constructor);
4607
Alexis Hunt61bc1732011-05-01 07:04:31 +00004608 return false;
4609}
Douglas Gregor493627b2011-08-10 15:22:55 +00004610
David Blaikie3fc2f912013-01-17 05:26:25 +00004611bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4612 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004613 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004614 // Just store the initializers as written, they will be checked during
4615 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004616 if (!Initializers.empty()) {
4617 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004618 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004619 new (Context) CXXCtorInitializer*[Initializers.size()];
4620 memcpy(baseOrMemberInitializers, Initializers.data(),
4621 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004622 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004623 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004624
4625 // Let template instantiation know whether we had errors.
4626 if (AnyErrors)
4627 Constructor->setInvalidDecl();
4628
Anders Carlssondb0a9652010-04-02 06:26:44 +00004629 return false;
4630 }
4631
John McCallbc83b3f2010-05-20 23:23:51 +00004632 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004633
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004634 // We need to build the initializer AST according to order of construction
4635 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004636 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004637 if (!ClassDecl)
4638 return true;
4639
Eli Friedman9cf6b592009-11-09 19:20:36 +00004640 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004641
David Blaikie3fc2f912013-01-17 05:26:25 +00004642 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004643 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004644
Anders Carlssondb0a9652010-04-02 06:26:44 +00004645 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004646 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004647 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004648 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004649
4650 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004651 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004652 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004653 if (FD && FD->getParent()->isUnion())
4654 Info.ActiveUnionMember.insert(std::make_pair(
4655 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4656 }
4657 } else if (FieldDecl *FD = Member->getMember()) {
4658 if (FD->getParent()->isUnion())
4659 Info.ActiveUnionMember.insert(std::make_pair(
4660 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4661 }
4662 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004663 }
4664
Anders Carlsson43c64af2010-04-21 19:52:01 +00004665 // Keep track of the direct virtual bases.
4666 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004667 for (auto &I : ClassDecl->bases()) {
4668 if (I.isVirtual())
4669 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004670 }
4671
Anders Carlssondb0a9652010-04-02 06:26:44 +00004672 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004673 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004674 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004675 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004676 // [class.base.init]p7, per DR257:
4677 // A mem-initializer where the mem-initializer-id names a virtual base
4678 // class is ignored during execution of a constructor of any class that
4679 // is not the most derived class.
4680 if (ClassDecl->isAbstract()) {
4681 // FIXME: Provide a fixit to remove the base specifier. This requires
4682 // tracking the location of the associated comma for a base specifier.
4683 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004684 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004685 DiagnoseAbstractType(ClassDecl);
4686 }
4687
John McCallbc83b3f2010-05-20 23:23:51 +00004688 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004689 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4690 // [class.base.init]p8, per DR257:
4691 // If a given [...] base class is not named by a mem-initializer-id
4692 // [...] and the entity is not a virtual base class of an abstract
4693 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004694 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004695 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004696 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004697 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004698 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004699 HadError = true;
4700 continue;
4701 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004702
John McCallbc83b3f2010-05-20 23:23:51 +00004703 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004704 }
4705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
John McCallbc83b3f2010-05-20 23:23:51 +00004707 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004708 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004709 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004710 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004711 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004712
Alexis Hunt1d792652011-01-08 20:30:50 +00004713 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004714 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004715 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004716 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004717 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004718 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004719 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004720 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004721 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004722 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004723 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004724
John McCallbc83b3f2010-05-20 23:23:51 +00004725 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004726 }
4727 }
Mike Stump11289f42009-09-09 15:08:12 +00004728
John McCallbc83b3f2010-05-20 23:23:51 +00004729 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004730 for (auto *Mem : ClassDecl->decls()) {
4731 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004732 // C++ [class.bit]p2:
4733 // A declaration for a bit-field that omits the identifier declares an
4734 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4735 // initialized.
4736 if (F->isUnnamedBitfield())
4737 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004738
Sebastian Redl22653ba2011-08-30 19:58:05 +00004739 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004740 // handle anonymous struct/union fields based on their individual
4741 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004742 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004743 continue;
4744
4745 if (CollectFieldInitializer(*this, Info, F))
4746 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004747 continue;
4748 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004749
4750 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004751 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004752 continue;
4753
Aaron Ballman629afae2014-03-07 19:56:05 +00004754 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004755 if (F->getType()->isIncompleteArrayType()) {
4756 assert(ClassDecl->hasFlexibleArrayMember() &&
4757 "Incomplete array type is not valid");
4758 continue;
4759 }
4760
Douglas Gregor493627b2011-08-10 15:22:55 +00004761 // Initialize each field of an anonymous struct individually.
4762 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4763 HadError = true;
4764
4765 continue;
4766 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004767 }
Mike Stump11289f42009-09-09 15:08:12 +00004768
David Blaikie3fc2f912013-01-17 05:26:25 +00004769 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004770 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004771 Constructor->setNumCtorInitializers(NumInitializers);
4772 CXXCtorInitializer **baseOrMemberInitializers =
4773 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004774 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004775 NumInitializers * sizeof(CXXCtorInitializer*));
4776 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004777
John McCalla6309952010-03-16 21:39:52 +00004778 // Constructors implicitly reference the base and member
4779 // destructors.
4780 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4781 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004782 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004783
4784 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004785}
4786
David Blaikieb61b8152013-01-17 08:49:22 +00004787static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004788 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004789 const RecordDecl *RD = RT->getDecl();
4790 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004791 for (auto *Field : RD->fields())
4792 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004793 return;
4794 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004795 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004796 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004797}
4798
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004799static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4800 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004801}
4802
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004803static const void *GetKeyForMember(ASTContext &Context,
4804 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004805 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004806 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004807
Richard Smithcd45dbc2014-04-19 03:48:30 +00004808 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004809}
4810
David Blaikie3fc2f912013-01-17 05:26:25 +00004811static void DiagnoseBaseOrMemInitializerOrder(
4812 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4813 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004814 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004815 return;
Mike Stump11289f42009-09-09 15:08:12 +00004816
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004817 // Don't check initializers order unless the warning is enabled at the
4818 // location of at least one initializer.
4819 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004820 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004821 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004822 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4823 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004824 ShouldCheckOrder = true;
4825 break;
4826 }
4827 }
4828 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004829 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004830
John McCallbb7b6582010-04-10 07:37:23 +00004831 // Build the list of bases and members in the order that they'll
4832 // actually be initialized. The explicit initializers should be in
4833 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004834 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004835
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004836 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4837
John McCallbb7b6582010-04-10 07:37:23 +00004838 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004839 for (const auto &VBase : ClassDecl->vbases())
4840 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004841
John McCallbb7b6582010-04-10 07:37:23 +00004842 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004843 for (const auto &Base : ClassDecl->bases()) {
4844 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004845 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004846 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848
John McCallbb7b6582010-04-10 07:37:23 +00004849 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004850 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004851 if (Field->isUnnamedBitfield())
4852 continue;
4853
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004854 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004855 }
4856
John McCallbb7b6582010-04-10 07:37:23 +00004857 unsigned NumIdealInits = IdealInitKeys.size();
4858 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004859
Craig Topperc3ec1492014-05-26 06:22:03 +00004860 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004861 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004862 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004863 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004864
4865 // Scan forward to try to find this initializer in the idealized
4866 // initializers list.
4867 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4868 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004869 break;
John McCallbb7b6582010-04-10 07:37:23 +00004870
4871 // If we didn't find this initializer, it must be because we
4872 // scanned past it on a previous iteration. That can only
4873 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004874 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004875 Sema::SemaDiagnosticBuilder D =
4876 SemaRef.Diag(PrevInit->getSourceLocation(),
4877 diag::warn_initializer_out_of_order);
4878
Francois Pichetd583da02010-12-04 09:14:42 +00004879 if (PrevInit->isAnyMemberInitializer())
4880 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004881 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004882 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004883
Francois Pichetd583da02010-12-04 09:14:42 +00004884 if (Init->isAnyMemberInitializer())
4885 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004886 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004887 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004888
4889 // Move back to the initializer's location in the ideal list.
4890 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4891 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004892 break;
John McCallbb7b6582010-04-10 07:37:23 +00004893
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004894 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004895 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004896 }
John McCallbb7b6582010-04-10 07:37:23 +00004897
4898 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004899 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004900}
4901
John McCall23eebd92010-04-10 09:28:51 +00004902namespace {
4903bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004904 CXXCtorInitializer *Init,
4905 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004906 if (!PrevInit) {
4907 PrevInit = Init;
4908 return false;
4909 }
4910
Douglas Gregorea306a12013-03-25 23:28:23 +00004911 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004912 S.Diag(Init->getSourceLocation(),
4913 diag::err_multiple_mem_initialization)
4914 << Field->getDeclName()
4915 << Init->getSourceRange();
4916 else {
John McCall424cec92011-01-19 06:33:43 +00004917 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004918 assert(BaseClass && "neither field nor base");
4919 S.Diag(Init->getSourceLocation(),
4920 diag::err_multiple_base_initialization)
4921 << QualType(BaseClass, 0)
4922 << Init->getSourceRange();
4923 }
4924 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4925 << 0 << PrevInit->getSourceRange();
4926
4927 return true;
4928}
4929
Alexis Hunt1d792652011-01-08 20:30:50 +00004930typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004931typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4932
4933bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004934 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004935 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004936 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004937 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004938 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004939
4940 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004941 if (Parent->isUnion()) {
4942 UnionEntry &En = Unions[Parent];
4943 if (En.first && En.first != Child) {
4944 S.Diag(Init->getSourceLocation(),
4945 diag::err_multiple_mem_union_initialization)
4946 << Field->getDeclName()
4947 << Init->getSourceRange();
4948 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4949 << 0 << En.second->getSourceRange();
4950 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004951 }
4952 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004953 En.first = Child;
4954 En.second = Init;
4955 }
David Blaikie0f65d592011-11-17 06:01:57 +00004956 if (!Parent->isAnonymousStructOrUnion())
4957 return false;
John McCall23eebd92010-04-10 09:28:51 +00004958 }
4959
4960 Child = Parent;
4961 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004962 }
John McCall23eebd92010-04-10 09:28:51 +00004963
4964 return false;
4965}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004966}
John McCall23eebd92010-04-10 09:28:51 +00004967
Anders Carlssone857b292010-04-02 03:37:03 +00004968/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004969void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004970 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004971 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004972 bool AnyErrors) {
4973 if (!ConstructorDecl)
4974 return;
4975
4976 AdjustDeclIfTemplate(ConstructorDecl);
4977
4978 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004979 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004980
4981 if (!Constructor) {
4982 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4983 return;
4984 }
4985
John McCall23eebd92010-04-10 09:28:51 +00004986 // Mapping for the duplicate initializers check.
4987 // For member initializers, this is keyed with a FieldDecl*.
4988 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004989 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004990
4991 // Mapping for the inconsistent anonymous-union initializers check.
4992 RedundantUnionMap MemberUnions;
4993
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004994 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004995 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004996 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004997
Abramo Bagnara341d7832010-05-26 18:09:23 +00004998 // Set the source order index.
4999 Init->setSourceOrder(i);
5000
Francois Pichetd583da02010-12-04 09:14:42 +00005001 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005002 const void *Key = GetKeyForMember(Context, Init);
5003 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005004 CheckRedundantUnionInit(*this, Init, MemberUnions))
5005 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005006 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005007 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005008 if (CheckRedundantInit(*this, Init, Members[Key]))
5009 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005010 } else {
5011 assert(Init->isDelegatingInitializer());
5012 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005013 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005014 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005015 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005016 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005017 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005018 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005019 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005020 // Return immediately as the initializer is set.
5021 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005022 }
Anders Carlssone857b292010-04-02 03:37:03 +00005023 }
5024
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005025 if (HadError)
5026 return;
5027
David Blaikie3fc2f912013-01-17 05:26:25 +00005028 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005029
David Blaikie3fc2f912013-01-17 05:26:25 +00005030 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005031
Richard Trieuef64e942013-10-25 00:56:00 +00005032 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005033}
5034
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005035void
John McCalla6309952010-03-16 21:39:52 +00005036Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5037 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005038 // Ignore dependent contexts. Also ignore unions, since their members never
5039 // have destructors implicitly called.
5040 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005041 return;
John McCall1064d7e2010-03-16 05:22:47 +00005042
5043 // FIXME: all the access-control diagnostics are positioned on the
5044 // field/base declaration. That's probably good; that said, the
5045 // user might reasonably want to know why the destructor is being
5046 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005047
Anders Carlssondee9a302009-11-17 04:44:12 +00005048 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005049 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005050 if (Field->isInvalidDecl())
5051 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005052
5053 // Don't destroy incomplete or zero-length arrays.
5054 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5055 continue;
5056
Anders Carlssondee9a302009-11-17 04:44:12 +00005057 QualType FieldType = Context.getBaseElementType(Field->getType());
5058
5059 const RecordType* RT = FieldType->getAs<RecordType>();
5060 if (!RT)
5061 continue;
5062
5063 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005064 if (FieldClassDecl->isInvalidDecl())
5065 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005066 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005067 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005068 // The destructor for an implicit anonymous union member is never invoked.
5069 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5070 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005071
Douglas Gregore71edda2010-07-01 22:47:18 +00005072 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005073 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005074 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005075 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005076 << Field->getDeclName()
5077 << FieldType);
5078
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005079 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005080 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005081 }
5082
Richard Smithdf054d32017-02-25 23:53:05 +00005083 // We only potentially invoke the destructors of potentially constructed
5084 // subobjects.
5085 bool VisitVirtualBases = !ClassDecl->isAbstract();
5086
John McCall1064d7e2010-03-16 05:22:47 +00005087 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5088
Anders Carlssondee9a302009-11-17 04:44:12 +00005089 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005090 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005091 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005092 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005093
5094 // Remember direct virtual bases.
Richard Smithdf054d32017-02-25 23:53:05 +00005095 if (Base.isVirtual()) {
5096 if (!VisitVirtualBases)
5097 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005098 DirectVirtualBases.insert(RT);
Richard Smithdf054d32017-02-25 23:53:05 +00005099 }
Anders Carlssondee9a302009-11-17 04:44:12 +00005100
John McCall1064d7e2010-03-16 05:22:47 +00005101 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005102 // If our base class is invalid, we probably can't get its dtor anyway.
5103 if (BaseClassDecl->isInvalidDecl())
5104 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005105 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005106 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005107
Douglas Gregore71edda2010-07-01 22:47:18 +00005108 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005109 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005110
5111 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005112 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005113 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005114 << Base.getType()
5115 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005116 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005117
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005118 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005119 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005120 }
Richard Smithdf054d32017-02-25 23:53:05 +00005121
5122 if (!VisitVirtualBases)
5123 return;
Anders Carlssondee9a302009-11-17 04:44:12 +00005124
5125 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005126 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005127 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005128 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005129
5130 // Ignore direct virtual bases.
5131 if (DirectVirtualBases.count(RT))
5132 continue;
5133
John McCall1064d7e2010-03-16 05:22:47 +00005134 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005135 // If our base class is invalid, we probably can't get its dtor anyway.
5136 if (BaseClassDecl->isInvalidDecl())
5137 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005138 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005139 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005140
Douglas Gregore71edda2010-07-01 22:47:18 +00005141 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005142 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005143 if (CheckDestructorAccess(
5144 ClassDecl->getLocation(), Dtor,
5145 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005146 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005147 Context.getTypeDeclType(ClassDecl)) ==
5148 AR_accessible) {
5149 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005150 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005151 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005152 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005153 }
John McCall1064d7e2010-03-16 05:22:47 +00005154
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005155 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005156 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005157 }
5158}
5159
John McCall48871652010-08-21 09:40:31 +00005160void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005161 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005162 return;
Mike Stump11289f42009-09-09 15:08:12 +00005163
Mike Stump11289f42009-09-09 15:08:12 +00005164 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005165 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005166 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005167 DiagnoseUninitializedFields(*this, Constructor);
5168 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005169}
5170
Richard Smithdb0ac552015-12-18 22:40:25 +00005171bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005172 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005173 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005174
Richard Smithdb0ac552015-12-18 22:40:25 +00005175 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5176 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005177 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005178
Richard Smithdb0ac552015-12-18 22:40:25 +00005179 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5180 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005181
John McCall02db245d2010-08-18 09:41:07 +00005182 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005183 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005184 // over all the declarations when we have a full definition.
5185 const CXXRecordDecl *Def = RD->getDefinition();
5186 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005187 return false;
5188
Richard Smithdb0ac552015-12-18 22:40:25 +00005189 return RD->isAbstract();
5190}
5191
5192bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5193 TypeDiagnoser &Diagnoser) {
5194 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005195 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005196
Richard Smithdb0ac552015-12-18 22:40:25 +00005197 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005198 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005199 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005200 return true;
5201}
5202
5203void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5204 // Check if we've already emitted the list of pure virtual functions
5205 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005206 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005207 return;
Mike Stump11289f42009-09-09 15:08:12 +00005208
Richard Smithbc46e432013-07-22 02:56:56 +00005209 // If the diagnostic is suppressed, don't emit the notes. We're only
5210 // going to emit them once, so try to attach them to a diagnostic we're
5211 // actually going to show.
5212 if (Diags.isLastDiagnosticIgnored())
5213 return;
5214
Douglas Gregor4165bd62010-03-23 23:47:56 +00005215 CXXFinalOverriderMap FinalOverriders;
5216 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005217
Anders Carlssona2f74f32010-06-03 01:00:02 +00005218 // Keep a set of seen pure methods so we won't diagnose the same method
5219 // more than once.
5220 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5221
Douglas Gregor4165bd62010-03-23 23:47:56 +00005222 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5223 MEnd = FinalOverriders.end();
5224 M != MEnd;
5225 ++M) {
5226 for (OverridingMethods::iterator SO = M->second.begin(),
5227 SOEnd = M->second.end();
5228 SO != SOEnd; ++SO) {
5229 // C++ [class.abstract]p4:
5230 // A class is abstract if it contains or inherits at least one
5231 // pure virtual function for which the final overrider is pure
5232 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005233
Douglas Gregor4165bd62010-03-23 23:47:56 +00005234 //
5235 if (SO->second.size() != 1)
5236 continue;
5237
5238 if (!SO->second.front().Method->isPure())
5239 continue;
5240
David Blaikie82e95a32014-11-19 07:49:47 +00005241 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005242 continue;
5243
Douglas Gregor4165bd62010-03-23 23:47:56 +00005244 Diag(SO->second.front().Method->getLocation(),
5245 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005246 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005247 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005248 }
5249
5250 if (!PureVirtualClassDiagSet)
5251 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5252 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005253}
5254
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005255namespace {
John McCall02db245d2010-08-18 09:41:07 +00005256struct AbstractUsageInfo {
5257 Sema &S;
5258 CXXRecordDecl *Record;
5259 CanQualType AbstractType;
5260 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005261
John McCall02db245d2010-08-18 09:41:07 +00005262 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5263 : S(S), Record(Record),
5264 AbstractType(S.Context.getCanonicalType(
5265 S.Context.getTypeDeclType(Record))),
5266 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005267
John McCall02db245d2010-08-18 09:41:07 +00005268 void DiagnoseAbstractType() {
5269 if (Invalid) return;
5270 S.DiagnoseAbstractType(Record);
5271 Invalid = true;
5272 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005273
John McCall02db245d2010-08-18 09:41:07 +00005274 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5275};
5276
5277struct CheckAbstractUsage {
5278 AbstractUsageInfo &Info;
5279 const NamedDecl *Ctx;
5280
5281 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5282 : Info(Info), Ctx(Ctx) {}
5283
5284 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5285 switch (TL.getTypeLocClass()) {
5286#define ABSTRACT_TYPELOC(CLASS, PARENT)
5287#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005288 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005289#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005290 }
John McCall02db245d2010-08-18 09:41:07 +00005291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCall02db245d2010-08-18 09:41:07 +00005293 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005294 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005295 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5296 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005297 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005298
5299 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005300 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005301 }
John McCall02db245d2010-08-18 09:41:07 +00005302 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005303
John McCall02db245d2010-08-18 09:41:07 +00005304 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5305 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5306 }
Mike Stump11289f42009-09-09 15:08:12 +00005307
John McCall02db245d2010-08-18 09:41:07 +00005308 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5309 // Visit the type parameters from a permissive context.
5310 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5311 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5312 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5313 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5314 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5315 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005316 }
John McCall02db245d2010-08-18 09:41:07 +00005317 }
Mike Stump11289f42009-09-09 15:08:12 +00005318
John McCall02db245d2010-08-18 09:41:07 +00005319 // Visit pointee types from a permissive context.
5320#define CheckPolymorphic(Type) \
5321 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5322 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5323 }
5324 CheckPolymorphic(PointerTypeLoc)
5325 CheckPolymorphic(ReferenceTypeLoc)
5326 CheckPolymorphic(MemberPointerTypeLoc)
5327 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005328 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005329
John McCall02db245d2010-08-18 09:41:07 +00005330 /// Handle all the types we haven't given a more specific
5331 /// implementation for above.
5332 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5333 // Every other kind of type that we haven't called out already
5334 // that has an inner type is either (1) sugar or (2) contains that
5335 // inner type in some way as a subobject.
5336 if (TypeLoc Next = TL.getNextTypeLoc())
5337 return Visit(Next, Sel);
5338
5339 // If there's no inner type and we're in a permissive context,
5340 // don't diagnose.
5341 if (Sel == Sema::AbstractNone) return;
5342
5343 // Check whether the type matches the abstract type.
5344 QualType T = TL.getType();
5345 if (T->isArrayType()) {
5346 Sel = Sema::AbstractArrayType;
5347 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005348 }
John McCall02db245d2010-08-18 09:41:07 +00005349 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5350 if (CT != Info.AbstractType) return;
5351
5352 // It matched; do some magic.
5353 if (Sel == Sema::AbstractArrayType) {
5354 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5355 << T << TL.getSourceRange();
5356 } else {
5357 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5358 << Sel << T << TL.getSourceRange();
5359 }
5360 Info.DiagnoseAbstractType();
5361 }
5362};
5363
5364void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5365 Sema::AbstractDiagSelID Sel) {
5366 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5367}
5368
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005369}
John McCall02db245d2010-08-18 09:41:07 +00005370
5371/// Check for invalid uses of an abstract type in a method declaration.
5372static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5373 CXXMethodDecl *MD) {
5374 // No need to do the check on definitions, which require that
5375 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005376 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005377 return;
5378
5379 // For safety's sake, just ignore it if we don't have type source
5380 // information. This should never happen for non-implicit methods,
5381 // but...
5382 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5383 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5384}
5385
5386/// Check for invalid uses of an abstract type within a class definition.
5387static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5388 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005389 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005390 if (D->isImplicit()) continue;
5391
5392 // Methods and method templates.
5393 if (isa<CXXMethodDecl>(D)) {
5394 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5395 } else if (isa<FunctionTemplateDecl>(D)) {
5396 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5397 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5398
5399 // Fields and static variables.
5400 } else if (isa<FieldDecl>(D)) {
5401 FieldDecl *FD = cast<FieldDecl>(D);
5402 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5403 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5404 } else if (isa<VarDecl>(D)) {
5405 VarDecl *VD = cast<VarDecl>(D);
5406 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5407 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5408
5409 // Nested classes and class templates.
5410 } else if (isa<CXXRecordDecl>(D)) {
5411 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5412 } else if (isa<ClassTemplateDecl>(D)) {
5413 CheckAbstractClassUsage(Info,
5414 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5415 }
5416 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005417}
5418
Hans Wennborg99000c22015-08-15 01:18:16 +00005419static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5420 Attr *ClassAttr = getDLLAttr(Class);
5421 if (!ClassAttr)
5422 return;
5423
5424 assert(ClassAttr->getKind() == attr::DLLExport);
5425
5426 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5427
5428 if (TSK == TSK_ExplicitInstantiationDeclaration)
5429 // Don't go any further if this is just an explicit instantiation
5430 // declaration.
5431 return;
5432
5433 for (Decl *Member : Class->decls()) {
5434 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5435 if (!MD)
5436 continue;
5437
5438 if (Member->getAttr<DLLExportAttr>()) {
5439 if (MD->isUserProvided()) {
5440 // Instantiate non-default class member functions ...
5441
5442 // .. except for certain kinds of template specializations.
5443 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5444 continue;
5445
5446 S.MarkFunctionReferenced(Class->getLocation(), MD);
5447
5448 // The function will be passed to the consumer when its definition is
5449 // encountered.
5450 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5451 MD->isCopyAssignmentOperator() ||
5452 MD->isMoveAssignmentOperator()) {
5453 // Synthesize and instantiate non-trivial implicit methods, explicitly
5454 // defaulted methods, and the copy and move assignment operators. The
5455 // latter are exported even if they are trivial, because the address of
Simon Pilgrim2c518802017-03-30 14:13:19 +00005456 // an operator can be taken and should compare equal across libraries.
Hans Wennborg99000c22015-08-15 01:18:16 +00005457 DiagnosticErrorTrap Trap(S.Diags);
5458 S.MarkFunctionReferenced(Class->getLocation(), MD);
5459 if (Trap.hasErrorOccurred()) {
5460 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5461 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5462 break;
5463 }
5464
5465 // There is no later point when we will see the definition of this
5466 // function, so pass it to the consumer now.
5467 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5468 }
5469 }
5470 }
5471}
5472
Reid Kleckner82713bf2017-01-09 17:27:17 +00005473static void checkForMultipleExportedDefaultConstructors(Sema &S,
5474 CXXRecordDecl *Class) {
5475 // Only the MS ABI has default constructor closures, so we don't need to do
5476 // this semantic checking anywhere else.
5477 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5478 return;
5479
Reid Kleckner61195e12017-01-05 01:08:22 +00005480 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5481 for (Decl *Member : Class->decls()) {
5482 // Look for exported default constructors.
5483 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
Reid Kleckner82713bf2017-01-09 17:27:17 +00005484 if (!CD || !CD->isDefaultConstructor())
Reid Kleckner61195e12017-01-05 01:08:22 +00005485 continue;
Reid Kleckner82713bf2017-01-09 17:27:17 +00005486 auto *Attr = CD->getAttr<DLLExportAttr>();
5487 if (!Attr)
5488 continue;
5489
5490 // If the class is non-dependent, mark the default arguments as ODR-used so
5491 // that we can properly codegen the constructor closure.
5492 if (!Class->isDependentContext()) {
5493 for (ParmVarDecl *PD : CD->parameters()) {
5494 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5495 S.DiscardCleanupsInEvaluationContext();
5496 }
5497 }
Reid Kleckner61195e12017-01-05 01:08:22 +00005498
5499 if (LastExportedDefaultCtor) {
5500 S.Diag(LastExportedDefaultCtor->getLocation(),
5501 diag::err_attribute_dll_ambiguous_default_ctor)
5502 << Class;
5503 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5504 << CD->getDeclName();
5505 return;
5506 }
5507 LastExportedDefaultCtor = CD;
5508 }
5509}
5510
Hans Wennborg853ae942014-05-30 16:59:42 +00005511/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005512void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005513 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005514
5515 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005516 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005517 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5518 if (Attr *TemplateAttr =
5519 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005520 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005521 A->setInherited(true);
5522 ClassAttr = A;
5523 }
5524 }
5525 }
5526
Hans Wennborg853ae942014-05-30 16:59:42 +00005527 if (!ClassAttr)
5528 return;
5529
Hans Wennborg8313c762014-11-03 16:09:16 +00005530 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005531 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005532 << Class << ClassAttr;
5533 return;
5534 }
5535
Hans Wennborg17f9b442015-05-27 00:06:45 +00005536 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005537 !ClassAttr->isInherited()) {
5538 // Diagnose dll attributes on members of class with dll attribute.
5539 for (Decl *Member : Class->decls()) {
5540 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5541 continue;
5542 InheritableAttr *MemberAttr = getDLLAttr(Member);
5543 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5544 continue;
5545
Hans Wennborg17f9b442015-05-27 00:06:45 +00005546 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005547 diag::err_attribute_dll_member_of_dll_class)
5548 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005549 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005550 Member->setInvalidDecl();
5551 }
5552 }
5553
5554 if (Class->getDescribedClassTemplate())
5555 // Don't inherit dll attribute until the template is instantiated.
5556 return;
5557
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005558 // The class is either imported or exported.
5559 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005560
Hans Wennborgfd76d912015-01-15 21:18:30 +00005561 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5562
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005563 // Ignore explicit dllexport on explicit class template instantiation declarations.
5564 if (ClassExported && !ClassAttr->isInherited() &&
5565 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005566 Class->dropAttr<DLLExportAttr>();
5567 return;
5568 }
5569
Hans Wennborg853ae942014-05-30 16:59:42 +00005570 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005571 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005572
5573 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5574 // seem to be true in practice?
5575
Hans Wennborg853ae942014-05-30 16:59:42 +00005576 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005577 VarDecl *VD = dyn_cast<VarDecl>(Member);
5578 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5579
5580 // Only methods and static fields inherit the attributes.
5581 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005582 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005583
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005584 if (MD) {
5585 // Don't process deleted methods.
5586 if (MD->isDeleted())
5587 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005588
David Majnemer30f058a2015-05-11 03:00:22 +00005589 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005590 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005591 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5592 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005593 continue;
5594
Dmitry Polukhin41581522016-05-13 09:03:56 +00005595 // MSVC versions before 2015 don't export the move assignment operators
5596 // and move constructor, so don't attempt to import/export them if
5597 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005598 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005599 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005600 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005601 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005602 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005603
5604 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5605 // operator is exported anyway.
5606 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5607 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5608 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005609 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005610 }
5611
Hans Wennborg287231c2015-04-22 04:05:17 +00005612 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5613 continue;
5614
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005615 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005616 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005617 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005618 NewAttr->setInherited(true);
5619 Member->addAttr(NewAttr);
5620 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005621 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005622
5623 if (ClassExported)
5624 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005625}
5626
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005627/// \brief Perform propagation of DLL attributes from a derived class to a
5628/// templated base class for MS compatibility.
5629void Sema::propagateDLLAttrToBaseClassTemplate(
5630 CXXRecordDecl *Class, Attr *ClassAttr,
5631 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5632 if (getDLLAttr(
5633 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5634 // If the base class template has a DLL attribute, don't try to change it.
5635 return;
5636 }
5637
5638 auto TSK = BaseTemplateSpec->getSpecializationKind();
5639 if (!getDLLAttr(BaseTemplateSpec) &&
5640 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5641 TSK == TSK_ImplicitInstantiation)) {
5642 // The template hasn't been instantiated yet (or it has, but only as an
5643 // explicit instantiation declaration or implicit instantiation, which means
5644 // we haven't codegenned any members yet), so propagate the attribute.
5645 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5646 NewAttr->setInherited(true);
5647 BaseTemplateSpec->addAttr(NewAttr);
5648
5649 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5650 // needs to be run again to work see the new attribute. Otherwise this will
5651 // get run whenever the template is instantiated.
5652 if (TSK != TSK_Undeclared)
5653 checkClassLevelDLLAttribute(BaseTemplateSpec);
5654
5655 return;
5656 }
5657
5658 if (getDLLAttr(BaseTemplateSpec)) {
5659 // The template has already been specialized or instantiated with an
5660 // attribute, explicitly or through propagation. We should not try to change
5661 // it.
5662 return;
5663 }
5664
5665 // The template was previously instantiated or explicitly specialized without
5666 // a dll attribute, It's too late for us to add an attribute, so warn that
5667 // this is unsupported.
5668 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5669 << BaseTemplateSpec->isExplicitSpecialization();
5670 Diag(ClassAttr->getLocation(), diag::note_attribute);
5671 if (BaseTemplateSpec->isExplicitSpecialization()) {
5672 Diag(BaseTemplateSpec->getLocation(),
5673 diag::note_template_class_explicit_specialization_was_here)
5674 << BaseTemplateSpec;
5675 } else {
5676 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5677 diag::note_template_class_instantiation_was_here)
5678 << BaseTemplateSpec;
5679 }
5680}
5681
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005682static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5683 SourceLocation DefaultLoc) {
5684 switch (S.getSpecialMember(MD)) {
5685 case Sema::CXXDefaultConstructor:
5686 S.DefineImplicitDefaultConstructor(DefaultLoc,
5687 cast<CXXConstructorDecl>(MD));
5688 break;
5689 case Sema::CXXCopyConstructor:
5690 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5691 break;
5692 case Sema::CXXCopyAssignment:
5693 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5694 break;
5695 case Sema::CXXDestructor:
5696 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5697 break;
5698 case Sema::CXXMoveConstructor:
5699 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5700 break;
5701 case Sema::CXXMoveAssignment:
5702 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5703 break;
5704 case Sema::CXXInvalid:
5705 llvm_unreachable("Invalid special member.");
5706 }
5707}
5708
Douglas Gregorc99f1552009-12-03 18:33:45 +00005709/// \brief Perform semantic checks on a class definition that has been
5710/// completing, introducing implicitly-declared members, checking for
5711/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005712void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005713 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005714 return;
5715
John McCall02db245d2010-08-18 09:41:07 +00005716 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5717 AbstractUsageInfo Info(*this, Record);
5718 CheckAbstractClassUsage(Info, Record);
5719 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005720
5721 // If this is not an aggregate type and has no user-declared constructor,
5722 // complain about any non-static data members of reference or const scalar
5723 // type, since they will never get initializers.
5724 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005725 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5726 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005727 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005728 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005729 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005730 continue;
5731
Douglas Gregor454a5b62010-04-15 00:00:53 +00005732 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005733 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005734 if (!Complained) {
5735 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5736 << Record->getTagKind() << Record;
5737 Complained = true;
5738 }
5739
5740 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5741 << F->getType()->isReferenceType()
5742 << F->getDeclName();
5743 }
5744 }
5745 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005746
Douglas Gregor36c22a22010-10-15 13:21:21 +00005747 if (Record->getIdentifier()) {
5748 // C++ [class.mem]p13:
5749 // If T is the name of a class, then each of the following shall have a
5750 // name different from T:
5751 // - every member of every anonymous union that is a member of class T.
5752 //
5753 // C++ [class.mem]p14:
5754 // In addition, if class T has a user-declared constructor (12.1), every
5755 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005756 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5757 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5758 ++I) {
5759 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005760 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5761 isa<IndirectFieldDecl>(D)) {
5762 Diag(D->getLocation(), diag::err_member_name_of_class)
5763 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005764 break;
5765 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005766 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005767 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005768
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005769 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005770 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005771 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005772 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5773 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005774 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5775 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5776 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005777
David Majnemera5433082013-10-18 00:33:31 +00005778 if (Record->isAbstract()) {
5779 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5780 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5781 << FA->isSpelledAsSealed();
5782 DiagnoseAbstractType(Record);
5783 }
David Blaikie348df502012-09-21 03:21:07 +00005784 }
5785
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005786 bool HasMethodWithOverrideControl = false,
5787 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005788 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005789 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005790 // See if a method overloads virtual methods in a base
5791 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005792 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005793 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005794 if (M->hasAttr<OverrideAttr>())
5795 HasMethodWithOverrideControl = true;
5796 else if (M->size_overridden_methods() > 0)
5797 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005798 // Check whether the explicitly-defaulted special members are valid.
5799 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005800 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005801
5802 // For an explicitly defaulted or deleted special member, we defer
5803 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005804 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005805 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005806 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005807 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005808
5809 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005810 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005811 }
5812 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005813
5814 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5815 M->hasAttr<DLLExportAttr>()) {
5816 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5817 M->isTrivial() &&
5818 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5819 CSM == CXXDestructor))
5820 M->dropAttr<DLLExportAttr>();
5821
5822 if (M->hasAttr<DLLExportAttr>()) {
5823 DefineImplicitSpecialMember(*this, M, M->getLocation());
5824 ActOnFinishInlineFunctionDef(M);
5825 }
5826 }
Richard Smithbd305122012-12-11 01:14:52 +00005827 }
5828 }
5829
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005830 if (HasMethodWithOverrideControl &&
5831 HasOverridingMethodWithoutOverrideControl) {
5832 // At least one method has the 'override' control declared.
5833 // Diagnose all other overridden methods which do not have 'override' specified on them.
5834 for (auto *M : Record->methods())
5835 DiagnoseAbsenceOfOverrideControl(M);
5836 }
Sebastian Redl08905022011-02-05 19:23:19 +00005837
John McCall95833f32014-02-27 20:30:49 +00005838 // ms_struct is a request to use the same ABI rules as MSVC. Check
5839 // whether this class uses any C++ features that are implemented
5840 // completely differently in MSVC, and if so, emit a diagnostic.
5841 // That diagnostic defaults to an error, but we allow projects to
5842 // map it down to a warning (or ignore it). It's a fairly common
5843 // practice among users of the ms_struct pragma to mass-annotate
5844 // headers, sweeping up a bunch of types that the project doesn't
5845 // really rely on MSVC-compatible layout for. We must therefore
5846 // support "ms_struct except for C++ stuff" as a secondary ABI.
5847 if (Record->isMsStruct(Context) &&
5848 (Record->isPolymorphic() || Record->getNumBases())) {
5849 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005850 }
5851
Hans Wennborg17f9b442015-05-27 00:06:45 +00005852 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005853}
5854
Richard Smith41c35d62013-11-27 03:39:20 +00005855/// Look up the special member function that would be called by a special
5856/// member function for a subobject of class type.
5857///
5858/// \param Class The class type of the subobject.
5859/// \param CSM The kind of special member function.
5860/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5861/// \param ConstRHS True if this is a copy operation with a const object
5862/// on its RHS, that is, if the argument to the outer special member
5863/// function is 'const' and this is not a field marked 'mutable'.
Richard Smith8bae1be2017-02-24 02:07:20 +00005864static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
Richard Smith41c35d62013-11-27 03:39:20 +00005865 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5866 unsigned FieldQuals, bool ConstRHS) {
5867 unsigned LHSQuals = 0;
5868 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5869 LHSQuals = FieldQuals;
5870
5871 unsigned RHSQuals = FieldQuals;
5872 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5873 RHSQuals = 0;
5874 else if (ConstRHS)
5875 RHSQuals |= Qualifiers::Const;
5876
5877 return S.LookupSpecialMember(Class, CSM,
5878 RHSQuals & Qualifiers::Const,
5879 RHSQuals & Qualifiers::Volatile,
5880 false,
5881 LHSQuals & Qualifiers::Const,
5882 LHSQuals & Qualifiers::Volatile);
5883}
5884
Richard Smith80a47022016-06-29 01:10:27 +00005885class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005886 Sema &S;
5887 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005888
5889 /// A mapping from the base classes through which the constructor was
5890 /// inherited to the using shadow declaration in that base class (or a null
5891 /// pointer if the constructor was declared in that base class).
5892 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5893 InheritedFromBases;
5894
Richard Smith80a47022016-06-29 01:10:27 +00005895public:
Richard Smith5179eb72016-06-28 19:03:57 +00005896 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5897 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005898 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005899 bool DiagnosedMultipleConstructedBases = false;
5900 CXXRecordDecl *ConstructedBase = nullptr;
5901 UsingDecl *ConstructedBaseUsing = nullptr;
5902
5903 // Find the set of such base class subobjects and check that there's a
5904 // unique constructed subobject.
5905 for (auto *D : Shadow->redecls()) {
5906 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5907 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5908 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5909
5910 InheritedFromBases.insert(
5911 std::make_pair(DNominatedBase->getCanonicalDecl(),
5912 DShadow->getNominatedBaseClassShadowDecl()));
5913 if (DShadow->constructsVirtualBase())
5914 InheritedFromBases.insert(
5915 std::make_pair(DConstructedBase->getCanonicalDecl(),
5916 DShadow->getConstructedBaseClassShadowDecl()));
5917 else
5918 assert(DNominatedBase == DConstructedBase);
5919
5920 // [class.inhctor.init]p2:
5921 // If the constructor was inherited from multiple base class subobjects
5922 // of type B, the program is ill-formed.
5923 if (!ConstructedBase) {
5924 ConstructedBase = DConstructedBase;
5925 ConstructedBaseUsing = D->getUsingDecl();
5926 } else if (ConstructedBase != DConstructedBase &&
5927 !Shadow->isInvalidDecl()) {
5928 if (!DiagnosedMultipleConstructedBases) {
5929 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5930 << Shadow->getTargetDecl();
5931 S.Diag(ConstructedBaseUsing->getLocation(),
5932 diag::note_ambiguous_inherited_constructor_using)
5933 << ConstructedBase;
5934 DiagnosedMultipleConstructedBases = true;
5935 }
5936 S.Diag(D->getUsingDecl()->getLocation(),
5937 diag::note_ambiguous_inherited_constructor_using)
5938 << DConstructedBase;
5939 }
5940 }
5941
5942 if (DiagnosedMultipleConstructedBases)
5943 Shadow->setInvalidDecl();
5944 }
5945
5946 /// Find the constructor to use for inherited construction of a base class,
5947 /// and whether that base class constructor inherits the constructor from a
5948 /// virtual base class (in which case it won't actually invoke it).
5949 std::pair<CXXConstructorDecl *, bool>
5950 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5951 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5952 if (It == InheritedFromBases.end())
5953 return std::make_pair(nullptr, false);
5954
5955 // This is an intermediary class.
5956 if (It->second)
5957 return std::make_pair(
5958 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5959 It->second->constructsVirtualBase());
5960
5961 // This is the base class from which the constructor was inherited.
5962 return std::make_pair(Ctor, false);
5963 }
5964};
Richard Smith5179eb72016-06-28 19:03:57 +00005965
Richard Smithb5800092012-06-10 05:43:50 +00005966/// Is the special member function which would be selected to perform the
5967/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005968static bool
5969specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5970 Sema::CXXSpecialMember CSM, unsigned Quals,
5971 bool ConstRHS,
5972 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005973 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005974 // If we're inheriting a constructor, see if we need to call it for this base
5975 // class.
5976 if (InheritedCtor) {
5977 assert(CSM == Sema::CXXDefaultConstructor);
5978 auto BaseCtor =
5979 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5980 if (BaseCtor)
5981 return BaseCtor->isConstexpr();
5982 }
5983
5984 if (CSM == Sema::CXXDefaultConstructor)
5985 return ClassDecl->hasConstexprDefaultConstructor();
5986
Richard Smith8bae1be2017-02-24 02:07:20 +00005987 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005988 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith8bae1be2017-02-24 02:07:20 +00005989 if (!SMOR.getMethod())
Richard Smithb5800092012-06-10 05:43:50 +00005990 // A constructor we wouldn't select can't be "involved in initializing"
5991 // anything.
5992 return true;
Richard Smith8bae1be2017-02-24 02:07:20 +00005993 return SMOR.getMethod()->isConstexpr();
Richard Smithb5800092012-06-10 05:43:50 +00005994}
5995
5996/// Determine whether the specified special member function would be constexpr
5997/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005998static bool defaultedSpecialMemberIsConstexpr(
5999 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6000 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00006001 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006002 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00006003 return false;
6004
6005 // C++11 [dcl.constexpr]p4:
6006 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00006007 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00006008 switch (CSM) {
6009 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00006010 if (Inherited)
6011 break;
Richard Smith4086a132012-06-10 07:07:24 +00006012 // Since default constructor lookup is essentially trivial (and cannot
6013 // involve, for instance, template instantiation), we compute whether a
6014 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6015 //
6016 // This is important for performance; we need to know whether the default
6017 // constructor is constexpr to determine whether the type is a literal type.
6018 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6019
Richard Smithb5800092012-06-10 05:43:50 +00006020 case Sema::CXXCopyConstructor:
6021 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00006022 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00006023 break;
6024
6025 case Sema::CXXCopyAssignment:
6026 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006027 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00006028 return false;
6029 // In C++1y, we need to perform overload resolution.
6030 Ctor = false;
6031 break;
6032
Richard Smithb5800092012-06-10 05:43:50 +00006033 case Sema::CXXDestructor:
6034 case Sema::CXXInvalid:
6035 return false;
6036 }
6037
6038 // -- if the class is a non-empty union, or for each non-empty anonymous
6039 // union member of a non-union class, exactly one non-static data member
6040 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00006041 //
6042 // If we squint, this is guaranteed, since exactly one non-static data member
6043 // will be initialized (if the constructor isn't deleted), we just don't know
6044 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006045 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006046 return CSM == Sema::CXXDefaultConstructor
6047 ? ClassDecl->hasInClassInitializer() ||
6048 !ClassDecl->hasVariantMembers()
6049 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006050
6051 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006052 if (Ctor && ClassDecl->getNumVBases())
6053 return false;
6054
6055 // C++1y [class.copy]p26:
6056 // -- [the class] is a literal type, and
6057 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006058 return false;
6059
6060 // -- every constructor involved in initializing [...] base class
6061 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006062 // -- the assignment operator selected to copy/move each direct base
6063 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006064 for (const auto &B : ClassDecl->bases()) {
6065 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006066 if (!BaseType) continue;
6067
6068 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006069 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6070 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006071 return false;
6072 }
6073
6074 // -- every constructor involved in initializing non-static data members
6075 // [...] shall be a constexpr constructor;
6076 // -- every non-static data member and base class sub-object shall be
6077 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006078 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006079 // thereof), the assignment operator selected to copy/move that member is
6080 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006081 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006082 if (F->isInvalidDecl())
6083 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006084 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6085 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006086 QualType BaseType = S.Context.getBaseElementType(F->getType());
6087 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006088 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006089 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6090 BaseType.getCVRQualifiers(),
6091 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006092 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006093 } else if (CSM == Sema::CXXDefaultConstructor) {
6094 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006095 }
6096 }
6097
6098 // All OK, it's constexpr!
6099 return true;
6100}
6101
Richard Smithd3b5c9082012-07-27 04:22:15 +00006102static Sema::ImplicitExceptionSpecification
Richard Smith2246c832017-02-24 01:29:42 +00006103ComputeDefaultedSpecialMemberExceptionSpec(
6104 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6105 Sema::InheritedConstructorInfo *ICI);
6106
6107static Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00006108computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
Richard Smith55118002017-02-24 01:36:58 +00006109 auto CSM = S.getSpecialMember(MD);
6110 if (CSM != Sema::CXXInvalid)
6111 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
Richard Smith2246c832017-02-24 01:29:42 +00006112
6113 auto *CD = cast<CXXConstructorDecl>(MD);
6114 assert(CD->getInheritedConstructor() &&
Richard Smithc2bc61b2013-03-18 21:12:30 +00006115 "only special members have implicit exception specs");
Richard Smith2246c832017-02-24 01:29:42 +00006116 Sema::InheritedConstructorInfo ICI(
6117 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6118 return ComputeDefaultedSpecialMemberExceptionSpec(
6119 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006120}
6121
Reid Kleckner78af0702013-08-27 23:08:25 +00006122static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6123 CXXMethodDecl *MD) {
6124 FunctionProtoType::ExtProtoInfo EPI;
6125
6126 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006127 EPI.ExceptionSpec.Type = EST_Unevaluated;
6128 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006129
6130 // Set the calling convention to the default for C++ instance methods.
6131 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6132 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6133 /*IsCXXMethod=*/true));
6134 return EPI;
6135}
6136
Richard Smithd3b5c9082012-07-27 04:22:15 +00006137void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6138 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6139 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6140 return;
6141
Richard Smith7f782272012-07-30 23:48:14 +00006142 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006143 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6144 auto ESI = IES.getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006145
Richard Smith7f782272012-07-30 23:48:14 +00006146 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006147 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006148
6149 // A user-provided destructor can be defined outside the class. When that
6150 // happens, be sure to update the exception specification on both
6151 // declarations.
6152 const FunctionProtoType *CanonicalFPT =
6153 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6154 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006155 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006156}
6157
Richard Smithb9e90b12012-05-15 04:39:51 +00006158void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6159 CXXRecordDecl *RD = MD->getParent();
6160 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006161
Richard Smithb9e90b12012-05-15 04:39:51 +00006162 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6163 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006164
6165 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006166 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006167 bool First = MD == MD->getCanonicalDecl();
6168
6169 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006170
6171 // C++11 [dcl.fct.def.default]p1:
6172 // A function that is explicitly defaulted shall
6173 // -- be a special member function (checked elsewhere),
6174 // -- have the same type (except for ref-qualifiers, and except that a
6175 // copy operation can take a non-const reference) as an implicit
6176 // declaration, and
6177 // -- not have default arguments.
6178 unsigned ExpectedParams = 1;
6179 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6180 ExpectedParams = 0;
6181 if (MD->getNumParams() != ExpectedParams) {
6182 // This also checks for default arguments: a copy or move constructor with a
6183 // default argument is classified as a default constructor, and assignment
6184 // operations and destructors can't have default arguments.
6185 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6186 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006187 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006188 } else if (MD->isVariadic()) {
6189 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6190 << CSM << MD->getSourceRange();
6191 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006192 }
6193
Richard Smithb9e90b12012-05-15 04:39:51 +00006194 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006195
Richard Smithb5800092012-06-10 05:43:50 +00006196 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006197 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006198 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006199 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006200 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006201
Richard Smithb9e90b12012-05-15 04:39:51 +00006202 QualType ReturnType = Context.VoidTy;
6203 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6204 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006205 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006206 QualType ExpectedReturnType =
6207 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6208 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6209 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6210 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6211 HadError = true;
6212 }
6213
6214 // A defaulted special member cannot have cv-qualifiers.
6215 if (Type->getTypeQuals()) {
6216 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006217 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006218 HadError = true;
6219 }
6220 }
6221
6222 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006223 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006224 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006225 if (ExpectedParams && ArgType->isReferenceType()) {
6226 // Argument must be reference to possibly-const T.
6227 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006228 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006229
6230 if (ReferentType.isVolatileQualified()) {
6231 Diag(MD->getLocation(),
6232 diag::err_defaulted_special_member_volatile_param) << CSM;
6233 HadError = true;
6234 }
6235
Richard Smithb5800092012-06-10 05:43:50 +00006236 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006237 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6238 Diag(MD->getLocation(),
6239 diag::err_defaulted_special_member_copy_const_param)
6240 << (CSM == CXXCopyAssignment);
6241 // FIXME: Explain why this special member can't be const.
6242 } else {
6243 Diag(MD->getLocation(),
6244 diag::err_defaulted_special_member_move_const_param)
6245 << (CSM == CXXMoveAssignment);
6246 }
6247 HadError = true;
6248 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006249 } else if (ExpectedParams) {
6250 // A copy assignment operator can take its argument by value, but a
6251 // defaulted one cannot.
6252 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006253 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006254 HadError = true;
6255 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006256
Richard Smithcc36f692011-12-22 02:22:31 +00006257 // C++11 [dcl.fct.def.default]p2:
6258 // An explicitly-defaulted function may be declared constexpr only if it
6259 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006260 // Do not apply this rule to members of class templates, since core issue 1358
6261 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006262 // functions which cannot be constexpr (for non-constructors in C++11 and for
6263 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006264 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6265 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006266 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006267 : isa<CXXConstructorDecl>(MD)) &&
6268 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006269 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6270 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006271 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006272 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006273 }
Richard Smithbd305122012-12-11 01:14:52 +00006274
Richard Smithcc36f692011-12-22 02:22:31 +00006275 // and may have an explicit exception-specification only if it is compatible
6276 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006277 if (Type->hasExceptionSpec()) {
6278 // Delay the check if this is the first declaration of the special member,
6279 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006280 if (First) {
6281 // If the exception specification needs to be instantiated, do so now,
6282 // before we clobber it with an EST_Unevaluated specification below.
6283 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6284 InstantiateExceptionSpec(MD->getLocStart(), MD);
6285 Type = MD->getType()->getAs<FunctionProtoType>();
6286 }
Richard Smithbd305122012-12-11 01:14:52 +00006287 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006288 } else
Richard Smithbd305122012-12-11 01:14:52 +00006289 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6290 }
Richard Smithcc36f692011-12-22 02:22:31 +00006291
6292 // If a function is explicitly defaulted on its first declaration,
6293 if (First) {
6294 // -- it is implicitly considered to be constexpr if the implicit
6295 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006296 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006297
Richard Smithb9e90b12012-05-15 04:39:51 +00006298 // -- it is implicitly considered to have the same exception-specification
6299 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006300 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006301 EPI.ExceptionSpec.Type = EST_Unevaluated;
6302 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006303 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006304 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006305 ExpectedParams),
6306 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006307 }
6308
Richard Smithb9e90b12012-05-15 04:39:51 +00006309 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006310 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006311 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006312 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006313 // C++11 [dcl.fct.def.default]p4:
6314 // [For a] user-provided explicitly-defaulted function [...] if such a
6315 // function is implicitly defined as deleted, the program is ill-formed.
6316 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006317 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006318 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006319 }
6320 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006321
Richard Smithb9e90b12012-05-15 04:39:51 +00006322 if (HadError)
6323 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006324}
6325
Richard Smithbd305122012-12-11 01:14:52 +00006326/// Check whether the exception specification provided for an
6327/// explicitly-defaulted special member matches the exception specification
6328/// that would have been generated for an implicit special member, per
6329/// C++11 [dcl.fct.def.default]p2.
6330void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6331 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006332 // If the exception specification was explicitly specified but hadn't been
6333 // parsed when the method was defaulted, grab it now.
6334 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6335 SpecifiedType =
6336 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6337
Richard Smithbd305122012-12-11 01:14:52 +00006338 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006339 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6340 /*IsCXXMethod=*/true);
6341 FunctionProtoType::ExtProtoInfo EPI(CC);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006342 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6343 EPI.ExceptionSpec = IES.getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006344 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006345 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006346
6347 // Ensure that it matches.
6348 CheckEquivalentExceptionSpec(
6349 PDiag(diag::err_incorrect_defaulted_exception_spec)
6350 << getSpecialMember(MD), PDiag(),
6351 ImplicitType, SourceLocation(),
6352 SpecifiedType, MD->getLocation());
6353}
6354
Alp Tokerae3a9442013-10-18 05:54:19 +00006355void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006356 decltype(DelayedExceptionSpecChecks) Checks;
6357 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006358
Richard Smith88f45492014-11-22 03:09:05 +00006359 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006360 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6361
6362 // Perform any deferred checking of exception specifications for virtual
6363 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006364 for (auto &Check : Checks)
6365 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006366
6367 // Check that any explicitly-defaulted methods have exception specifications
6368 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006369 for (auto &Spec : Specs)
6370 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006371}
6372
Richard Smithd951a1d2012-02-18 02:02:13 +00006373namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +00006374/// CRTP base class for visiting operations performed by a special member
6375/// function (or inherited constructor).
6376template<typename Derived>
6377struct SpecialMemberVisitor {
Richard Smithd951a1d2012-02-18 02:02:13 +00006378 Sema &S;
6379 CXXMethodDecl *MD;
6380 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006381 Sema::InheritedConstructorInfo *ICI;
Richard Smith8bae1be2017-02-24 02:07:20 +00006382
Richard Smith6f0e63e2017-02-24 21:18:47 +00006383 // Properties of the special member, computed for convenience.
6384 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
Richard Smith8bae1be2017-02-24 02:07:20 +00006385
6386 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6387 Sema::InheritedConstructorInfo *ICI)
6388 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006389 switch (CSM) {
6390 case Sema::CXXDefaultConstructor:
6391 case Sema::CXXCopyConstructor:
6392 case Sema::CXXMoveConstructor:
6393 IsConstructor = true;
6394 break;
6395 case Sema::CXXCopyAssignment:
6396 case Sema::CXXMoveAssignment:
6397 IsAssignment = true;
6398 break;
6399 case Sema::CXXDestructor:
6400 break;
6401 case Sema::CXXInvalid:
6402 llvm_unreachable("invalid special member kind");
6403 }
6404
Richard Smith8bae1be2017-02-24 02:07:20 +00006405 if (MD->getNumParams()) {
6406 if (const ReferenceType *RT =
6407 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6408 ConstArg = RT->getPointeeType().isConstQualified();
6409 }
6410 }
6411
Richard Smith6f0e63e2017-02-24 21:18:47 +00006412 Derived &getDerived() { return static_cast<Derived&>(*this); }
6413
6414 /// Is this a "move" special member?
6415 bool isMove() const {
6416 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6417 }
6418
Richard Smith8bae1be2017-02-24 02:07:20 +00006419 /// Look up the corresponding special member in the given class.
6420 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6421 unsigned Quals, bool IsMutable) {
6422 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6423 ConstArg && !IsMutable);
6424 }
6425
Richard Smith6f0e63e2017-02-24 21:18:47 +00006426 /// Look up the constructor for the specified base class to see if it's
6427 /// overridden due to this being an inherited constructor.
6428 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6429 if (!ICI)
6430 return {};
6431 assert(CSM == Sema::CXXDefaultConstructor);
6432 auto *BaseCtor =
6433 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6434 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6435 return MD;
6436 return {};
6437 }
6438
Richard Smith8bae1be2017-02-24 02:07:20 +00006439 /// A base or member subobject.
6440 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6441
Richard Smith6f0e63e2017-02-24 21:18:47 +00006442 /// Get the location to use for a subobject in diagnostics.
Richard Smith8bae1be2017-02-24 02:07:20 +00006443 static SourceLocation getSubobjectLoc(Subobject Subobj) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006444 // FIXME: For an indirect virtual base, the direct base leading to
6445 // the indirect virtual base would be a more useful choice.
Richard Smith8bae1be2017-02-24 02:07:20 +00006446 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6447 return B->getBaseTypeLoc();
6448 else
6449 return Subobj.get<FieldDecl*>()->getLocation();
6450 }
6451
Richard Smith6f0e63e2017-02-24 21:18:47 +00006452 enum BasesToVisit {
6453 /// Visit all non-virtual (direct) bases.
6454 VisitNonVirtualBases,
6455 /// Visit all direct bases, virtual or not.
6456 VisitDirectBases,
6457 /// Visit all non-virtual bases, and all virtual bases if the class
6458 /// is not abstract.
6459 VisitPotentiallyConstructedBases,
6460 /// Visit all direct or virtual bases.
6461 VisitAllBases
6462 };
6463
6464 // Visit the bases and members of the class.
6465 bool visit(BasesToVisit Bases) {
6466 CXXRecordDecl *RD = MD->getParent();
6467
6468 if (Bases == VisitPotentiallyConstructedBases)
6469 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6470
6471 for (auto &B : RD->bases())
6472 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6473 getDerived().visitBase(&B))
6474 return true;
6475
6476 if (Bases == VisitAllBases)
6477 for (auto &B : RD->vbases())
6478 if (getDerived().visitBase(&B))
6479 return true;
6480
6481 for (auto *F : RD->fields())
6482 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6483 getDerived().visitField(F))
6484 return true;
6485
6486 return false;
6487 }
Richard Smith8bae1be2017-02-24 02:07:20 +00006488};
6489}
6490
6491namespace {
6492struct SpecialMemberDeletionInfo
6493 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
Richard Smith852265f2012-03-30 20:53:28 +00006494 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006495
Richard Smithd951a1d2012-02-18 02:02:13 +00006496 SourceLocation Loc;
6497
6498 bool AllFieldsAreConst;
6499
6500 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006501 Sema::CXXSpecialMember CSM,
6502 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
Richard Smith8bae1be2017-02-24 02:07:20 +00006503 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
Richard Smith6f0e63e2017-02-24 21:18:47 +00006504 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
Richard Smithd951a1d2012-02-18 02:02:13 +00006505
6506 bool inUnion() const { return MD->getParent()->isUnion(); }
6507
Richard Smith80a47022016-06-29 01:10:27 +00006508 Sema::CXXSpecialMember getEffectiveCSM() {
6509 return ICI ? Sema::CXXInvalid : CSM;
6510 }
6511
Richard Smith6f0e63e2017-02-24 21:18:47 +00006512 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6513 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6514
Richard Smith852265f2012-03-30 20:53:28 +00006515 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006516 bool shouldDeleteForField(FieldDecl *FD);
6517 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006518
Richard Smithaf136f82012-07-18 03:51:16 +00006519 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6520 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006521 bool shouldDeleteForSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +00006522 Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006523 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006524
6525 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006526};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006527}
Richard Smithd951a1d2012-02-18 02:02:13 +00006528
John McCalld4274212012-04-09 20:53:23 +00006529/// Is the given special member inaccessible when used on the given
6530/// sub-object.
6531bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6532 CXXMethodDecl *target) {
6533 /// If we're operating on a base class, the object type is the
6534 /// type of this special member.
6535 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006536 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006537 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6538 objectTy = S.Context.getTypeDeclType(MD->getParent());
6539 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6540
6541 // If we're operating on a field, the object type is the type of the field.
6542 } else {
6543 objectTy = S.Context.getTypeDeclType(target->getParent());
6544 }
6545
6546 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6547}
6548
Richard Smith852265f2012-03-30 20:53:28 +00006549/// Check whether we should delete a special member due to the implicit
6550/// definition containing a call to a special member of a subobject.
6551bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +00006552 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006553 bool IsDtorCallInCtor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006554 CXXMethodDecl *Decl = SMOR.getMethod();
Richard Smith852265f2012-03-30 20:53:28 +00006555 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6556
6557 int DiagKind = -1;
6558
Richard Smith8bae1be2017-02-24 02:07:20 +00006559 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
Richard Smith852265f2012-03-30 20:53:28 +00006560 DiagKind = !Decl ? 0 : 1;
Richard Smith8bae1be2017-02-24 02:07:20 +00006561 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith852265f2012-03-30 20:53:28 +00006562 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006563 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006564 DiagKind = 3;
6565 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6566 !Decl->isTrivial()) {
6567 // A member of a union must have a trivial corresponding special member.
6568 // As a weird special case, a destructor call from a union's constructor
6569 // must be accessible and non-deleted, but need not be trivial. Such a
6570 // destructor is never actually called, but is semantically checked as
6571 // if it were.
6572 DiagKind = 4;
6573 }
6574
6575 if (DiagKind == -1)
6576 return false;
6577
6578 if (Diagnose) {
6579 if (Field) {
6580 S.Diag(Field->getLocation(),
6581 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006582 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006583 << Field << DiagKind << IsDtorCallInCtor;
6584 } else {
6585 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6586 S.Diag(Base->getLocStart(),
6587 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006588 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006589 << Base->getType() << DiagKind << IsDtorCallInCtor;
6590 }
6591
6592 if (DiagKind == 1)
6593 S.NoteDeletedFunction(Decl);
6594 // FIXME: Explain inaccessibility if DiagKind == 3.
6595 }
6596
6597 return true;
6598}
6599
Richard Smith921bd202012-02-26 09:11:52 +00006600/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006601/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006602bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006603 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006604 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006605 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006606
6607 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006608 // -- any direct or virtual base class, or non-static data member with no
6609 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006610 // either M has no default constructor or overload resolution as applied
6611 // to M's default constructor results in an ambiguity or in a function
6612 // that is deleted or inaccessible
6613 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6614 // -- a direct or virtual base class B that cannot be copied/moved because
6615 // overload resolution, as applied to B's corresponding special member,
6616 // results in an ambiguity or a function that is deleted or inaccessible
6617 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006618 // C++11 [class.dtor]p5:
6619 // -- any direct or virtual base class [...] has a type with a destructor
6620 // that is deleted or inaccessible
6621 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006622 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006623 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6624 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006625 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006626
Richard Smith852265f2012-03-30 20:53:28 +00006627 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6628 // -- any direct or virtual base class or non-static data member has a
6629 // type with a destructor that is deleted or inaccessible
6630 if (IsConstructor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006631 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith852265f2012-03-30 20:53:28 +00006632 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6633 false, false, false, false, false);
6634 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6635 return true;
6636 }
6637
Richard Smith921bd202012-02-26 09:11:52 +00006638 return false;
6639}
6640
6641/// Check whether we should delete a special member function due to the class
6642/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006643bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006644 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006645 // If program is correct, BaseClass cannot be null, but if it is, the error
6646 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006647 if (!BaseClass)
6648 return false;
6649 // If we have an inheriting constructor, check whether we're calling an
6650 // inherited constructor instead of a default constructor.
Richard Smith6f0e63e2017-02-24 21:18:47 +00006651 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6652 if (auto *BaseCtor = SMOR.getMethod()) {
6653 // Note that we do not check access along this path; other than that,
6654 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6655 // FIXME: Check that the base has a usable destructor! Sink this into
6656 // shouldDeleteForClassSubobject.
6657 if (BaseCtor->isDeleted() && Diagnose) {
6658 S.Diag(Base->getLocStart(),
6659 diag::note_deleted_special_member_class_subobject)
6660 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6661 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6662 S.NoteDeletedFunction(BaseCtor);
Richard Smith80a47022016-06-29 01:10:27 +00006663 }
Richard Smith6f0e63e2017-02-24 21:18:47 +00006664 return BaseCtor->isDeleted();
Richard Smith80a47022016-06-29 01:10:27 +00006665 }
6666 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006667}
6668
6669/// Check whether we should delete a special member function due to the class
6670/// having a particular non-static data member.
6671bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6672 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6673 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6674
6675 if (CSM == Sema::CXXDefaultConstructor) {
6676 // For a default constructor, all references must be initialized in-class
6677 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006678 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6679 if (Diagnose)
6680 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006681 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006682 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006683 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006684 // C++11 [class.ctor]p5: any non-variant non-static data member of
6685 // const-qualified type (or array thereof) with no
6686 // brace-or-equal-initializer does not have a user-provided default
6687 // constructor.
6688 if (!inUnion() && FieldType.isConstQualified() &&
6689 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006690 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6691 if (Diagnose)
6692 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006693 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006694 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006695 }
6696
6697 if (inUnion() && !FieldType.isConstQualified())
6698 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006699 } else if (CSM == Sema::CXXCopyConstructor) {
6700 // For a copy constructor, data members must not be of rvalue reference
6701 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006702 if (FieldType->isRValueReferenceType()) {
6703 if (Diagnose)
6704 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6705 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006706 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006707 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006708 } else if (IsAssignment) {
6709 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006710 if (FieldType->isReferenceType()) {
6711 if (Diagnose)
6712 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006713 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006714 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006715 }
6716 if (!FieldRecord && FieldType.isConstQualified()) {
6717 // C++11 [class.copy]p23:
6718 // -- a non-static data member of const non-class type (or array thereof)
6719 if (Diagnose)
6720 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006721 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006722 return true;
6723 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006724 }
6725
6726 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006727 // Some additional restrictions exist on the variant members.
6728 if (!inUnion() && FieldRecord->isUnion() &&
6729 FieldRecord->isAnonymousStructOrUnion()) {
6730 bool AllVariantFieldsAreConst = true;
6731
Richard Smith5704fe82012-03-29 19:00:10 +00006732 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006733 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006734 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006735
6736 if (!UnionFieldType.isConstQualified())
6737 AllVariantFieldsAreConst = false;
6738
Richard Smith921bd202012-02-26 09:11:52 +00006739 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6740 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006741 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006742 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006743 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006744 }
6745
6746 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006747 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006748 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006749 if (Diagnose)
6750 S.Diag(FieldRecord->getLocation(),
6751 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006752 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006753 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006754 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006755
Richard Smith5704fe82012-03-29 19:00:10 +00006756 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006757 // This is technically non-conformant, but sanity demands it.
6758 return false;
6759 }
6760
Richard Smithaf136f82012-07-18 03:51:16 +00006761 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6762 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006763 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006764 }
6765
6766 return false;
6767}
6768
6769/// C++11 [class.ctor] p5:
6770/// A defaulted default constructor for a class X is defined as deleted if
6771/// X is a union and all of its variant members are of const-qualified type.
6772bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006773 // This is a silly definition, because it gives an empty union a deleted
6774 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006775 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6776 bool AnyFields = false;
6777 for (auto *F : MD->getParent()->fields())
6778 if ((AnyFields = !F->isUnnamedBitfield()))
6779 break;
6780 if (!AnyFields)
6781 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006782 if (Diagnose)
6783 S.Diag(MD->getParent()->getLocation(),
6784 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006785 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006786 return true;
6787 }
6788 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006789}
6790
6791/// Determine whether a defaulted special member function should be defined as
6792/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6793/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006794bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006795 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006796 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006797 if (MD->isInvalidDecl())
6798 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006799 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006800 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006801 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006802 return false;
6803
Richard Smithd951a1d2012-02-18 02:02:13 +00006804 // C++11 [expr.lambda.prim]p19:
6805 // The closure type associated with a lambda-expression has a
6806 // deleted (8.4.3) default constructor and a deleted copy
6807 // assignment operator.
6808 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006809 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6810 if (Diagnose)
6811 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006812 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006813 }
6814
Richard Smith6f1e2c62012-04-02 20:59:25 +00006815 // For an anonymous struct or union, the copy and assignment special members
6816 // will never be used, so skip the check. For an anonymous union declared at
6817 // namespace scope, the constructor and destructor are used.
6818 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6819 RD->isAnonymousStructOrUnion())
6820 return false;
6821
Richard Smith852265f2012-03-30 20:53:28 +00006822 // C++11 [class.copy]p7, p18:
6823 // If the class definition declares a move constructor or move assignment
6824 // operator, an implicitly declared copy constructor or copy assignment
6825 // operator is defined as deleted.
6826 if (MD->isImplicit() &&
6827 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006828 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006829
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006830 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6831 // deletion of the corresponding copy operation, not both copy operations.
6832 // MSVC 2015 has adopted the standards conforming behavior.
6833 bool DeletesOnlyMatchingCopy =
6834 getLangOpts().MSVCCompat &&
6835 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6836
Richard Smith852265f2012-03-30 20:53:28 +00006837 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006838 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006839 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006840
6841 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006842 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006843 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006844 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006845 break;
6846 }
6847 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006848 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006849 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006850 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006851 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006852
6853 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006854 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006855 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006856 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006857 break;
6858 }
6859 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006860 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006861 }
6862
6863 if (UserDeclaredMove) {
6864 Diag(UserDeclaredMove->getLocation(),
6865 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006866 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006867 << UserDeclaredMove->isMoveAssignmentOperator();
6868 return true;
6869 }
6870 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006871
Richard Smith6f1e2c62012-04-02 20:59:25 +00006872 // Do access control from the special member function
6873 ContextRAII MethodContext(*this, MD);
6874
Richard Smith921bd202012-02-26 09:11:52 +00006875 // C++11 [class.dtor]p5:
6876 // -- for a virtual destructor, lookup of the non-array deallocation function
6877 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006878 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006879 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006880 DeclarationName Name =
6881 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6882 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006883 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006884 if (Diagnose)
6885 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006886 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006887 }
Richard Smith921bd202012-02-26 09:11:52 +00006888 }
6889
Richard Smith80a47022016-06-29 01:10:27 +00006890 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006891
Richard Smithd1627032013-07-22 18:06:23 +00006892 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smithdf054d32017-02-25 23:53:05 +00006893 // classes, since we are not going to construct them.
6894 // Per DR1658, do not consider virtual bases of destructors of abstract
6895 // classes either.
6896 // Per DR2180, for assignment operators we only assign (and thus only
6897 // consider) direct bases.
6898 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6899 : SMI.VisitPotentiallyConstructedBases))
Richard Smith6f0e63e2017-02-24 21:18:47 +00006900 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006901
Richard Smithd951a1d2012-02-18 02:02:13 +00006902 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006903 return true;
6904
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006905 if (getLangOpts().CUDA) {
6906 // We should delete the special member in CUDA mode if target inference
6907 // failed.
6908 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6909 Diagnose);
6910 }
6911
Alexis Huntea6f0322011-05-11 22:34:38 +00006912 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006913}
6914
Richard Smith92f241f2012-12-08 02:53:02 +00006915/// Perform lookup for a special member of the specified kind, and determine
6916/// whether it is trivial. If the triviality can be determined without the
6917/// lookup, skip it. This is intended for use when determining whether a
6918/// special member of a containing object is trivial, and thus does not ever
6919/// perform overload resolution for default constructors.
6920///
6921/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6922/// member that was most likely to be intended to be trivial, if any.
6923static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6924 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006925 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006926 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006927 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006928
6929 switch (CSM) {
6930 case Sema::CXXInvalid:
6931 llvm_unreachable("not a special member");
6932
6933 case Sema::CXXDefaultConstructor:
6934 // C++11 [class.ctor]p5:
6935 // A default constructor is trivial if:
6936 // - all the [direct subobjects] have trivial default constructors
6937 //
6938 // Note, no overload resolution is performed in this case.
6939 if (RD->hasTrivialDefaultConstructor())
6940 return true;
6941
6942 if (Selected) {
6943 // If there's a default constructor which could have been trivial, dig it
6944 // out. Otherwise, if there's any user-provided default constructor, point
6945 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006946 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006947 if (RD->needsImplicitDefaultConstructor())
6948 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006949 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006950 if (!CI->isDefaultConstructor())
6951 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006952 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006953 if (!DefCtor->isUserProvided())
6954 break;
6955 }
6956
6957 *Selected = DefCtor;
6958 }
6959
6960 return false;
6961
6962 case Sema::CXXDestructor:
6963 // C++11 [class.dtor]p5:
6964 // A destructor is trivial if:
6965 // - all the direct [subobjects] have trivial destructors
6966 if (RD->hasTrivialDestructor())
6967 return true;
6968
6969 if (Selected) {
6970 if (RD->needsImplicitDestructor())
6971 S.DeclareImplicitDestructor(RD);
6972 *Selected = RD->getDestructor();
6973 }
6974
6975 return false;
6976
6977 case Sema::CXXCopyConstructor:
6978 // C++11 [class.copy]p12:
6979 // A copy constructor is trivial if:
6980 // - the constructor selected to copy each direct [subobject] is trivial
6981 if (RD->hasTrivialCopyConstructor()) {
6982 if (Quals == Qualifiers::Const)
6983 // We must either select the trivial copy constructor or reach an
6984 // ambiguity; no need to actually perform overload resolution.
6985 return true;
6986 } else if (!Selected) {
6987 return false;
6988 }
6989 // In C++98, we are not supposed to perform overload resolution here, but we
6990 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6991 // cases like B as having a non-trivial copy constructor:
6992 // struct A { template<typename T> A(T&); };
6993 // struct B { mutable A a; };
6994 goto NeedOverloadResolution;
6995
6996 case Sema::CXXCopyAssignment:
6997 // C++11 [class.copy]p25:
6998 // A copy assignment operator is trivial if:
6999 // - the assignment operator selected to copy each direct [subobject] is
7000 // trivial
7001 if (RD->hasTrivialCopyAssignment()) {
7002 if (Quals == Qualifiers::Const)
7003 return true;
7004 } else if (!Selected) {
7005 return false;
7006 }
7007 // In C++98, we are not supposed to perform overload resolution here, but we
7008 // treat that as a language defect.
7009 goto NeedOverloadResolution;
7010
7011 case Sema::CXXMoveConstructor:
7012 case Sema::CXXMoveAssignment:
7013 NeedOverloadResolution:
Richard Smith8bae1be2017-02-24 02:07:20 +00007014 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00007015 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00007016
7017 // The standard doesn't describe how to behave if the lookup is ambiguous.
7018 // We treat it as not making the member non-trivial, just like the standard
7019 // mandates for the default constructor. This should rarely matter, because
7020 // the member will also be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +00007021 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith92f241f2012-12-08 02:53:02 +00007022 return true;
7023
Richard Smith8bae1be2017-02-24 02:07:20 +00007024 if (!SMOR.getMethod()) {
7025 assert(SMOR.getKind() ==
Richard Smith92f241f2012-12-08 02:53:02 +00007026 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7027 return false;
7028 }
7029
7030 // We deliberately don't check if we found a deleted special member. We're
7031 // not supposed to!
7032 if (Selected)
Richard Smith8bae1be2017-02-24 02:07:20 +00007033 *Selected = SMOR.getMethod();
7034 return SMOR.getMethod()->isTrivial();
Richard Smith92f241f2012-12-08 02:53:02 +00007035 }
7036
7037 llvm_unreachable("unknown special method kind");
7038}
7039
Benjamin Kramer3e350262013-02-15 12:30:38 +00007040static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007041 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00007042 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007043 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00007044
7045 // Look for constructor templates.
7046 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7047 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7048 if (CXXConstructorDecl *CD =
7049 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7050 return CD;
7051 }
7052
Craig Topperc3ec1492014-05-26 06:22:03 +00007053 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00007054}
7055
7056/// The kind of subobject we are checking for triviality. The values of this
7057/// enumeration are used in diagnostics.
7058enum TrivialSubobjectKind {
7059 /// The subobject is a base class.
7060 TSK_BaseClass,
7061 /// The subobject is a non-static data member.
7062 TSK_Field,
7063 /// The object is actually the complete object.
7064 TSK_CompleteObject
7065};
7066
7067/// Check whether the special member selected for a given type would be trivial.
7068static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00007069 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00007070 Sema::CXXSpecialMember CSM,
7071 TrivialSubobjectKind Kind,
7072 bool Diagnose) {
7073 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7074 if (!SubRD)
7075 return true;
7076
7077 CXXMethodDecl *Selected;
7078 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007079 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00007080 return true;
7081
7082 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00007083 if (ConstRHS)
7084 SubType.addConst();
7085
Richard Smith92f241f2012-12-08 02:53:02 +00007086 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7087 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7088 << Kind << SubType.getUnqualifiedType();
7089 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7090 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7091 } else if (!Selected)
7092 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7093 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7094 else if (Selected->isUserProvided()) {
7095 if (Kind == TSK_CompleteObject)
7096 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7097 << Kind << SubType.getUnqualifiedType() << CSM;
7098 else {
7099 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7100 << Kind << SubType.getUnqualifiedType() << CSM;
7101 S.Diag(Selected->getLocation(), diag::note_declared_at);
7102 }
7103 } else {
7104 if (Kind != TSK_CompleteObject)
7105 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7106 << Kind << SubType.getUnqualifiedType() << CSM;
7107
7108 // Explain why the defaulted or deleted special member isn't trivial.
7109 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7110 }
7111 }
7112
7113 return false;
7114}
7115
7116/// Check whether the members of a class type allow a special member to be
7117/// trivial.
7118static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7119 Sema::CXXSpecialMember CSM,
7120 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007121 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007122 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7123 continue;
7124
7125 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7126
7127 // Pretend anonymous struct or union members are members of this class.
7128 if (FI->isAnonymousStructOrUnion()) {
7129 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7130 CSM, ConstArg, Diagnose))
7131 return false;
7132 continue;
7133 }
7134
7135 // C++11 [class.ctor]p5:
7136 // A default constructor is trivial if [...]
7137 // -- no non-static data member of its class has a
7138 // brace-or-equal-initializer
7139 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7140 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007141 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007142 return false;
7143 }
7144
7145 // Objective C ARC 4.3.5:
7146 // [...] nontrivally ownership-qualified types are [...] not trivially
7147 // default constructible, copy constructible, move constructible, copy
7148 // assignable, move assignable, or destructible [...]
Brian Kelley762f9282017-03-29 18:16:38 +00007149 if (FieldType.hasNonTrivialObjCLifetime()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007150 if (Diagnose)
7151 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7152 << RD << FieldType.getObjCLifetime();
7153 return false;
7154 }
7155
Richard Smith41c35d62013-11-27 03:39:20 +00007156 bool ConstRHS = ConstArg && !FI->isMutable();
7157 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7158 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007159 return false;
7160 }
7161
7162 return true;
7163}
7164
7165/// Diagnose why the specified class does not have a trivial special member of
7166/// the given kind.
7167void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7168 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007169
Richard Smith41c35d62013-11-27 03:39:20 +00007170 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7171 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007172 TSK_CompleteObject, /*Diagnose*/true);
7173}
7174
7175/// Determine whether a defaulted or deleted special member function is trivial,
7176/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7177/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7178bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7179 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007180 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7181
7182 CXXRecordDecl *RD = MD->getParent();
7183
7184 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007185
Richard Smith2002bfe2013-11-04 02:02:27 +00007186 // C++11 [class.copy]p12, p25: [DR1593]
7187 // A [special member] is trivial if [...] its parameter-type-list is
7188 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007189 switch (CSM) {
7190 case CXXDefaultConstructor:
7191 case CXXDestructor:
7192 // Trivial default constructors and destructors cannot have parameters.
7193 break;
7194
7195 case CXXCopyConstructor:
7196 case CXXCopyAssignment: {
7197 // Trivial copy operations always have const, non-volatile parameter types.
7198 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007199 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007200 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7201 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7202 if (Diagnose)
7203 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7204 << Param0->getSourceRange() << Param0->getType()
7205 << Context.getLValueReferenceType(
7206 Context.getRecordType(RD).withConst());
7207 return false;
7208 }
7209 break;
7210 }
7211
7212 case CXXMoveConstructor:
7213 case CXXMoveAssignment: {
7214 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007215 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007216 const RValueReferenceType *RT =
7217 Param0->getType()->getAs<RValueReferenceType>();
7218 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7219 if (Diagnose)
7220 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7221 << Param0->getSourceRange() << Param0->getType()
7222 << Context.getRValueReferenceType(Context.getRecordType(RD));
7223 return false;
7224 }
7225 break;
7226 }
7227
7228 case CXXInvalid:
7229 llvm_unreachable("not a special member");
7230 }
7231
Richard Smith92f241f2012-12-08 02:53:02 +00007232 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7233 if (Diagnose)
7234 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7235 diag::note_nontrivial_default_arg)
7236 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7237 return false;
7238 }
7239 if (MD->isVariadic()) {
7240 if (Diagnose)
7241 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7242 return false;
7243 }
7244
7245 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7246 // A copy/move [constructor or assignment operator] is trivial if
7247 // -- the [member] selected to copy/move each direct base class subobject
7248 // is trivial
7249 //
7250 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7251 // A [default constructor or destructor] is trivial if
7252 // -- all the direct base classes have trivial [default constructors or
7253 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007254 for (const auto &BI : RD->bases())
7255 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007256 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007257 return false;
7258
7259 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7260 // A copy/move [constructor or assignment operator] for a class X is
7261 // trivial if
7262 // -- for each non-static data member of X that is of class type (or array
7263 // thereof), the constructor selected to copy/move that member is
7264 // trivial
7265 //
7266 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7267 // A [default constructor or destructor] is trivial if
7268 // -- for all of the non-static data members of its class that are of class
7269 // type (or array thereof), each such class has a trivial [default
7270 // constructor or destructor]
7271 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7272 return false;
7273
7274 // C++11 [class.dtor]p5:
7275 // A destructor is trivial if [...]
7276 // -- the destructor is not virtual
7277 if (CSM == CXXDestructor && MD->isVirtual()) {
7278 if (Diagnose)
7279 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7280 return false;
7281 }
7282
7283 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7284 // A [special member] for class X is trivial if [...]
7285 // -- class X has no virtual functions and no virtual base classes
7286 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7287 if (!Diagnose)
7288 return false;
7289
7290 if (RD->getNumVBases()) {
7291 // Check for virtual bases. We already know that the corresponding
7292 // member in all bases is trivial, so vbases must all be direct.
7293 CXXBaseSpecifier &BS = *RD->vbases_begin();
7294 assert(BS.isVirtual());
7295 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7296 return false;
7297 }
7298
7299 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007300 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007301 if (MI->isVirtual()) {
7302 SourceLocation MLoc = MI->getLocStart();
7303 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7304 return false;
7305 }
7306 }
7307
7308 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7309 }
7310
7311 // Looks like it's trivial!
7312 return true;
7313}
7314
Benjamin Kramer024e6192011-03-04 13:12:48 +00007315namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007316struct FindHiddenVirtualMethod {
7317 Sema *S;
7318 CXXMethodDecl *Method;
7319 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7320 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007321
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007322private:
7323 /// Check whether any most overriden method from MD in Methods
7324 static bool CheckMostOverridenMethods(
7325 const CXXMethodDecl *MD,
7326 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7327 if (MD->size_overridden_methods() == 0)
7328 return Methods.count(MD->getCanonicalDecl());
7329 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7330 E = MD->end_overridden_methods();
7331 I != E; ++I)
7332 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007333 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007334 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007335 }
7336
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007337public:
7338 /// Member lookup function that determines whether a given C++
7339 /// method overloads virtual methods in a base class without overriding any,
7340 /// to be used with CXXRecordDecl::lookupInBases().
7341 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7342 RecordDecl *BaseRecord =
7343 Specifier->getType()->getAs<RecordType>()->getDecl();
7344
7345 DeclarationName Name = Method->getDeclName();
7346 assert(Name.getNameKind() == DeclarationName::Identifier);
7347
7348 bool foundSameNameMethod = false;
7349 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7350 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7351 Path.Decls = Path.Decls.slice(1)) {
7352 NamedDecl *D = Path.Decls.front();
7353 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7354 MD = MD->getCanonicalDecl();
7355 foundSameNameMethod = true;
7356 // Interested only in hidden virtual methods.
7357 if (!MD->isVirtual())
7358 continue;
7359 // If the method we are checking overrides a method from its base
7360 // don't warn about the other overloaded methods. Clang deviates from
7361 // GCC by only diagnosing overloads of inherited virtual functions that
7362 // do not override any other virtual functions in the base. GCC's
7363 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7364 // function from a base class. These cases may be better served by a
7365 // warning (not specific to virtual functions) on call sites when the
7366 // call would select a different function from the base class, were it
7367 // visible.
7368 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7369 if (!S->IsOverload(Method, MD, false))
7370 return true;
7371 // Collect the overload only if its hidden.
7372 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7373 overloadedMethods.push_back(MD);
7374 }
7375 }
7376
7377 if (foundSameNameMethod)
7378 OverloadedMethods.append(overloadedMethods.begin(),
7379 overloadedMethods.end());
7380 return foundSameNameMethod;
7381 }
7382};
7383} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007384
David Blaikie282c92a2012-10-19 00:53:08 +00007385/// \brief Add the most overriden methods from MD to Methods
7386static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007387 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007388 if (MD->size_overridden_methods() == 0)
7389 Methods.insert(MD->getCanonicalDecl());
7390 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7391 E = MD->end_overridden_methods();
7392 I != E; ++I)
7393 AddMostOverridenMethods(*I, Methods);
7394}
7395
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007396/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007397/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007398void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7399 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007400 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007401 return;
7402
7403 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7404 /*bool RecordPaths=*/false,
7405 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007406 FindHiddenVirtualMethod FHVM;
7407 FHVM.Method = MD;
7408 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007409
7410 // Keep the base methods that were overriden or introduced in the subclass
7411 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007412 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007413 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7414 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7415 NamedDecl *ND = *I;
7416 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007417 ND = shad->getTargetDecl();
7418 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007419 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007420 }
7421
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007422 if (DC->lookupInBases(FHVM, Paths))
7423 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007424}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007425
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007426void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7427 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7428 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7429 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7430 PartialDiagnostic PD = PDiag(
7431 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7432 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7433 Diag(overloadedMD->getLocation(), PD);
7434 }
7435}
7436
7437/// \brief Diagnose methods which overload virtual methods in a base class
7438/// without overriding any.
7439void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7440 if (MD->isInvalidDecl())
7441 return;
7442
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007443 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007444 return;
7445
7446 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7447 FindHiddenVirtualMethods(MD, OverloadedMethods);
7448 if (!OverloadedMethods.empty()) {
7449 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7450 << MD << (OverloadedMethods.size() > 1);
7451
7452 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007453 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007454}
7455
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007456void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007457 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007458 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007459 SourceLocation RBrac,
7460 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007461 if (!TagDecl)
7462 return;
Mike Stump11289f42009-09-09 15:08:12 +00007463
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007464 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007465
Rafael Espindola06e1b132012-07-12 04:32:30 +00007466 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7467 if (l->getKind() != AttributeList::AT_Visibility)
7468 continue;
7469 l->setInvalid();
7470 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7471 l->getName();
7472 }
7473
David Blaikie751c5582011-09-22 02:58:26 +00007474 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007475 // strict aliasing violation!
7476 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007477 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007478
Douglas Gregor0be31a22010-07-02 17:43:08 +00007479 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007480 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007481}
7482
Douglas Gregor05379422008-11-03 17:51:48 +00007483/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7484/// special functions, such as the default constructor, copy
7485/// constructor, or destructor, to the given C++ class (C++
7486/// [special]p1). This routine can only be executed just before the
7487/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007488void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007489 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007490 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007491
Richard Smith5179eb72016-06-28 19:03:57 +00007492 if (ClassDecl->hasInheritedConstructor())
7493 DeclareImplicitDefaultConstructor(ClassDecl);
7494 }
Richard Smith12e79312016-05-13 06:47:56 +00007495
Richard Smitha87b7662016-05-13 18:48:05 +00007496 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007497 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007498
Richard Smith6b02d462012-12-08 08:32:28 +00007499 // If the properties or semantics of the copy constructor couldn't be
7500 // determined while the class was being declared, force a declaration
7501 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007502 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7503 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007504 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007505 // For the MS ABI we need to know whether the copy ctor is deleted. A
7506 // prerequisite for deleting the implicit copy ctor is that the class has a
7507 // move ctor or move assignment that is either user-declared or whose
7508 // semantics are inherited from a subobject. FIXME: We should provide a more
7509 // direct way for CodeGen to ask whether the constructor was deleted.
7510 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7511 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7512 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7513 ClassDecl->hasUserDeclaredMoveAssignment() ||
7514 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7515 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007516 }
7517
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007518 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007519 ++ASTContext::NumImplicitMoveConstructors;
7520
Richard Smith12e79312016-05-13 06:47:56 +00007521 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7522 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007523 DeclareImplicitMoveConstructor(ClassDecl);
7524 }
7525
Richard Smitha87b7662016-05-13 18:48:05 +00007526 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007527 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007528
7529 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007530 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007531 // it shows up in the right place in the vtable and that we diagnose
7532 // problems with the implicit exception specification.
7533 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007534 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7535 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007536 DeclareImplicitCopyAssignment(ClassDecl);
7537 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007538
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007539 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007540 ++ASTContext::NumImplicitMoveAssignmentOperators;
7541
7542 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007543 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007544 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7545 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007546 DeclareImplicitMoveAssignment(ClassDecl);
7547 }
7548
Richard Smitha87b7662016-05-13 18:48:05 +00007549 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007550 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007551
7552 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007553 // have to declare the destructor immediately. This ensures that, e.g., it
7554 // shows up in the right place in the vtable and that we diagnose problems
7555 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007556 if (ClassDecl->isDynamicClass() ||
7557 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007558 DeclareImplicitDestructor(ClassDecl);
7559 }
Douglas Gregor05379422008-11-03 17:51:48 +00007560}
7561
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007562unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007563 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007564 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007565
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007566 // The order of template parameters is not important here. All names
7567 // get added to the same scope.
7568 SmallVector<TemplateParameterList *, 4> ParameterLists;
7569
7570 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7571 D = TD->getTemplatedDecl();
7572
7573 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7574 ParameterLists.push_back(PSD->getTemplateParameters());
7575
7576 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7577 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7578 ParameterLists.push_back(DD->getTemplateParameterList(i));
7579
7580 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7581 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7582 ParameterLists.push_back(FTD->getTemplateParameters());
7583 }
7584 }
7585
7586 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7587 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7588 ParameterLists.push_back(TD->getTemplateParameterList(i));
7589
7590 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7591 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7592 ParameterLists.push_back(CTD->getTemplateParameters());
7593 }
7594 }
7595
7596 unsigned Count = 0;
7597 for (TemplateParameterList *Params : ParameterLists) {
7598 if (Params->size() > 0)
7599 // Ignore explicit specializations; they don't contribute to the template
7600 // depth.
7601 ++Count;
7602 for (NamedDecl *Param : *Params) {
7603 if (Param->getDeclName()) {
7604 S->AddDecl(Param);
7605 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007606 }
7607 }
7608 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007609
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007610 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007611}
7612
John McCall48871652010-08-21 09:40:31 +00007613void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007614 if (!RecordD) return;
7615 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007616 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007617 PushDeclContext(S, Record);
7618}
7619
John McCall48871652010-08-21 09:40:31 +00007620void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007621 if (!RecordD) return;
7622 PopDeclContext();
7623}
7624
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007625/// This is used to implement the constant expression evaluation part of the
7626/// attribute enable_if extension. There is nothing in standard C++ which would
7627/// require reentering parameters.
7628void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7629 if (!Param)
7630 return;
7631
7632 S->AddDecl(Param);
7633 if (Param->getDeclName())
7634 IdResolver.AddDecl(Param);
7635}
7636
Douglas Gregor4d87df52008-12-16 21:30:33 +00007637/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7638/// parsing a top-level (non-nested) C++ class, and we are now
7639/// parsing those parts of the given Method declaration that could
7640/// not be parsed earlier (C++ [class.mem]p2), such as default
7641/// arguments. This action should enter the scope of the given
7642/// Method declaration as if we had just parsed the qualified method
7643/// name. However, it should not bring the parameters into scope;
7644/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007645void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007646}
7647
7648/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7649/// C++ method declaration. We're (re-)introducing the given
7650/// function parameter into scope for use in parsing later parts of
7651/// the method declaration. For example, we could see an
7652/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007653void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007654 if (!ParamD)
7655 return;
Mike Stump11289f42009-09-09 15:08:12 +00007656
John McCall48871652010-08-21 09:40:31 +00007657 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007658
7659 // If this parameter has an unparsed default argument, clear it out
7660 // to make way for the parsed default argument.
7661 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007662 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007663
John McCall48871652010-08-21 09:40:31 +00007664 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007665 if (Param->getDeclName())
7666 IdResolver.AddDecl(Param);
7667}
7668
7669/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7670/// processing the delayed method declaration for Method. The method
7671/// declaration is now considered finished. There may be a separate
7672/// ActOnStartOfFunctionDef action later (not necessarily
7673/// immediately!) for this method, if it was also defined inside the
7674/// class body.
John McCall48871652010-08-21 09:40:31 +00007675void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007676 if (!MethodD)
7677 return;
Mike Stump11289f42009-09-09 15:08:12 +00007678
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007679 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007680
John McCall48871652010-08-21 09:40:31 +00007681 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007682
7683 // Now that we have our default arguments, check the constructor
7684 // again. It could produce additional diagnostics or affect whether
7685 // the class has implicitly-declared destructors, among other
7686 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007687 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7688 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007689
7690 // Check the default arguments, which we may have added.
7691 if (!Method->isInvalidDecl())
7692 CheckCXXDefaultArguments(Method);
7693}
7694
Douglas Gregor831c93f2008-11-05 20:51:48 +00007695/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007696/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007697/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007698/// emit diagnostics and set the invalid bit to true. In any case, the type
7699/// will be updated to reflect a well-formed type for the constructor and
7700/// returned.
7701QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007702 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007703 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007704
7705 // C++ [class.ctor]p3:
7706 // A constructor shall not be virtual (10.3) or static (9.4). A
7707 // constructor can be invoked for a const, volatile or const
7708 // volatile object. A constructor shall not be declared const,
7709 // volatile, or const volatile (9.3.2).
7710 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007711 if (!D.isInvalidType())
7712 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7713 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7714 << SourceRange(D.getIdentifierLoc());
7715 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007716 }
John McCall8e7d6562010-08-26 03:08:43 +00007717 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007718 if (!D.isInvalidType())
7719 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7720 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7721 << SourceRange(D.getIdentifierLoc());
7722 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007723 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007724 }
Mike Stump11289f42009-09-09 15:08:12 +00007725
David Majnemer03f705f2014-07-08 18:18:04 +00007726 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7727 diagnoseIgnoredQualifiers(
7728 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7729 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7730 D.getDeclSpec().getRestrictSpecLoc(),
7731 D.getDeclSpec().getAtomicSpecLoc());
7732 D.setInvalidType();
7733 }
7734
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007735 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007736 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007737 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007738 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7739 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007740 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007741 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7742 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007743 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007744 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7745 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007746 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007747 }
Mike Stump11289f42009-09-09 15:08:12 +00007748
Douglas Gregordb9d6642011-01-26 05:01:58 +00007749 // C++0x [class.ctor]p4:
7750 // A constructor shall not be declared with a ref-qualifier.
7751 if (FTI.hasRefQualifier()) {
7752 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7753 << FTI.RefQualifierIsLValueRef
7754 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7755 D.setInvalidType();
7756 }
7757
Douglas Gregor831c93f2008-11-05 20:51:48 +00007758 // Rebuild the function type "R" without any type qualifiers (in
7759 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007760 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007761 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007762 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007763 return R;
7764
7765 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7766 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007767 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007768
7769 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007770}
7771
Douglas Gregor4d87df52008-12-16 21:30:33 +00007772/// CheckConstructor - Checks a fully-formed constructor for
7773/// well-formedness, issuing any diagnostics required. Returns true if
7774/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007775void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007776 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007777 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7778 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007779 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007780
7781 // C++ [class.copy]p3:
7782 // A declaration of a constructor for a class X is ill-formed if
7783 // its first parameter is of type (optionally cv-qualified) X and
7784 // either there are no other parameters or else all other
7785 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007786 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007787 ((Constructor->getNumParams() == 1) ||
7788 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007789 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7790 Constructor->getTemplateSpecializationKind()
7791 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007792 QualType ParamType = Constructor->getParamDecl(0)->getType();
7793 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7794 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007795 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007796 const char *ConstRef
7797 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7798 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007799 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007800 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007801
7802 // FIXME: Rather that making the constructor invalid, we should endeavor
7803 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007804 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007805 }
7806 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007807}
7808
John McCalldeb646e2010-08-04 01:04:25 +00007809/// CheckDestructor - Checks a fully-formed destructor definition for
7810/// well-formedness, issuing any diagnostics required. Returns true
7811/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007812bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007813 CXXRecordDecl *RD = Destructor->getParent();
7814
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007815 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007816 SourceLocation Loc;
7817
7818 if (!Destructor->isImplicit())
7819 Loc = Destructor->getLocation();
7820 else
7821 Loc = RD->getLocation();
7822
7823 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007824 if (FunctionDecl *OperatorDelete =
7825 FindDeallocationFunctionForDestructor(Loc, RD)) {
7826 MarkFunctionReferenced(Loc, OperatorDelete);
7827 Destructor->setOperatorDelete(OperatorDelete);
7828 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007829 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007830
7831 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007832}
7833
Douglas Gregor831c93f2008-11-05 20:51:48 +00007834/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7835/// the well-formednes of the destructor declarator @p D with type @p
7836/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007837/// emit diagnostics and set the declarator to invalid. Even if this happens,
7838/// will be updated to reflect a well-formed type for the destructor and
7839/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007840QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007841 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007842 // C++ [class.dtor]p1:
7843 // [...] A typedef-name that names a class is a class-name
7844 // (7.1.3); however, a typedef-name that names a class shall not
7845 // be used as the identifier in the declarator for a destructor
7846 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007847 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007848 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007849 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007850 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007851 else if (const TemplateSpecializationType *TST =
7852 DeclaratorType->getAs<TemplateSpecializationType>())
7853 if (TST->isTypeAlias())
7854 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7855 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007856
7857 // C++ [class.dtor]p2:
7858 // A destructor is used to destroy objects of its class type. A
7859 // destructor takes no parameters, and no return type can be
7860 // specified for it (not even void). The address of a destructor
7861 // shall not be taken. A destructor shall not be static. A
7862 // destructor can be invoked for a const, volatile or const
7863 // volatile object. A destructor shall not be declared const,
7864 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007865 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007866 if (!D.isInvalidType())
7867 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7868 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007869 << SourceRange(D.getIdentifierLoc())
7870 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7871
John McCall8e7d6562010-08-26 03:08:43 +00007872 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007873 }
David Majnemer03f705f2014-07-08 18:18:04 +00007874 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007875 // Destructors don't have return types, but the parser will
7876 // happily parse something like:
7877 //
7878 // class X {
7879 // float ~X();
7880 // };
7881 //
7882 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007883 if (D.getDeclSpec().hasTypeSpecifier())
7884 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7885 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7886 << SourceRange(D.getIdentifierLoc());
7887 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7888 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7889 SourceLocation(),
7890 D.getDeclSpec().getConstSpecLoc(),
7891 D.getDeclSpec().getVolatileSpecLoc(),
7892 D.getDeclSpec().getRestrictSpecLoc(),
7893 D.getDeclSpec().getAtomicSpecLoc());
7894 D.setInvalidType();
7895 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007896 }
Mike Stump11289f42009-09-09 15:08:12 +00007897
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007898 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007899 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007900 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007901 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7902 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007903 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007904 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7905 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007906 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007907 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7908 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007909 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007910 }
7911
Douglas Gregordb9d6642011-01-26 05:01:58 +00007912 // C++0x [class.dtor]p2:
7913 // A destructor shall not be declared with a ref-qualifier.
7914 if (FTI.hasRefQualifier()) {
7915 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7916 << FTI.RefQualifierIsLValueRef
7917 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7918 D.setInvalidType();
7919 }
7920
Douglas Gregor831c93f2008-11-05 20:51:48 +00007921 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007922 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007923 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7924
7925 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007926 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007927 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007928 }
7929
Mike Stump11289f42009-09-09 15:08:12 +00007930 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007931 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007932 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007933 D.setInvalidType();
7934 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007935
7936 // Rebuild the function type "R" without any type qualifiers or
7937 // parameters (in case any of the errors above fired) and with
7938 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007939 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007940 if (!D.isInvalidType())
7941 return R;
7942
Douglas Gregor95755162010-07-01 05:10:53 +00007943 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007944 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7945 EPI.Variadic = false;
7946 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007947 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007948 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007949}
7950
Craig Toppere335f252015-10-04 04:53:55 +00007951static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007952 if (Before.isInvalid())
7953 return;
7954 R.setBegin(Before.getBegin());
7955 if (R.getEnd().isInvalid())
7956 R.setEnd(Before.getEnd());
7957}
7958
Craig Toppere335f252015-10-04 04:53:55 +00007959static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007960 if (After.isInvalid())
7961 return;
7962 if (R.getBegin().isInvalid())
7963 R.setBegin(After.getBegin());
7964 R.setEnd(After.getEnd());
7965}
7966
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007967/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7968/// well-formednes of the conversion function declarator @p D with
7969/// type @p R. If there are any errors in the declarator, this routine
7970/// will emit diagnostics and return true. Otherwise, it will return
7971/// false. Either way, the type @p R will be updated to reflect a
7972/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007973void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007974 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007975 // C++ [class.conv.fct]p1:
7976 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007977 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007978 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007979 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007980 if (!D.isInvalidType())
7981 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007982 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7983 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007984 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007985 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007986 }
John McCall212fa2e2010-04-13 00:04:31 +00007987
Richard Smitha865a162014-12-19 02:07:47 +00007988 TypeSourceInfo *ConvTSI = nullptr;
7989 QualType ConvType =
7990 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007991
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007992 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007993 // Conversion functions don't have return types, but the parser will
7994 // happily parse something like:
7995 //
7996 // class X {
7997 // float operator bool();
7998 // };
7999 //
8000 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00008001 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8002 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8003 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00008004 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008005 }
8006
John McCall212fa2e2010-04-13 00:04:31 +00008007 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8008
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008009 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00008010 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008011 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8012
8013 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00008014 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008015 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00008016 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008017 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008018 D.setInvalidType();
8019 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008020
John McCall212fa2e2010-04-13 00:04:31 +00008021 // Diagnose "&operator bool()" and other such nonsense. This
8022 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00008023 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00008024 bool NeedsTypedef = false;
8025 SourceRange Before, After;
8026
8027 // Walk the chunks and extract information on them for our diagnostic.
8028 bool PastFunctionChunk = false;
8029 for (auto &Chunk : D.type_objects()) {
8030 switch (Chunk.Kind) {
8031 case DeclaratorChunk::Function:
8032 if (!PastFunctionChunk) {
8033 if (Chunk.Fun.HasTrailingReturnType) {
8034 TypeSourceInfo *TRT = nullptr;
8035 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8036 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8037 }
8038 PastFunctionChunk = true;
8039 break;
8040 }
8041 // Fall through.
8042 case DeclaratorChunk::Array:
8043 NeedsTypedef = true;
8044 extendRight(After, Chunk.getSourceRange());
8045 break;
8046
8047 case DeclaratorChunk::Pointer:
8048 case DeclaratorChunk::BlockPointer:
8049 case DeclaratorChunk::Reference:
8050 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00008051 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00008052 extendLeft(Before, Chunk.getSourceRange());
8053 break;
8054
8055 case DeclaratorChunk::Paren:
8056 extendLeft(Before, Chunk.Loc);
8057 extendRight(After, Chunk.EndLoc);
8058 break;
8059 }
8060 }
8061
8062 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8063 After.isValid() ? After.getBegin() :
8064 D.getIdentifierLoc();
8065 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8066 DB << Before << After;
8067
8068 if (!NeedsTypedef) {
8069 DB << /*don't need a typedef*/0;
8070
8071 // If we can provide a correct fix-it hint, do so.
8072 if (After.isInvalid() && ConvTSI) {
8073 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008074 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00008075 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8076 << FixItHint::CreateInsertionFromRange(
8077 InsertLoc, CharSourceRange::getTokenRange(Before))
8078 << FixItHint::CreateRemoval(Before);
8079 }
8080 } else if (!Proto->getReturnType()->isDependentType()) {
8081 DB << /*typedef*/1 << Proto->getReturnType();
8082 } else if (getLangOpts().CPlusPlus11) {
8083 DB << /*alias template*/2 << Proto->getReturnType();
8084 } else {
8085 DB << /*might not be fixable*/3;
8086 }
8087
8088 // Recover by incorporating the other type chunks into the result type.
8089 // Note, this does *not* change the name of the function. This is compatible
8090 // with the GCC extension:
8091 // struct S { &operator int(); } s;
8092 // int &r = s.operator int(); // ok in GCC
8093 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00008094 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00008095 }
8096
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008097 // C++ [class.conv.fct]p4:
8098 // The conversion-type-id shall not represent a function type nor
8099 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008100 if (ConvType->isArrayType()) {
8101 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8102 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008103 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008104 } else if (ConvType->isFunctionType()) {
8105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8106 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008107 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008108 }
8109
8110 // Rebuild the function type "R" without any parameters (in case any
8111 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00008112 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00008113 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008114 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008115
Douglas Gregor5fb53972009-01-14 15:45:31 +00008116 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00008117 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008118 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008119 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008120 diag::warn_cxx98_compat_explicit_conversion_functions :
8121 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008122 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008123}
8124
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008125/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8126/// the declaration of the given C++ conversion function. This routine
8127/// is responsible for recording the conversion function in the C++
8128/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008129Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008130 assert(Conversion && "Expected to receive a conversion function declaration");
8131
Douglas Gregor4287b372008-12-12 08:25:50 +00008132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008133
8134 // Make sure we aren't redeclaring the conversion function.
8135 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008136
8137 // C++ [class.conv.fct]p1:
8138 // [...] A conversion function is never used to convert a
8139 // (possibly cv-qualified) object to the (possibly cv-qualified)
8140 // same object type (or a reference to it), to a (possibly
8141 // cv-qualified) base class of that type (or a reference to it),
8142 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008143 // FIXME: Suppress this warning if the conversion function ends up being a
8144 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008145 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008146 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008147 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008148 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008149 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8150 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008151 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008152 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008153 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8154 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008155 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008156 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008157 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008158 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008159 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008160 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008161 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008162 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008163 }
8164
Douglas Gregor457104e2010-09-29 04:25:11 +00008165 if (FunctionTemplateDecl *ConversionTemplate
8166 = Conversion->getDescribedFunctionTemplate())
8167 return ConversionTemplate;
8168
John McCall48871652010-08-21 09:40:31 +00008169 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008170}
8171
Richard Smithf283fdc2017-02-08 00:35:25 +00008172namespace {
8173/// Utility class to accumulate and print a diagnostic listing the invalid
8174/// specifier(s) on a declaration.
8175struct BadSpecifierDiagnoser {
8176 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8177 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8178 ~BadSpecifierDiagnoser() {
8179 Diagnostic << Specifiers;
8180 }
8181
8182 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8183 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8184 }
8185 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8186 return check(SpecLoc,
8187 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8188 }
8189 void check(SourceLocation SpecLoc, const char *Spec) {
8190 if (SpecLoc.isInvalid()) return;
8191 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8192 if (!Specifiers.empty()) Specifiers += " ";
8193 Specifiers += Spec;
8194 }
8195
8196 Sema &S;
8197 Sema::SemaDiagnosticBuilder Diagnostic;
8198 std::string Specifiers;
8199};
8200}
8201
Richard Smith35845152017-02-07 01:37:30 +00008202/// Check the validity of a declarator that we parsed for a deduction-guide.
8203/// These aren't actually declarators in the grammar, so we need to check that
8204/// the user didn't specify any pieces that are not part of the deduction-guide
8205/// grammar.
8206void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8207 StorageClass &SC) {
Richard Smith278890f2017-02-10 20:39:58 +00008208 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8209 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8210 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8211
8212 // C++ [temp.deduct.guide]p3:
8213 // A deduction-gide shall be declared in the same scope as the
8214 // corresponding class template.
8215 if (!CurContext->getRedeclContext()->Equals(
8216 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8217 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8218 << GuidedTemplateDecl;
8219 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8220 }
8221
Richard Smithf283fdc2017-02-08 00:35:25 +00008222 auto &DS = D.getMutableDeclSpec();
8223 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8224 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8225 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8226 DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8227 DS.isConceptSpecified()) {
8228 BadSpecifierDiagnoser Diagnoser(
8229 *this, D.getIdentifierLoc(),
8230 diag::err_deduction_guide_invalid_specifier);
8231
8232 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8233 DS.ClearStorageClassSpecs();
8234 SC = SC_None;
8235
8236 // 'explicit' is permitted.
8237 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8238 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8239 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8240 Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8241 DS.ClearConstexprSpec();
8242 DS.ClearConceptSpec();
8243
8244 Diagnoser.check(DS.getConstSpecLoc(), "const");
8245 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8246 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8247 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8248 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8249 DS.ClearTypeQualifiers();
8250
8251 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8252 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8253 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8254 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8255 DS.ClearTypeSpecType();
8256 }
8257
8258 if (D.isInvalidType())
8259 return;
8260
8261 // Check the declarator is simple enough.
8262 bool FoundFunction = false;
8263 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8264 if (Chunk.Kind == DeclaratorChunk::Paren)
8265 continue;
8266 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8267 Diag(D.getDeclSpec().getLocStart(),
8268 diag::err_deduction_guide_with_complex_decl)
8269 << D.getSourceRange();
8270 break;
8271 }
8272 if (!Chunk.Fun.hasTrailingReturnType()) {
8273 Diag(D.getName().getLocStart(),
8274 diag::err_deduction_guide_no_trailing_return_type);
8275 break;
8276 }
Richard Smith3817e4a2017-02-10 19:49:50 +00008277
8278 // Check that the return type is written as a specialization of
8279 // the template specified as the deduction-guide's name.
8280 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
Richard Smith3817e4a2017-02-10 19:49:50 +00008281 TypeSourceInfo *TSI = nullptr;
8282 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8283 assert(TSI && "deduction guide has valid type but invalid return type?");
8284 bool AcceptableReturnType = false;
8285 bool MightInstantiateToSpecialization = false;
8286 if (auto RetTST =
8287 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8288 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8289 bool TemplateMatches =
8290 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8291 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8292 AcceptableReturnType = true;
8293 else {
8294 // This could still instantiate to the right type, unless we know it
8295 // names the wrong class template.
8296 auto *TD = SpecifiedName.getAsTemplateDecl();
8297 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8298 !TemplateMatches);
8299 }
8300 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8301 MightInstantiateToSpecialization = true;
8302 }
8303
8304 if (!AcceptableReturnType) {
8305 Diag(TSI->getTypeLoc().getLocStart(),
8306 diag::err_deduction_guide_bad_trailing_return_type)
8307 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8308 << TSI->getTypeLoc().getSourceRange();
8309 }
8310
8311 // Keep going to check that we don't have any inner declarator pieces (we
8312 // could still have a function returning a pointer to a function).
Richard Smithf283fdc2017-02-08 00:35:25 +00008313 FoundFunction = true;
8314 }
8315
Richard Smithc88aa3f2017-02-08 01:27:29 +00008316 if (D.isFunctionDefinition())
8317 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
Richard Smith35845152017-02-07 01:37:30 +00008318}
8319
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008320//===----------------------------------------------------------------------===//
8321// Namespace Handling
8322//===----------------------------------------------------------------------===//
8323
Richard Smith45bb8852012-10-04 22:13:39 +00008324/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8325/// reopened.
8326static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8327 SourceLocation Loc,
8328 IdentifierInfo *II, bool *IsInline,
8329 NamespaceDecl *PrevNS) {
8330 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008331
Richard Smithf501cc32012-10-05 01:46:25 +00008332 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8333 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8334 // inline namespaces, with the intention of bringing names into namespace std.
8335 //
8336 // We support this just well enough to get that case working; this is not
8337 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008338 if (*IsInline && II && II->getName().startswith("__atomic") &&
8339 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008340 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008341 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8342 NS = NS->getPreviousDecl())
8343 NS->setInline(*IsInline);
8344 // Patch up the lookup table for the containing namespace. This isn't really
8345 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008346 for (auto *I : PrevNS->decls())
8347 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008348 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8349 return;
8350 }
8351
8352 if (PrevNS->isInline())
8353 // The user probably just forgot the 'inline', so suggest that it
8354 // be added back.
8355 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8356 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8357 else
Richard Smith360cb252016-09-30 23:16:08 +00008358 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008359
8360 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8361 *IsInline = PrevNS->isInline();
8362}
John McCallb1be5232010-08-26 09:15:37 +00008363
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008364/// ActOnStartNamespaceDef - This is called at the start of a namespace
8365/// definition.
John McCall48871652010-08-21 09:40:31 +00008366Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008367 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008368 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008369 SourceLocation IdentLoc,
8370 IdentifierInfo *II,
8371 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008372 AttributeList *AttrList,
8373 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008374 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8375 // For anonymous namespace, take the location of the left brace.
8376 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008377 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008378 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008379 bool IsStd = false;
8380 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008381 Scope *DeclRegionScope = NamespcScope->getParent();
8382
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008384 if (II) {
8385 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008386 // The identifier in an original-namespace-definition shall not
8387 // have been previously defined in the declarative region in
8388 // which the original-namespace-definition appears. The
8389 // identifier in an original-namespace-definition is the name of
8390 // the namespace. Subsequently in that declarative region, it is
8391 // treated as an original-namespace-name.
8392 //
8393 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008394 // look through using directives, just look for any ordinary names
8395 // as if by qualified name lookup.
8396 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8397 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008398 NamedDecl *PrevDecl =
8399 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008400 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008401
Douglas Gregore57e7522012-01-07 09:11:48 +00008402 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008403 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008404 if (IsInline != PrevNS->isInline())
8405 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8406 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008407 } else if (PrevDecl) {
8408 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008409 Diag(Loc, diag::err_redefinition_different_kind)
8410 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008411 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008412 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008413 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008414 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008415 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008416 // This is the first "real" definition of the namespace "std", so update
8417 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008418 PrevNS = getStdNamespace();
8419 IsStd = true;
8420 AddToKnown = !IsInline;
8421 } else {
8422 // We've seen this namespace for the first time.
8423 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008424 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008425 } else {
John McCall4fa53422009-10-01 00:25:31 +00008426 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008427
8428 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008429 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008430 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008431 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008432 } else {
8433 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008434 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008435 }
8436
Richard Smith45bb8852012-10-04 22:13:39 +00008437 if (PrevNS && IsInline != PrevNS->isInline())
8438 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8439 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008440 }
8441
8442 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8443 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008444 if (IsInvalid)
8445 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008446
8447 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008448
Douglas Gregore57e7522012-01-07 09:11:48 +00008449 // FIXME: Should we be merging attributes?
8450 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008451 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008452
8453 if (IsStd)
8454 StdNamespace = Namespc;
8455 if (AddToKnown)
8456 KnownNamespaces[Namespc] = false;
8457
8458 if (II) {
8459 PushOnScopeChains(Namespc, DeclRegionScope);
8460 } else {
8461 // Link the anonymous namespace into its parent.
8462 DeclContext *Parent = CurContext->getRedeclContext();
8463 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8464 TU->setAnonymousNamespace(Namespc);
8465 } else {
8466 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008467 }
John McCall4fa53422009-10-01 00:25:31 +00008468
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008469 CurContext->addDecl(Namespc);
8470
John McCall4fa53422009-10-01 00:25:31 +00008471 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8472 // behaves as if it were replaced by
8473 // namespace unique { /* empty body */ }
8474 // using namespace unique;
8475 // namespace unique { namespace-body }
8476 // where all occurrences of 'unique' in a translation unit are
8477 // replaced by the same identifier and this identifier differs
8478 // from all other identifiers in the entire program.
8479
8480 // We just create the namespace with an empty name and then add an
8481 // implicit using declaration, just like the standard suggests.
8482 //
8483 // CodeGen enforces the "universally unique" aspect by giving all
8484 // declarations semantically contained within an anonymous
8485 // namespace internal linkage.
8486
Douglas Gregore57e7522012-01-07 09:11:48 +00008487 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008488 UD = UsingDirectiveDecl::Create(Context, Parent,
8489 /* 'using' */ LBrace,
8490 /* 'namespace' */ SourceLocation(),
8491 /* qualifier */ NestedNameSpecifierLoc(),
8492 /* identifier */ SourceLocation(),
8493 Namespc,
8494 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008495 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008496 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008497 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008498 }
8499
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008500 ActOnDocumentableDecl(Namespc);
8501
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008502 // Although we could have an invalid decl (i.e. the namespace name is a
8503 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008504 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8505 // for the namespace has the declarations that showed up in that particular
8506 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008507 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008508 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008509}
8510
Sebastian Redla6602e92009-11-23 15:34:23 +00008511/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8512/// is a namespace alias, returns the namespace it points to.
8513static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8514 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8515 return AD->getNamespace();
8516 return dyn_cast_or_null<NamespaceDecl>(D);
8517}
8518
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008519/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8520/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008521void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008522 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8523 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008524 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008525 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008526 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008527 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008528}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008529
John McCall28a0cf72010-08-25 07:42:41 +00008530CXXRecordDecl *Sema::getStdBadAlloc() const {
8531 return cast_or_null<CXXRecordDecl>(
8532 StdBadAlloc.get(Context.getExternalSource()));
8533}
8534
Richard Smith96269c52016-09-29 22:49:46 +00008535EnumDecl *Sema::getStdAlignValT() const {
8536 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8537}
8538
John McCall28a0cf72010-08-25 07:42:41 +00008539NamespaceDecl *Sema::getStdNamespace() const {
8540 return cast_or_null<NamespaceDecl>(
8541 StdNamespace.get(Context.getExternalSource()));
8542}
8543
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008544NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8545 if (!StdExperimentalNamespaceCache) {
8546 if (auto Std = getStdNamespace()) {
8547 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8548 SourceLocation(), LookupNamespaceName);
8549 if (!LookupQualifiedName(Result, Std) ||
8550 !(StdExperimentalNamespaceCache =
8551 Result.getAsSingle<NamespaceDecl>()))
8552 Result.suppressDiagnostics();
8553 }
8554 }
8555 return StdExperimentalNamespaceCache;
8556}
8557
Douglas Gregorcdf87022010-06-29 17:53:46 +00008558/// \brief Retrieve the special "std" namespace, which may require us to
8559/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008560NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008561 if (!StdNamespace) {
8562 // The "std" namespace has not yet been defined, so build one implicitly.
8563 StdNamespace = NamespaceDecl::Create(Context,
8564 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008565 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008566 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008567 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008568 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008569 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008570 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008571
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008572 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008573}
8574
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008575bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008576 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008577 "Looking for std::initializer_list outside of C++.");
8578
8579 // We're looking for implicit instantiations of
8580 // template <typename E> class std::initializer_list.
8581
8582 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8583 return false;
8584
Craig Topperc3ec1492014-05-26 06:22:03 +00008585 ClassTemplateDecl *Template = nullptr;
8586 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008587
Sebastian Redl43144e72012-01-17 22:49:58 +00008588 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008589
Sebastian Redl43144e72012-01-17 22:49:58 +00008590 ClassTemplateSpecializationDecl *Specialization =
8591 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8592 if (!Specialization)
8593 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008594
Sebastian Redl43144e72012-01-17 22:49:58 +00008595 Template = Specialization->getSpecializedTemplate();
8596 Arguments = Specialization->getTemplateArgs().data();
8597 } else if (const TemplateSpecializationType *TST =
8598 Ty->getAs<TemplateSpecializationType>()) {
8599 Template = dyn_cast_or_null<ClassTemplateDecl>(
8600 TST->getTemplateName().getAsTemplateDecl());
8601 Arguments = TST->getArgs();
8602 }
8603 if (!Template)
8604 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008605
8606 if (!StdInitializerList) {
8607 // Haven't recognized std::initializer_list yet, maybe this is it.
8608 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8609 if (TemplateClass->getIdentifier() !=
8610 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008611 !getStdNamespace()->InEnclosingNamespaceSetOf(
8612 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008613 return false;
8614 // This is a template called std::initializer_list, but is it the right
8615 // template?
8616 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008617 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008618 return false;
8619 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8620 return false;
8621
8622 // It's the right template.
8623 StdInitializerList = Template;
8624 }
8625
Richard Smith7d7dee72015-02-24 03:30:14 +00008626 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008627 return false;
8628
8629 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008630 if (Element)
8631 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008632 return true;
8633}
8634
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008635static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8636 NamespaceDecl *Std = S.getStdNamespace();
8637 if (!Std) {
8638 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008639 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008640 }
8641
8642 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8643 Loc, Sema::LookupOrdinaryName);
8644 if (!S.LookupQualifiedName(Result, Std)) {
8645 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008646 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008647 }
8648 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8649 if (!Template) {
8650 Result.suppressDiagnostics();
8651 // We found something weird. Complain about the first thing we found.
8652 NamedDecl *Found = *Result.begin();
8653 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008654 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008655 }
8656
8657 // We found some template called std::initializer_list. Now verify that it's
8658 // correct.
8659 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008660 if (Params->getMinRequiredArguments() != 1 ||
8661 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008662 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008663 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008664 }
8665
8666 return Template;
8667}
8668
8669QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8670 if (!StdInitializerList) {
8671 StdInitializerList = LookupStdInitializerList(*this, Loc);
8672 if (!StdInitializerList)
8673 return QualType();
8674 }
8675
8676 TemplateArgumentListInfo Args(Loc, Loc);
8677 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8678 Context.getTrivialTypeSourceInfo(Element,
8679 Loc)));
8680 return Context.getCanonicalType(
8681 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8682}
8683
Richard Smith60437622017-02-09 19:17:44 +00008684bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008685 // C++ [dcl.init.list]p2:
8686 // A constructor is an initializer-list constructor if its first parameter
8687 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8688 // std::initializer_list<E> for some type E, and either there are no other
8689 // parameters or else all other parameters have default arguments.
8690 if (Ctor->getNumParams() < 1 ||
8691 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8692 return false;
8693
8694 QualType ArgType = Ctor->getParamDecl(0)->getType();
8695 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8696 ArgType = RT->getPointeeType().getUnqualifiedType();
8697
Craig Topperc3ec1492014-05-26 06:22:03 +00008698 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008699}
8700
Douglas Gregora172e082011-03-26 22:25:30 +00008701/// \brief Determine whether a using statement is in a context where it will be
8702/// apply in all contexts.
8703static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8704 switch (CurContext->getDeclKind()) {
8705 case Decl::TranslationUnit:
8706 return true;
8707 case Decl::LinkageSpec:
8708 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8709 default:
8710 return false;
8711 }
8712}
8713
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008714namespace {
8715
8716// Callback to only accept typo corrections that are namespaces.
8717class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008718public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008719 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008720 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008721 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008722 return false;
8723 }
8724};
8725
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008726}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008727
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008728static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8729 CXXScopeSpec &SS,
8730 SourceLocation IdentLoc,
8731 IdentifierInfo *Ident) {
8732 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008733 if (TypoCorrection Corrected =
8734 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8735 llvm::make_unique<NamespaceValidatorCCC>(),
8736 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008737 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008738 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8739 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008740 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008741 S.diagnoseTypo(Corrected,
8742 S.PDiag(diag::err_using_directive_member_suggest)
8743 << Ident << DC << DroppedSpecifier << SS.getRange(),
8744 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008745 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008746 S.diagnoseTypo(Corrected,
8747 S.PDiag(diag::err_using_directive_suggest) << Ident,
8748 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008749 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008750 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008751 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008752 }
8753 return false;
8754}
8755
John McCall48871652010-08-21 09:40:31 +00008756Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008757 SourceLocation UsingLoc,
8758 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008759 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008760 SourceLocation IdentLoc,
8761 IdentifierInfo *NamespcName,
8762 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008763 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8764 assert(NamespcName && "Invalid NamespcName.");
8765 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008766
8767 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008768 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008769 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008770 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008771
Craig Topperc3ec1492014-05-26 06:22:03 +00008772 UsingDirectiveDecl *UDir = nullptr;
8773 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008774 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008775 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008776
Douglas Gregor34074322009-01-14 22:20:51 +00008777 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008778 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8779 LookupParsedName(R, S, &SS);
8780 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008781 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008782
Douglas Gregorcdf87022010-06-29 17:53:46 +00008783 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008784 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008785 // Allow "using namespace std;" or "using namespace ::std;" even if
8786 // "std" hasn't been defined yet, for GCC compatibility.
8787 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8788 NamespcName->isStr("std")) {
8789 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008790 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008791 R.resolveKind();
8792 }
8793 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008794 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008795 }
8796
John McCall9f3059a2009-10-09 21:13:30 +00008797 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008798 NamedDecl *Named = R.getRepresentativeDecl();
8799 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8800 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008801
Nico Riecke50e59a2014-11-24 17:29:52 +00008802 // The use of a nested name specifier may trigger deprecation warnings.
8803 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008804
Douglas Gregor889ceb72009-02-03 19:21:40 +00008805 // C++ [namespace.udir]p1:
8806 // A using-directive specifies that the names in the nominated
8807 // namespace can be used in the scope in which the
8808 // using-directive appears after the using-directive. During
8809 // unqualified name lookup (3.4.1), the names appear as if they
8810 // were declared in the nearest enclosing namespace which
8811 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008812 // namespace. [Note: in this context, "contains" means "contains
8813 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008814
8815 // Find enclosing context containing both using-directive and
8816 // nominated namespace.
8817 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8818 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8819 CommonAncestor = CommonAncestor->getParent();
8820
Sebastian Redla6602e92009-11-23 15:34:23 +00008821 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008822 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008823 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008824
Douglas Gregora172e082011-03-26 22:25:30 +00008825 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008826 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008827 Diag(IdentLoc, diag::warn_using_directive_in_header);
8828 }
8829
Douglas Gregor889ceb72009-02-03 19:21:40 +00008830 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008831 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008832 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008833 }
8834
Richard Smith54ecd982013-02-20 19:22:51 +00008835 if (UDir)
8836 ProcessDeclAttributeList(S, UDir, AttrList);
8837
John McCall48871652010-08-21 09:40:31 +00008838 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008839}
8840
8841void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008842 // If the scope has an associated entity and the using directive is at
8843 // namespace or translation unit scope, add the UsingDirectiveDecl into
8844 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008845 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008846 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008847 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008848 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008849 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008850 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008851 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008852}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008853
Douglas Gregorfec52632009-06-20 00:51:54 +00008854
John McCall48871652010-08-21 09:40:31 +00008855Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008856 AccessSpecifier AS,
John McCall9b72f892010-11-10 02:40:36 +00008857 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008858 SourceLocation TypenameLoc,
John McCall9b72f892010-11-10 02:40:36 +00008859 CXXScopeSpec &SS,
8860 UnqualifiedId &Name,
Richard Smith151c4562016-12-20 21:35:28 +00008861 SourceLocation EllipsisLoc,
8862 AttributeList *AttrList) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008863 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008864
Richard Smith151c4562016-12-20 21:35:28 +00008865 if (SS.isEmpty()) {
8866 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8867 return nullptr;
8868 }
8869
Douglas Gregor220f4272009-11-04 16:30:06 +00008870 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008871 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008872 case UnqualifiedId::IK_Identifier:
8873 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008874 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008875 case UnqualifiedId::IK_ConversionFunctionId:
8876 break;
8877
8878 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008879 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008880 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008881 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008882 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008883 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008884 diag::err_using_decl_constructor)
8885 << SS.getRange();
8886
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008887 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008888
Craig Topperc3ec1492014-05-26 06:22:03 +00008889 return nullptr;
8890
Douglas Gregor220f4272009-11-04 16:30:06 +00008891 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008892 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008893 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008894 return nullptr;
8895
Douglas Gregor220f4272009-11-04 16:30:06 +00008896 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008897 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008898 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008899 return nullptr;
Richard Smith35845152017-02-07 01:37:30 +00008900
8901 case UnqualifiedId::IK_DeductionGuideName:
8902 llvm_unreachable("cannot parse qualified deduction guide name");
Douglas Gregor220f4272009-11-04 16:30:06 +00008903 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008904
8905 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8906 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008907 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008908 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008909
Richard Smithc2bc61b2013-03-18 21:12:30 +00008910 // Warn about access declarations.
Richard Smith6f1daa42016-12-16 00:58:48 +00008911 if (UsingLoc.isInvalid()) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008912 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008913 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8914 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008915 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008916 }
8917
Richard Smith151c4562016-12-20 21:35:28 +00008918 if (EllipsisLoc.isInvalid()) {
8919 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8920 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8921 return nullptr;
8922 } else {
8923 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8924 !TargetNameInfo.containsUnexpandedParameterPack()) {
8925 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8926 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8927 EllipsisLoc = SourceLocation();
8928 }
8929 }
Douglas Gregorc4356532010-12-16 00:46:58 +00008930
Richard Smith151c4562016-12-20 21:35:28 +00008931 NamedDecl *UD =
8932 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8933 SS, TargetNameInfo, EllipsisLoc, AttrList,
8934 /*IsInstantiation*/false);
John McCallb96ec562009-12-04 22:46:56 +00008935 if (UD)
8936 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008937
John McCall48871652010-08-21 09:40:31 +00008938 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008939}
8940
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008941/// \brief Determine whether a using declaration considers the given
8942/// declarations as "equivalent", e.g., if they are redeclarations of
8943/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008944static bool
8945IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8946 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008947 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008948
Richard Smithdda56e42011-04-15 14:24:37 +00008949 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008950 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008951 return Context.hasSameType(TD1->getUnderlyingType(),
8952 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008953
8954 return false;
8955}
8956
8957
John McCall84d87672009-12-10 09:41:52 +00008958/// Determines whether to create a using shadow decl for a particular
8959/// decl, given the set of decls existing prior to this using lookup.
8960bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008961 const LookupResult &Previous,
8962 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008963 // Diagnose finding a decl which is not from a base class of the
8964 // current class. We do this now because there are cases where this
8965 // function will silently decide not to build a shadow decl, which
8966 // will pre-empt further diagnostics.
8967 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008968 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008969 // the qualifier.
8970 //
8971 // FIXME: diagnose the following if we care enough:
8972 // struct A { int foo; };
8973 // struct B : A { using A::foo; };
8974 // template <class T> struct C : A {};
8975 // template <class T> struct D : C<T> { using B::foo; } // <---
8976 // This is invalid (during instantiation) in C++03 because B::foo
8977 // resolves to the using decl in B, which is not a base class of D<T>.
8978 // We can't diagnose it immediately because C<T> is an unknown
8979 // specialization. The UsingShadowDecl in D<T> then points directly
8980 // to A::foo, which will look well-formed when we instantiate.
8981 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008982 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008983 DeclContext *OrigDC = Orig->getDeclContext();
8984
8985 // Handle enums and anonymous structs.
8986 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8987 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8988 while (OrigRec->isAnonymousStructOrUnion())
8989 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8990
8991 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8992 if (OrigDC == CurContext) {
8993 Diag(Using->getLocation(),
8994 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008995 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008996 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00008997 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008998 return true;
8999 }
9000
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009001 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00009002 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009003 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00009004 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009005 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00009006 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00009007 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009008 return true;
9009 }
9010 }
9011
9012 if (Previous.empty()) return false;
9013
9014 NamedDecl *Target = Orig;
9015 if (isa<UsingShadowDecl>(Target))
9016 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9017
John McCalla17e83e2009-12-11 02:33:26 +00009018 // If the target happens to be one of the previous declarations, we
9019 // don't have a conflict.
9020 //
9021 // FIXME: but we might be increasing its access, in which case we
9022 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00009023 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009024 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00009025 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9026 I != E; ++I) {
9027 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00009028 // We can have UsingDecls in our Previous results because we use the same
9029 // LookupResult for checking whether the UsingDecl itself is a valid
9030 // redeclaration.
Richard Smith151c4562016-12-20 21:35:28 +00009031 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
Richard Smithe5a91462016-02-27 02:36:43 +00009032 continue;
9033
Richard Smithfd8634a2013-10-23 02:17:46 +00009034 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9035 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9036 PrevShadow = Shadow;
9037 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00009038 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9039 // We don't conflict with an existing using shadow decl of an equivalent
9040 // declaration, but we're not a redeclaration of it.
9041 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00009042 }
John McCalla17e83e2009-12-11 02:33:26 +00009043
Richard Smithf091e122015-09-15 01:28:55 +00009044 if (isVisible(D))
9045 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00009046 }
9047
Richard Smithfd8634a2013-10-23 02:17:46 +00009048 if (FoundEquivalentDecl)
9049 return false;
9050
Alp Tokera2794f92014-01-22 07:29:52 +00009051 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009052 NamedDecl *OldDecl = nullptr;
9053 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9054 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00009055 case Ovl_Overload:
9056 return false;
9057
9058 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00009059 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009060 break;
Richard Smith18819302014-02-06 01:31:33 +00009061
John McCall84d87672009-12-10 09:41:52 +00009062 // We found a decl with the exact signature.
9063 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00009064 // If we're in a record, we want to hide the target, so we
9065 // return true (without a diagnostic) to tell the caller not to
9066 // build a shadow decl.
9067 if (CurContext->isRecord())
9068 return true;
9069
9070 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00009071 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009072 break;
9073 }
9074
9075 Diag(Target->getLocation(), diag::note_using_decl_target);
9076 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009077 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009078 return true;
9079 }
9080
9081 // Target is not a function.
9082
John McCall84d87672009-12-10 09:41:52 +00009083 if (isa<TagDecl>(Target)) {
9084 // No conflict between a tag and a non-tag.
9085 if (!Tag) return false;
9086
John McCalle29c5cd2009-12-10 19:51:03 +00009087 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009088 Diag(Target->getLocation(), diag::note_using_decl_target);
9089 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009090 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009091 return true;
9092 }
9093
9094 // No conflict between a tag and a non-tag.
9095 if (!NonTag) return false;
9096
John McCalle29c5cd2009-12-10 19:51:03 +00009097 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009098 Diag(Target->getLocation(), diag::note_using_decl_target);
9099 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009100 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009101 return true;
9102}
9103
Richard Smith5179eb72016-06-28 19:03:57 +00009104/// Determine whether a direct base class is a virtual base class.
9105static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9106 if (!Derived->getNumVBases())
9107 return false;
9108 for (auto &B : Derived->bases())
9109 if (B.getType()->getAsCXXRecordDecl() == Base)
9110 return B.isVirtual();
9111 llvm_unreachable("not a direct base class");
9112}
9113
John McCall3f746822009-11-17 05:59:44 +00009114/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00009115UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00009116 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00009117 NamedDecl *Orig,
9118 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00009119 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00009120 NamedDecl *Target = Orig;
9121 if (isa<UsingShadowDecl>(Target)) {
9122 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9123 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00009124 }
Richard Smithfd8634a2013-10-23 02:17:46 +00009125
Richard Smith5179eb72016-06-28 19:03:57 +00009126 NamedDecl *NonTemplateTarget = Target;
9127 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9128 NonTemplateTarget = TargetTD->getTemplatedDecl();
9129
9130 UsingShadowDecl *Shadow;
9131 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9132 bool IsVirtualBase =
9133 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9134 UD->getQualifier()->getAsRecordDecl());
9135 Shadow = ConstructorUsingShadowDecl::Create(
9136 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9137 } else {
9138 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9139 Target);
9140 }
John McCall3f746822009-11-17 05:59:44 +00009141 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00009142
Douglas Gregor457104e2010-09-29 04:25:11 +00009143 Shadow->setAccess(UD->getAccess());
9144 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9145 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00009146
9147 Shadow->setPreviousDecl(PrevDecl);
9148
John McCall3f746822009-11-17 05:59:44 +00009149 if (S)
John McCall3969e302009-12-08 07:46:18 +00009150 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00009151 else
John McCall3969e302009-12-08 07:46:18 +00009152 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00009153
John McCall3969e302009-12-08 07:46:18 +00009154
John McCall84d87672009-12-10 09:41:52 +00009155 return Shadow;
9156}
John McCall3969e302009-12-08 07:46:18 +00009157
John McCall84d87672009-12-10 09:41:52 +00009158/// Hides a using shadow declaration. This is required by the current
9159/// using-decl implementation when a resolvable using declaration in a
9160/// class is followed by a declaration which would hide or override
9161/// one or more of the using decl's targets; for example:
9162///
9163/// struct Base { void foo(int); };
9164/// struct Derived : Base {
9165/// using Base::foo;
9166/// void foo(int);
9167/// };
9168///
9169/// The governing language is C++03 [namespace.udecl]p12:
9170///
9171/// When a using-declaration brings names from a base class into a
9172/// derived class scope, member functions in the derived class
9173/// override and/or hide member functions with the same name and
9174/// parameter types in a base class (rather than conflicting).
9175///
9176/// There are two ways to implement this:
9177/// (1) optimistically create shadow decls when they're not hidden
9178/// by existing declarations, or
9179/// (2) don't create any shadow decls (or at least don't make them
9180/// visible) until we've fully parsed/instantiated the class.
9181/// The problem with (1) is that we might have to retroactively remove
9182/// a shadow decl, which requires several O(n) operations because the
9183/// decl structures are (very reasonably) not designed for removal.
9184/// (2) avoids this but is very fiddly and phase-dependent.
9185void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00009186 if (Shadow->getDeclName().getNameKind() ==
9187 DeclarationName::CXXConversionFunctionName)
9188 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9189
John McCall84d87672009-12-10 09:41:52 +00009190 // Remove it from the DeclContext...
9191 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009192
John McCall84d87672009-12-10 09:41:52 +00009193 // ...and the scope, if applicable...
9194 if (S) {
John McCall48871652010-08-21 09:40:31 +00009195 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00009196 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009197 }
9198
John McCall84d87672009-12-10 09:41:52 +00009199 // ...and the using decl.
9200 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9201
9202 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00009203 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00009204}
9205
Richard Smith09d5b3a2014-05-01 00:35:04 +00009206/// Find the base specifier for a base class with the given type.
9207static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9208 QualType DesiredBase,
9209 bool &AnyDependentBases) {
9210 // Check whether the named type is a direct base class.
9211 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9212 for (auto &Base : Derived->bases()) {
9213 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9214 if (CanonicalDesiredBase == BaseType)
9215 return &Base;
9216 if (BaseType->isDependentType())
9217 AnyDependentBases = true;
9218 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009219 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009220}
9221
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009222namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009223class UsingValidatorCCC : public CorrectionCandidateCallback {
9224public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00009225 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009226 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009227 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00009228 IsInstantiation(IsInstantiation), OldNNS(NNS),
9229 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009230
Craig Toppera798a9d2014-03-02 09:32:10 +00009231 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009232 NamedDecl *ND = Candidate.getCorrectionDecl();
9233
9234 // Keywords are not valid here.
9235 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009236 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009237
9238 // Completely unqualified names are invalid for a 'using' declaration.
9239 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9240 return false;
9241
Richard Smith9385d702016-05-14 01:58:49 +00009242 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9243 // reject.
9244
Richard Smith09d5b3a2014-05-01 00:35:04 +00009245 if (RequireMemberOf) {
9246 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9247 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9248 // No-one ever wants a using-declaration to name an injected-class-name
9249 // of a base class, unless they're declaring an inheriting constructor.
9250 ASTContext &Ctx = ND->getASTContext();
9251 if (!Ctx.getLangOpts().CPlusPlus11)
9252 return false;
9253 QualType FoundType = Ctx.getRecordType(FoundRecord);
9254
9255 // Check that the injected-class-name is named as a member of its own
9256 // type; we don't want to suggest 'using Derived::Base;', since that
9257 // means something else.
9258 NestedNameSpecifier *Specifier =
9259 Candidate.WillReplaceSpecifier()
9260 ? Candidate.getCorrectionSpecifier()
9261 : OldNNS;
9262 if (!Specifier->getAsType() ||
9263 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9264 return false;
9265
9266 // Check that this inheriting constructor declaration actually names a
9267 // direct base class of the current class.
9268 bool AnyDependentBases = false;
9269 if (!findDirectBaseWithType(RequireMemberOf,
9270 Ctx.getRecordType(FoundRecord),
9271 AnyDependentBases) &&
9272 !AnyDependentBases)
9273 return false;
9274 } else {
9275 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9276 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9277 return false;
9278
9279 // FIXME: Check that the base class member is accessible?
9280 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00009281 } else {
9282 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9283 if (FoundRecord && FoundRecord->isInjectedClassName())
9284 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009285 }
9286
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009287 if (isa<TypeDecl>(ND))
9288 return HasTypenameKeyword || !IsInstantiation;
9289
9290 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009291 }
9292
9293private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009294 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009295 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009296 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009297 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009298};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009299} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009300
John McCalle61f2ba2009-11-18 02:36:19 +00009301/// Builds a using declaration.
9302///
9303/// \param IsInstantiation - Whether this call arises from an
9304/// instantiation of an unresolved using declaration. We treat
9305/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009306NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9307 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009308 bool HasTypenameKeyword,
9309 SourceLocation TypenameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009310 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009311 DeclarationNameInfo NameInfo,
Richard Smith151c4562016-12-20 21:35:28 +00009312 SourceLocation EllipsisLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009313 AttributeList *AttrList,
Richard Smith151c4562016-12-20 21:35:28 +00009314 bool IsInstantiation) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009315 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009316 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009317 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009318
Anders Carlssonf038fc22009-08-28 05:49:21 +00009319 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009320
Richard Smith5179eb72016-06-28 19:03:57 +00009321 // For an inheriting constructor declaration, the name of the using
9322 // declaration is the name of a constructor in this class, not in the
9323 // base class.
9324 DeclarationNameInfo UsingName = NameInfo;
9325 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9326 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9327 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9328 Context.getCanonicalType(Context.getRecordType(RD))));
9329
John McCall84d87672009-12-10 09:41:52 +00009330 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009331 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009332 ForRedeclaration);
9333 Previous.setHideTags(false);
9334 if (S) {
9335 LookupName(Previous, S);
9336
9337 // It is really dumb that we have to do this.
9338 LookupResult::Filter F = Previous.makeFilter();
9339 while (F.hasNext()) {
9340 NamedDecl *D = F.next();
9341 if (!isDeclInScope(D, CurContext, S))
9342 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009343 // If we found a local extern declaration that's not ordinarily visible,
9344 // and this declaration is being added to a non-block scope, ignore it.
9345 // We're only checking for scope conflicts here, not also for violations
9346 // of the linkage rules.
9347 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9348 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9349 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009350 }
9351 F.done();
9352 } else {
9353 assert(IsInstantiation && "no scope in non-instantiation");
Richard Smithd8a9e372016-12-18 21:39:37 +00009354 if (CurContext->isRecord())
9355 LookupQualifiedName(Previous, CurContext);
9356 else {
9357 // No redeclaration check is needed here; in non-member contexts we
9358 // diagnosed all possible conflicts with other using-declarations when
9359 // building the template:
9360 //
9361 // For a dependent non-type using declaration, the only valid case is
9362 // if we instantiate to a single enumerator. We check for conflicts
9363 // between shadow declarations we introduce, and we check in the template
9364 // definition for conflicts between a non-type using declaration and any
9365 // other declaration, which together covers all cases.
9366 //
9367 // A dependent typename using declaration will never successfully
9368 // instantiate, since it will always name a class member, so we reject
9369 // that in the template definition.
9370 }
John McCall84d87672009-12-10 09:41:52 +00009371 }
9372
John McCall84d87672009-12-10 09:41:52 +00009373 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009374 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9375 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009376 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009377
9378 // Check for bad qualifiers.
Richard Smithd8a9e372016-12-18 21:39:37 +00009379 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9380 IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009381 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009382
John McCall84c16cf2009-11-12 03:15:40 +00009383 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009384 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009385 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Richard Smith151c4562016-12-20 21:35:28 +00009386 if (!LookupContext || EllipsisLoc.isValid()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009387 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009388 // FIXME: not all declaration name kinds are legal here
9389 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9390 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009391 QualifierLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009392 IdentLoc, NameInfo.getName(),
9393 EllipsisLoc);
John McCallb96ec562009-12-04 22:46:56 +00009394 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009395 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009396 QualifierLoc, NameInfo, EllipsisLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00009397 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009398 D->setAccess(AS);
9399 CurContext->addDecl(D);
9400 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009401 }
John McCallb96ec562009-12-04 22:46:56 +00009402
Richard Smith09d5b3a2014-05-01 00:35:04 +00009403 auto Build = [&](bool Invalid) {
9404 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009405 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9406 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009407 UD->setAccess(AS);
9408 CurContext->addDecl(UD);
9409 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009410 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009411 };
9412 auto BuildInvalid = [&]{ return Build(true); };
9413 auto BuildValid = [&]{ return Build(false); };
9414
9415 if (RequireCompleteDeclContext(SS, LookupContext))
9416 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009417
Richard Smith78163e22015-04-01 19:31:06 +00009418 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009419 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009420
John McCall3969e302009-12-08 07:46:18 +00009421 // Unlike most lookups, we don't always want to hide tag
9422 // declarations: tag names are visible through the using declaration
9423 // even if hidden by ordinary names, *except* in a dependent context
9424 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009425 if (!IsInstantiation)
9426 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009427
John McCall5dadb652012-04-07 03:04:20 +00009428 // For the purposes of this lookup, we have a base object type
9429 // equal to that of the current context.
9430 if (CurContext->isRecord()) {
9431 R.setBaseObjectType(
9432 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9433 }
9434
John McCall27b18f82009-11-17 02:14:36 +00009435 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009436
Richard Smith78163e22015-04-01 19:31:06 +00009437 // Try to correct typos if possible. If constructor name lookup finds no
9438 // results, that means the named class has no explicit constructors, and we
9439 // suppressed declaring implicit ones (probably because it's dependent or
9440 // invalid).
9441 if (R.empty() &&
9442 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Richard Smith46d04a32017-01-08 04:01:15 +00009443 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9444 // it will believe that glibc provides a ::gets in cases where it does not,
9445 // and will try to pull it into namespace std with a using-declaration.
9446 // Just ignore the using-declaration in that case.
9447 auto *II = NameInfo.getName().getAsIdentifierInfo();
9448 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9449 CurContext->isStdNamespace() &&
9450 isa<TranslationUnitDecl>(LookupContext) &&
9451 getSourceManager().isInSystemHeader(UsingLoc))
9452 return nullptr;
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009453 if (TypoCorrection Corrected = CorrectTypo(
9454 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9455 llvm::make_unique<UsingValidatorCCC>(
9456 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9457 dyn_cast<CXXRecordDecl>(CurContext)),
9458 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00009459 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009460 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009461 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9462 << NameInfo.getName() << LookupContext << 0
9463 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009464
Benjamin Kramerae65d222017-01-24 12:49:59 +00009465 // If we picked a correction with no attached Decl we can't do anything
9466 // useful with it, bail out.
9467 NamedDecl *ND = Corrected.getCorrectionDecl();
9468 if (!ND)
9469 return BuildInvalid();
9470
Richard Smith09d5b3a2014-05-01 00:35:04 +00009471 // If we corrected to an inheriting constructor, handle it as one.
9472 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9473 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009474 // The parent of the injected class name is the class itself.
9475 RD = cast<CXXRecordDecl>(RD->getParent());
9476
Richard Smith09d5b3a2014-05-01 00:35:04 +00009477 // Fix up the information we'll use to build the using declaration.
9478 if (Corrected.WillReplaceSpecifier()) {
9479 NestedNameSpecifierLocBuilder Builder;
9480 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9481 QualifierLoc.getSourceRange());
9482 QualifierLoc = Builder.getWithLocInContext(Context);
9483 }
9484
Richard Smith5179eb72016-06-28 19:03:57 +00009485 // In this case, the name we introduce is the name of a derived class
9486 // constructor.
9487 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9488 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9489 Context.getCanonicalType(Context.getRecordType(CurClass))));
9490 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009491 for (auto *Ctor : LookupConstructors(RD))
9492 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009493 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009494 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009495 // FIXME: Pick up all the declarations if we found an overloaded
9496 // function.
9497 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009498 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009499 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009500 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009501 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009502 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009503 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009504 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009505 }
9506
Richard Smith09d5b3a2014-05-01 00:35:04 +00009507 if (R.isAmbiguous())
9508 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009509
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009510 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009511 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009512 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009513 Diag(IdentLoc, diag::err_using_typename_non_type);
9514 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9515 Diag((*I)->getUnderlyingDecl()->getLocation(),
9516 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009517 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009518 }
9519 } else {
9520 // If we asked for a non-typename and we got a type, error out,
9521 // but only if this is an instantiation of an unresolved using
9522 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009523 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009524 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9525 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009526 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009527 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009528 }
9529
Richard Smith5cbeb752016-05-05 02:13:49 +00009530 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009531 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009532 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009533 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9534 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009535 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009536 }
Mike Stump11289f42009-09-09 15:08:12 +00009537
Richard Smith5cbeb752016-05-05 02:13:49 +00009538 // C++14 [namespace.udecl]p7:
9539 // A using-declaration shall not name a scoped enumerator.
9540 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9541 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9542 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9543 << SS.getRange();
9544 return BuildInvalid();
9545 }
9546 }
9547
Richard Smith09d5b3a2014-05-01 00:35:04 +00009548 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009549
Richard Smith5179eb72016-06-28 19:03:57 +00009550 // Some additional rules apply to inheriting constructors.
9551 if (UsingName.getName().getNameKind() ==
9552 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009553 // Suppress access diagnostics; the access check is instead performed at the
9554 // point of use for an inheriting constructor.
9555 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009556 if (CheckInheritingConstructorUsingDecl(UD))
9557 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009558 }
9559
John McCall84d87672009-12-10 09:41:52 +00009560 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009561 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009562 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9563 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009564 }
John McCall3f746822009-11-17 05:59:44 +00009565
9566 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009567}
9568
Richard Smith151c4562016-12-20 21:35:28 +00009569NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9570 ArrayRef<NamedDecl *> Expansions) {
9571 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9572 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9573 isa<UsingPackDecl>(InstantiatedFrom));
9574
9575 auto *UPD =
9576 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9577 UPD->setAccess(InstantiatedFrom->getAccess());
9578 CurContext->addDecl(UPD);
9579 return UPD;
9580}
9581
Sebastian Redl08905022011-02-05 19:23:19 +00009582/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009583bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009584 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009585
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009586 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009587 assert(SourceType &&
9588 "Using decl naming constructor doesn't have type in scope spec.");
9589 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9590
9591 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009592 bool AnyDependentBases = false;
9593 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9594 AnyDependentBases);
9595 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009596 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009597 diag::err_using_decl_constructor_not_in_direct_base)
9598 << UD->getNameInfo().getSourceRange()
9599 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009600 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009601 return true;
9602 }
9603
Richard Smith09d5b3a2014-05-01 00:35:04 +00009604 if (Base)
9605 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009606
9607 return false;
9608}
9609
John McCall84d87672009-12-10 09:41:52 +00009610/// Checks that the given using declaration is not an invalid
9611/// redeclaration. Note that this is checking only for the using decl
9612/// itself, not for any ill-formedness among the UsingShadowDecls.
9613bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009614 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009615 const CXXScopeSpec &SS,
9616 SourceLocation NameLoc,
9617 const LookupResult &Prev) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009618 NestedNameSpecifier *Qual = SS.getScopeRep();
9619
John McCall84d87672009-12-10 09:41:52 +00009620 // C++03 [namespace.udecl]p8:
9621 // C++0x [namespace.udecl]p10:
9622 // A using-declaration is a declaration and can therefore be used
9623 // repeatedly where (and only where) multiple declarations are
9624 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009625 //
John McCall032092f2010-11-29 18:01:58 +00009626 // That's in non-member contexts.
Richard Smith4eeaec42016-12-18 22:01:46 +00009627 if (!CurContext->getRedeclContext()->isRecord()) {
9628 // A dependent qualifier outside a class can only ever resolve to an
9629 // enumeration type. Therefore it conflicts with any other non-type
9630 // declaration in the same scope.
9631 // FIXME: How should we check for dependent type-type conflicts at block
9632 // scope?
9633 if (Qual->isDependent() && !HasTypenameKeyword) {
9634 for (auto *D : Prev) {
Richard Smith151c4562016-12-20 21:35:28 +00009635 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009636 bool OldCouldBeEnumerator =
9637 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9638 Diag(NameLoc,
9639 OldCouldBeEnumerator ? diag::err_redefinition
9640 : diag::err_redefinition_different_kind)
9641 << Prev.getLookupName();
9642 Diag(D->getLocation(), diag::note_previous_definition);
9643 return true;
9644 }
9645 }
9646 }
John McCall84d87672009-12-10 09:41:52 +00009647 return false;
Richard Smith4eeaec42016-12-18 22:01:46 +00009648 }
John McCall84d87672009-12-10 09:41:52 +00009649
9650 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9651 NamedDecl *D = *I;
9652
9653 bool DTypename;
9654 NestedNameSpecifier *DQual;
9655 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009656 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009657 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009658 } else if (UnresolvedUsingValueDecl *UD
9659 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9660 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009661 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009662 } else if (UnresolvedUsingTypenameDecl *UD
9663 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9664 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009665 DQual = UD->getQualifier();
Richard Smith4eeaec42016-12-18 22:01:46 +00009666 } else continue;
John McCall84d87672009-12-10 09:41:52 +00009667
9668 // using decls differ if one says 'typename' and the other doesn't.
9669 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009670 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009671
9672 // using decls differ if they name different scopes (but note that
9673 // template instantiation can cause this check to trigger when it
9674 // didn't before instantiation).
9675 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9676 Context.getCanonicalNestedNameSpecifier(DQual))
9677 continue;
9678
9679 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009680 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009681 return true;
9682 }
9683
9684 return false;
9685}
9686
John McCall3969e302009-12-08 07:46:18 +00009687
John McCallb96ec562009-12-04 22:46:56 +00009688/// Checks that the given nested-name qualifier used in a using decl
9689/// in the current context is appropriately related to the current
9690/// scope. If an error is found, diagnoses it and returns true.
9691bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
Richard Smithd8a9e372016-12-18 21:39:37 +00009692 bool HasTypename,
John McCallb96ec562009-12-04 22:46:56 +00009693 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009694 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009695 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009696 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009697
John McCall3969e302009-12-08 07:46:18 +00009698 if (!CurContext->isRecord()) {
9699 // C++03 [namespace.udecl]p3:
9700 // C++0x [namespace.udecl]p8:
9701 // A using-declaration for a class member shall be a member-declaration.
9702
Richard Smithd8a9e372016-12-18 21:39:37 +00009703 // If we weren't able to compute a valid scope, it might validly be a
9704 // dependent class scope or a dependent enumeration unscoped scope. If
9705 // we have a 'typename' keyword, the scope must resolve to a class type.
9706 if ((HasTypename && !NamedContext) ||
9707 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009708 auto *RD = NamedContext
9709 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9710 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009711 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009712 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009713
John McCall3969e302009-12-08 07:46:18 +00009714 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9715 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009716
9717 // If we have a complete, non-dependent source type, try to suggest a
9718 // way to get the same effect.
9719 if (!RD)
9720 return true;
9721
9722 // Find what this using-declaration was referring to.
9723 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9724 R.setHideTags(false);
9725 R.suppressDiagnostics();
9726 LookupQualifiedName(R, RD);
9727
9728 if (R.getAsSingle<TypeDecl>()) {
9729 if (getLangOpts().CPlusPlus11) {
9730 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9731 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9732 << 0 // alias declaration
9733 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9734 NameInfo.getName().getAsString() +
9735 " = ");
9736 } else {
9737 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9738 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009739 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009740 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9741 << 1 // typedef declaration
9742 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9743 << FixItHint::CreateInsertion(
9744 InsertLoc, " " + NameInfo.getName().getAsString());
9745 }
9746 } else if (R.getAsSingle<VarDecl>()) {
9747 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9748 // repeating the type of the static data member here.
9749 FixItHint FixIt;
9750 if (getLangOpts().CPlusPlus11) {
9751 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9752 FixIt = FixItHint::CreateReplacement(
9753 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9754 }
9755
9756 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9757 << 2 // reference declaration
9758 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009759 } else if (R.getAsSingle<EnumConstantDecl>()) {
9760 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9761 // repeating the type of the enumeration here, and we can't do so if
9762 // the type is anonymous.
9763 FixItHint FixIt;
9764 if (getLangOpts().CPlusPlus11) {
9765 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9766 FixIt = FixItHint::CreateReplacement(
Richard Smithd8a9e372016-12-18 21:39:37 +00009767 UsingLoc,
9768 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
Richard Smithdce10ea2016-05-05 19:16:15 +00009769 }
9770
9771 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9772 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9773 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009774 }
John McCall3969e302009-12-08 07:46:18 +00009775 return true;
9776 }
9777
Richard Smithd8a9e372016-12-18 21:39:37 +00009778 // Otherwise, this might be valid.
John McCall3969e302009-12-08 07:46:18 +00009779 return false;
9780 }
9781
9782 // The current scope is a record.
9783
9784 // If the named context is dependent, we can't decide much.
9785 if (!NamedContext) {
9786 // FIXME: in C++0x, we can diagnose if we can prove that the
9787 // nested-name-specifier does not refer to a base class, which is
9788 // still possible in some cases.
9789
9790 // Otherwise we have to conservatively report that things might be
9791 // okay.
9792 return false;
9793 }
9794
9795 if (!NamedContext->isRecord()) {
9796 // Ideally this would point at the last name in the specifier,
9797 // but we don't have that level of source info.
9798 Diag(SS.getRange().getBegin(),
9799 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009800 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009801 return true;
9802 }
9803
Douglas Gregor7c842292010-12-21 07:41:49 +00009804 if (!NamedContext->isDependentContext() &&
9805 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9806 return true;
9807
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009808 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009809 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009810 // In a using-declaration used as a member-declaration, the
9811 // nested-name-specifier shall name a base class of the class
9812 // being defined.
9813
9814 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9815 cast<CXXRecordDecl>(NamedContext))) {
9816 if (CurContext == NamedContext) {
9817 Diag(NameLoc,
9818 diag::err_using_decl_nested_name_specifier_is_current_class)
9819 << SS.getRange();
9820 return true;
9821 }
9822
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009823 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9824 Diag(SS.getRange().getBegin(),
9825 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9826 << SS.getScopeRep()
9827 << cast<CXXRecordDecl>(CurContext)
9828 << SS.getRange();
9829 }
John McCall3969e302009-12-08 07:46:18 +00009830 return true;
9831 }
9832
9833 return false;
9834 }
9835
9836 // C++03 [namespace.udecl]p4:
9837 // A using-declaration used as a member-declaration shall refer
9838 // to a member of a base class of the class being defined [etc.].
9839
9840 // Salient point: SS doesn't have to name a base class as long as
9841 // lookup only finds members from base classes. Therefore we can
9842 // diagnose here only if we can prove that that can't happen,
9843 // i.e. if the class hierarchies provably don't intersect.
9844
9845 // TODO: it would be nice if "definitely valid" results were cached
9846 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9847 // need to be repeated.
9848
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009849 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9850 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9851 Bases.insert(Base);
9852 return true;
John McCall3969e302009-12-08 07:46:18 +00009853 };
9854
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009855 // Collect all bases. Return false if we find a dependent base.
9856 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009857 return false;
9858
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009859 // Returns true if the base is dependent or is one of the accumulated base
9860 // classes.
9861 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9862 return !Bases.count(Base);
9863 };
9864
9865 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009866 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009867 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9868 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009869 return false;
9870
9871 Diag(SS.getRange().getBegin(),
9872 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009873 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009874 << cast<CXXRecordDecl>(CurContext)
9875 << SS.getRange();
9876
9877 return true;
John McCallb96ec562009-12-04 22:46:56 +00009878}
9879
Richard Smithdda56e42011-04-15 14:24:37 +00009880Decl *Sema::ActOnAliasDeclaration(Scope *S,
9881 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009882 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009883 SourceLocation UsingLoc,
9884 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009885 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009886 TypeResult Type,
9887 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009888 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009889 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009890 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009891 assert((S->getFlags() & Scope::DeclScope) &&
9892 "got alias-declaration outside of declaration scope");
9893
9894 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009895 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009896
9897 bool Invalid = false;
9898 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009899 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009900 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009901
9902 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009903 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009904
9905 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009906 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009907 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009908 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9909 TInfo->getTypeLoc().getBeginLoc());
9910 }
Richard Smithdda56e42011-04-15 14:24:37 +00009911
9912 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9913 LookupName(Previous, S);
9914
9915 // Warn about shadowing the name of a template parameter.
9916 if (Previous.isSingleResult() &&
9917 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009918 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009919 Previous.clear();
9920 }
9921
9922 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9923 "name in alias declaration must be an identifier");
9924 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9925 Name.StartLocation,
9926 Name.Identifier, TInfo);
9927
9928 NewTD->setAccess(AS);
9929
9930 if (Invalid)
9931 NewTD->setInvalidDecl();
9932
Richard Smith54ecd982013-02-20 19:22:51 +00009933 ProcessDeclAttributeList(S, NewTD, AttrList);
9934
Richard Smith3f1b5d02011-05-05 21:57:07 +00009935 CheckTypedefForVariablyModifiedType(S, NewTD);
9936 Invalid |= NewTD->isInvalidDecl();
9937
Richard Smithdda56e42011-04-15 14:24:37 +00009938 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009939
9940 NamedDecl *NewND;
9941 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009942 TypeAliasTemplateDecl *OldDecl = nullptr;
9943 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009944
9945 if (TemplateParamLists.size() != 1) {
9946 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009947 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9948 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009949 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009950 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009951
Richard Smith882593f2016-04-06 17:38:58 +00009952 // Check that we can declare a template here.
9953 if (CheckTemplateDeclScope(S, TemplateParams))
9954 return nullptr;
9955
Richard Smith3f1b5d02011-05-05 21:57:07 +00009956 // Only consider previous declarations in the same scope.
9957 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9958 /*ExplicitInstantiationOrSpecialization*/false);
9959 if (!Previous.empty()) {
9960 Redeclaration = true;
9961
9962 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9963 if (!OldDecl && !Invalid) {
9964 Diag(UsingLoc, diag::err_redefinition_different_kind)
9965 << Name.Identifier;
9966
9967 NamedDecl *OldD = Previous.getRepresentativeDecl();
9968 if (OldD->getLocation().isValid())
9969 Diag(OldD->getLocation(), diag::note_previous_definition);
9970
9971 Invalid = true;
9972 }
9973
9974 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9975 if (TemplateParameterListsAreEqual(TemplateParams,
9976 OldDecl->getTemplateParameters(),
9977 /*Complain=*/true,
9978 TPL_TemplateMatch))
9979 OldTemplateParams = OldDecl->getTemplateParameters();
9980 else
9981 Invalid = true;
9982
9983 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9984 if (!Invalid &&
9985 !Context.hasSameType(OldTD->getUnderlyingType(),
9986 NewTD->getUnderlyingType())) {
9987 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9988 // but we can't reasonably accept it.
9989 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9990 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9991 if (OldTD->getLocation().isValid())
9992 Diag(OldTD->getLocation(), diag::note_previous_definition);
9993 Invalid = true;
9994 }
9995 }
9996 }
9997
9998 // Merge any previous default template arguments into our parameters,
9999 // and check the parameter list.
10000 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10001 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +000010002 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +000010003
10004 TypeAliasTemplateDecl *NewDecl =
10005 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10006 Name.Identifier, TemplateParams,
10007 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +000010008 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010009
10010 NewDecl->setAccess(AS);
10011
10012 if (Invalid)
10013 NewDecl->setInvalidDecl();
10014 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +000010015 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010016
10017 NewND = NewDecl;
10018 } else {
David Majnemerf9bde282015-03-11 06:45:39 +000010019 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10020 setTagNameForLinkagePurposes(TD, NewTD);
10021 handleTagNumbering(TD, S);
10022 }
Richard Smith3f1b5d02011-05-05 21:57:07 +000010023 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10024 NewND = NewTD;
10025 }
Richard Smithdda56e42011-04-15 14:24:37 +000010026
Richard Smith3cbf3f12016-07-15 20:53:25 +000010027 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +000010028 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010029 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +000010030}
10031
Richard Smithf4634362014-09-03 23:11:22 +000010032Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10033 SourceLocation AliasLoc,
10034 IdentifierInfo *Alias, CXXScopeSpec &SS,
10035 SourceLocation IdentLoc,
10036 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +000010037
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010038 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +000010039 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10040 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010041
John McCall27b18f82009-11-17 02:14:36 +000010042 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010043 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +000010044
John McCall9f3059a2009-10-09 21:13:30 +000010045 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +000010046 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +000010047 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010048 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +000010049 }
Anders Carlssonac2c9652009-03-28 06:42:02 +000010050 }
Richard Smithf4634362014-09-03 23:11:22 +000010051 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +000010052 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +000010053
10054 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +000010055 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10056 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +000010057 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +000010058
Richard Smith2b2a1762015-12-03 23:24:04 +000010059 // Check we're not shadowing a template parameter.
10060 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10061 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10062 PrevR.clear();
10063 }
Aaron Ballman43f40102014-11-14 22:34:56 +000010064
Richard Smith2b2a1762015-12-03 23:24:04 +000010065 // Filter out any other lookup result from an enclosing scope.
10066 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10067 /*AllowInlineNamespace*/false);
10068
10069 // Find the previous declaration and check that we can redeclare it.
10070 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +000010071 if (PrevR.isSingleResult()) {
10072 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10073 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010074 // We already have an alias with the same name that points to the same
10075 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +000010076 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10077 Prev = AD;
10078 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010079 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10080 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +000010081 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +000010082 << AD->getNamespace();
10083 return nullptr;
10084 }
Richard Smith2b2a1762015-12-03 23:24:04 +000010085 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +000010086 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +000010087 ? diag::err_redefinition
10088 : diag::err_redefinition_different_kind;
10089 Diag(AliasLoc, DiagID) << Alias;
10090 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10091 return nullptr;
10092 }
10093 }
Mike Stump11289f42009-09-09 15:08:12 +000010094
Nico Riecke50e59a2014-11-24 17:29:52 +000010095 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +000010096 DiagnoseUseOfDecl(ND, IdentLoc);
10097
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010098 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +000010099 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +000010100 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +000010101 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +000010102 if (Prev)
10103 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +000010104
John McCalld8d0d432010-02-16 06:53:13 +000010105 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +000010106 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +000010107}
10108
Richard Smith2246c832017-02-24 01:29:42 +000010109namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +000010110struct SpecialMemberExceptionSpecInfo
10111 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
Richard Smith2246c832017-02-24 01:29:42 +000010112 SourceLocation Loc;
10113 Sema::ImplicitExceptionSpecification ExceptSpec;
10114
Richard Smith2246c832017-02-24 01:29:42 +000010115 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10116 Sema::CXXSpecialMember CSM,
10117 Sema::InheritedConstructorInfo *ICI,
10118 SourceLocation Loc)
Richard Smith8bae1be2017-02-24 02:07:20 +000010119 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
Richard Smith2246c832017-02-24 01:29:42 +000010120
Richard Smith6f0e63e2017-02-24 21:18:47 +000010121 bool visitBase(CXXBaseSpecifier *Base);
10122 bool visitField(FieldDecl *FD);
Richard Smith2246c832017-02-24 01:29:42 +000010123
10124 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10125 unsigned Quals);
10126
10127 void visitSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +000010128 Sema::SpecialMemberOverloadResult SMOR);
Richard Smith2246c832017-02-24 01:29:42 +000010129};
10130}
10131
Richard Smith6f0e63e2017-02-24 21:18:47 +000010132bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
Richard Smith2246c832017-02-24 01:29:42 +000010133 auto *RT = Base->getType()->getAs<RecordType>();
10134 if (!RT)
Richard Smith6f0e63e2017-02-24 21:18:47 +000010135 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010136
10137 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith6f0e63e2017-02-24 21:18:47 +000010138 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10139 if (auto *BaseCtor = SMOR.getMethod()) {
10140 visitSubobjectCall(Base, BaseCtor);
10141 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010142 }
10143
10144 visitClassSubobject(BaseClass, Base, 0);
Richard Smith6f0e63e2017-02-24 21:18:47 +000010145 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010146}
10147
Richard Smith6f0e63e2017-02-24 21:18:47 +000010148bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
Richard Smith2246c832017-02-24 01:29:42 +000010149 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10150 Expr *E = FD->getInClassInitializer();
10151 if (!E)
10152 // FIXME: It's a little wasteful to build and throw away a
10153 // CXXDefaultInitExpr here.
10154 // FIXME: We should have a single context note pointing at Loc, and
10155 // this location should be MD->getLocation() instead, since that's
10156 // the location where we actually use the default init expression.
10157 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10158 if (E)
10159 ExceptSpec.CalledExpr(E);
10160 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10161 ->getAs<RecordType>()) {
10162 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10163 FD->getType().getCVRQualifiers());
10164 }
Richard Smith6f0e63e2017-02-24 21:18:47 +000010165 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010166}
10167
10168void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10169 Subobject Subobj,
10170 unsigned Quals) {
10171 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10172 bool IsMutable = Field && Field->isMutable();
10173 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10174}
10175
10176void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +000010177 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
Richard Smith2246c832017-02-24 01:29:42 +000010178 // Note, if lookup fails, it doesn't matter what exception specification we
10179 // choose because the special member will be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +000010180 if (CXXMethodDecl *MD = SMOR.getMethod())
10181 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
Richard Smith2246c832017-02-24 01:29:42 +000010182}
10183
10184static Sema::ImplicitExceptionSpecification
10185ComputeDefaultedSpecialMemberExceptionSpec(
10186 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10187 Sema::InheritedConstructorInfo *ICI) {
Richard Smithd3b5c9082012-07-27 04:22:15 +000010188 CXXRecordDecl *ClassDecl = MD->getParent();
10189
Douglas Gregor6d880b12010-07-01 22:31:05 +000010190 // C++ [except.spec]p14:
10191 // An implicitly declared special member function (Clause 12) shall have an
10192 // exception-specification. [...]
Richard Smith2246c832017-02-24 01:29:42 +000010193 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010194 if (ClassDecl->isInvalidDecl())
Richard Smith2246c832017-02-24 01:29:42 +000010195 return Info.ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +000010196
Richard Smith6f0e63e2017-02-24 21:18:47 +000010197 // C++1z [except.spec]p7:
10198 // [Look for exceptions thrown by] a constructor selected [...] to
10199 // initialize a potentially constructed subobject,
10200 // C++1z [except.spec]p8:
10201 // The exception specification for an implicitly-declared destructor, or a
10202 // destructor without a noexcept-specifier, is potentially-throwing if and
10203 // only if any of the destructors for any of its potentially constructed
10204 // subojects is potentially throwing.
Richard Smithdf054d32017-02-25 23:53:05 +000010205 // FIXME: We respect the first rule but ignore the "potentially constructed"
10206 // in the second rule to resolve a core issue (no number yet) that would have
10207 // us reject:
Richard Smith6f0e63e2017-02-24 21:18:47 +000010208 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10209 // struct B : A {};
10210 // struct C : B { void f(); };
10211 // ... due to giving B::~B() a non-throwing exception specification.
Richard Smithdf054d32017-02-25 23:53:05 +000010212 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10213 : Info.VisitAllBases);
John McCalldb40c7f2010-12-14 08:05:40 +000010214
Richard Smith2246c832017-02-24 01:29:42 +000010215 return Info.ExceptSpec;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010216}
10217
Richard Smith8bf22e52012-11-29 01:34:07 +000010218namespace {
10219/// RAII object to register a special member as being currently declared.
10220struct DeclaringSpecialMember {
10221 Sema &S;
10222 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +000010223 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +000010224 bool WasAlreadyBeingDeclared;
10225
10226 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith13381222017-02-23 21:43:43 +000010227 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +000010228 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +000010229 if (WasAlreadyBeingDeclared)
10230 // This almost never happens, but if it does, ensure that our cache
10231 // doesn't contain a stale result.
10232 S.SpecialMemberCache.clear();
Richard Smith13381222017-02-23 21:43:43 +000010233 else {
10234 // Register a note to be produced if we encounter an error while
10235 // declaring the special member.
10236 Sema::CodeSynthesisContext Ctx;
10237 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10238 // FIXME: We don't have a location to use here. Using the class's
10239 // location maintains the fiction that we declare all special members
10240 // with the class, but (1) it's not clear that lying about that helps our
10241 // users understand what's going on, and (2) there may be outer contexts
10242 // on the stack (some of which are relevant) and printing them exposes
10243 // our lies.
10244 Ctx.PointOfInstantiation = RD->getLocation();
10245 Ctx.Entity = RD;
10246 Ctx.SpecialMember = CSM;
10247 S.pushCodeSynthesisContext(Ctx);
10248 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010249 }
10250 ~DeclaringSpecialMember() {
Richard Smith13381222017-02-23 21:43:43 +000010251 if (!WasAlreadyBeingDeclared) {
Richard Smith8bf22e52012-11-29 01:34:07 +000010252 S.SpecialMembersBeingDeclared.erase(D);
Richard Smith13381222017-02-23 21:43:43 +000010253 S.popCodeSynthesisContext();
10254 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010255 }
10256
10257 /// \brief Are we already trying to declare this special member?
10258 bool isAlreadyBeingDeclared() const {
10259 return WasAlreadyBeingDeclared;
10260 }
10261};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010262}
Richard Smith8bf22e52012-11-29 01:34:07 +000010263
Richard Smith12e79312016-05-13 06:47:56 +000010264void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10265 // Look up any existing declarations, but don't trigger declaration of all
10266 // implicit special members with this name.
10267 DeclarationName Name = FD->getDeclName();
10268 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10269 ForRedeclaration);
10270 for (auto *D : FD->getParent()->lookup(Name))
10271 if (auto *Acceptable = R.getAcceptableDecl(D))
10272 R.addDecl(Acceptable);
10273 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +000010274 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +000010275
Richard Smithf445f192017-02-09 21:04:43 +000010276 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
Richard Smith12e79312016-05-13 06:47:56 +000010277}
10278
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010279CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10280 CXXRecordDecl *ClassDecl) {
10281 // C++ [class.ctor]p5:
10282 // A default constructor for a class X is a constructor of class X
10283 // that can be called without an argument. If there is no
10284 // user-declared constructor for class X, a default constructor is
10285 // implicitly declared. An implicitly-declared default constructor
10286 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010287 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010288 "Should not build implicit default constructor!");
10289
Richard Smith8bf22e52012-11-29 01:34:07 +000010290 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10291 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010292 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010293
Richard Smithb5800092012-06-10 05:43:50 +000010294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10295 CXXDefaultConstructor,
10296 false);
10297
Douglas Gregor6d880b12010-07-01 22:31:05 +000010298 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010299 CanQualType ClassType
10300 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010301 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010302 DeclarationName Name
10303 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010304 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +000010305 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010306 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10307 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10308 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010309 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +000010310 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010311
10312 if (getLangOpts().CUDA) {
10313 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10314 DefaultCon,
10315 /* ConstRHS */ false,
10316 /* Diagnose */ false);
10317 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010318
10319 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010320 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010321 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010322
Richard Smith6b02d462012-12-08 08:32:28 +000010323 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10324 // constructors is easy to compute.
10325 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10326
Douglas Gregor9672f922010-07-03 00:47:00 +000010327 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +000010328 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +000010329
Richard Smith12e79312016-05-13 06:47:56 +000010330 Scope *S = getScopeForContext(ClassDecl);
10331 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10332
10333 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10334 SetDeclDeleted(DefaultCon, ClassLoc);
10335
10336 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +000010337 PushOnScopeChains(DefaultCon, S, false);
10338 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +000010339
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010340 return DefaultCon;
10341}
10342
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010343void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10344 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010345 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010346 !Constructor->doesThisDeclarationHaveABody() &&
10347 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010348 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010349
Anders Carlsson423f5d82010-04-23 16:04:08 +000010350 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010351 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010352
Eli Friedmaneaf34142012-10-18 20:14:08 +000010353 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010354 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +000010355 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010356 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010357 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +000010358 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +000010359 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +000010360 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +000010361 }
Douglas Gregor73193272010-09-20 16:48:21 +000010362
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010363 // The exception specification is needed because we are defining the
10364 // function.
10365 ResolveExceptionSpec(CurrentLocation,
10366 Constructor->getType()->castAs<FunctionProtoType>());
10367
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010368 SourceLocation Loc = Constructor->getLocEnd().isValid()
10369 ? Constructor->getLocEnd()
10370 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010371 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010372
Eli Friedman276dd182013-09-05 00:02:25 +000010373 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010374 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010375
10376 if (ASTMutationListener *L = getASTMutationListener()) {
10377 L->CompletedImplicitDefinition(Constructor);
10378 }
Richard Trieuef64e942013-10-25 00:56:00 +000010379
10380 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010381}
10382
Richard Smith938f40b2011-06-11 17:19:42 +000010383void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010384 // Perform any delayed checks on exception specifications.
10385 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010386}
10387
Richard Smith5179eb72016-06-28 19:03:57 +000010388/// Find or create the fake constructor we synthesize to model constructing an
10389/// object of a derived class via a constructor of a base class.
10390CXXConstructorDecl *
10391Sema::findInheritingConstructor(SourceLocation Loc,
10392 CXXConstructorDecl *BaseCtor,
10393 ConstructorUsingShadowDecl *Shadow) {
10394 CXXRecordDecl *Derived = Shadow->getParent();
10395 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010396
Richard Smith5179eb72016-06-28 19:03:57 +000010397 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10398 // For now we use the name of the base class constructor as a member of the
10399 // derived class to indicate a (fake) inherited constructor name.
10400 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010401
Richard Smith5179eb72016-06-28 19:03:57 +000010402 // Check to see if we already have a fake constructor for this inherited
10403 // constructor call.
10404 for (NamedDecl *Ctor : Derived->lookup(Name))
10405 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10406 ->getInheritedConstructor()
10407 .getConstructor(),
10408 BaseCtor))
10409 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010410
Richard Smith5179eb72016-06-28 19:03:57 +000010411 DeclarationNameInfo NameInfo(Name, UsingLoc);
10412 TypeSourceInfo *TInfo =
10413 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10414 FunctionProtoTypeLoc ProtoLoc =
10415 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010416
Richard Smith5179eb72016-06-28 19:03:57 +000010417 // Check the inherited constructor is valid and find the list of base classes
10418 // from which it was inherited.
10419 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010420
Richard Smith5179eb72016-06-28 19:03:57 +000010421 bool Constexpr =
10422 BaseCtor->isConstexpr() &&
10423 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10424 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010425
Richard Smith5179eb72016-06-28 19:03:57 +000010426 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10427 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10428 BaseCtor->isExplicit(), /*Inline=*/true,
10429 /*ImplicitlyDeclared=*/true, Constexpr,
10430 InheritedConstructor(Shadow, BaseCtor));
10431 if (Shadow->isInvalidDecl())
10432 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010433
Richard Smith5179eb72016-06-28 19:03:57 +000010434 // Build an unevaluated exception specification for this fake constructor.
10435 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10436 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10437 EPI.ExceptionSpec.Type = EST_Unevaluated;
10438 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10439 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10440 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010441
Richard Smith5179eb72016-06-28 19:03:57 +000010442 // Build the parameter declarations.
10443 SmallVector<ParmVarDecl *, 16> ParamDecls;
10444 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010445 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010446 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10447 ParmVarDecl *PD = ParmVarDecl::Create(
10448 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10449 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10450 PD->setScopeInfo(0, I);
10451 PD->setImplicit();
10452 // Ensure attributes are propagated onto parameters (this matters for
10453 // format, pass_object_size, ...).
10454 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10455 ParamDecls.push_back(PD);
10456 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010457 }
10458
Richard Smith5179eb72016-06-28 19:03:57 +000010459 // Set up the new constructor.
10460 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10461 DerivedCtor->setAccess(BaseCtor->getAccess());
10462 DerivedCtor->setParams(ParamDecls);
10463 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010464
10465 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10466 SetDeclDeleted(DerivedCtor, UsingLoc);
10467
Richard Smith5179eb72016-06-28 19:03:57 +000010468 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010469}
10470
Richard Smith80a47022016-06-29 01:10:27 +000010471void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10472 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10473 Ctor->getInheritedConstructor().getShadowDecl());
10474 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10475 /*Diagnose*/true);
10476}
10477
Richard Smithc2bc61b2013-03-18 21:12:30 +000010478void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10479 CXXConstructorDecl *Constructor) {
10480 CXXRecordDecl *ClassDecl = Constructor->getParent();
10481 assert(Constructor->getInheritedConstructor() &&
10482 !Constructor->doesThisDeclarationHaveABody() &&
10483 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010484 if (Constructor->isInvalidDecl())
10485 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010486
Richard Smith5179eb72016-06-28 19:03:57 +000010487 ConstructorUsingShadowDecl *Shadow =
10488 Constructor->getInheritedConstructor().getShadowDecl();
10489 CXXConstructorDecl *InheritedCtor =
10490 Constructor->getInheritedConstructor().getConstructor();
10491
10492 // [class.inhctor.init]p1:
10493 // initialization proceeds as if a defaulted default constructor is used to
10494 // initialize the D object and each base class subobject from which the
10495 // constructor was inherited
10496
10497 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10498 CXXRecordDecl *RD = Shadow->getParent();
10499 SourceLocation InitLoc = Shadow->getLocation();
10500
10501 // Initializations are performed "as if by a defaulted default constructor",
10502 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010503 SynthesizedFunctionScope Scope(*this, Constructor);
10504 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010505
10506 // Build explicit initializers for all base classes from which the
10507 // constructor was inherited.
10508 SmallVector<CXXCtorInitializer*, 8> Inits;
10509 for (bool VBase : {false, true}) {
10510 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10511 if (B.isVirtual() != VBase)
10512 continue;
10513
10514 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10515 if (!BaseRD)
10516 continue;
10517
10518 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10519 if (!BaseCtor.first)
10520 continue;
10521
10522 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10523 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10524 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10525
10526 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10527 Inits.push_back(new (Context) CXXCtorInitializer(
10528 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10529 SourceLocation()));
10530 }
10531 }
10532
10533 // We now proceed as if for a defaulted default constructor, with the relevant
10534 // initializers replaced.
10535
10536 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10537 if (HadError || Trap.hasErrorOccurred()) {
10538 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010539 Constructor->setInvalidDecl();
10540 return;
10541 }
10542
Richard Smith5179eb72016-06-28 19:03:57 +000010543 // The exception specification is needed because we are defining the
10544 // function.
10545 ResolveExceptionSpec(CurrentLocation,
10546 Constructor->getType()->castAs<FunctionProtoType>());
10547
10548 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010549
Eli Friedman276dd182013-09-05 00:02:25 +000010550 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010551 MarkVTableUsed(CurrentLocation, ClassDecl);
10552
10553 if (ASTMutationListener *L = getASTMutationListener()) {
10554 L->CompletedImplicitDefinition(Constructor);
10555 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010556
Richard Smith5179eb72016-06-28 19:03:57 +000010557 DiagnoseUninitializedFields(*this, Constructor);
10558}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010559
Alexis Huntf91729462011-05-12 22:46:25 +000010560CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10561 // C++ [class.dtor]p2:
10562 // If a class has no user-declared destructor, a destructor is
10563 // declared implicitly. An implicitly-declared destructor is an
10564 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010565 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010566
Richard Smith8bf22e52012-11-29 01:34:07 +000010567 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10568 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010569 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010570
Douglas Gregor7454c562010-07-02 20:37:36 +000010571 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010572 CanQualType ClassType
10573 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010574 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010575 DeclarationName Name
10576 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010577 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010578 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010579 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010580 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010581 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010582 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010583 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010584
10585 if (getLangOpts().CUDA) {
10586 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10587 Destructor,
10588 /* ConstRHS */ false,
10589 /* Diagnose */ false);
10590 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010591
10592 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010593 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010594 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010595
Richard Smith6b02d462012-12-08 08:32:28 +000010596 // We don't need to use SpecialMemberIsTrivial here; triviality for
10597 // destructors is easy to compute.
10598 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10599
Douglas Gregor7454c562010-07-02 20:37:36 +000010600 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010601 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010602
Richard Smith12e79312016-05-13 06:47:56 +000010603 Scope *S = getScopeForContext(ClassDecl);
10604 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10605
Richard Smithb2f0f052016-10-10 18:54:32 +000010606 // We can't check whether an implicit destructor is deleted before we complete
10607 // the definition of the class, because its validity depends on the alignment
10608 // of the class. We'll check this from ActOnFields once the class is complete.
10609 if (ClassDecl->isCompleteDefinition() &&
10610 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010611 SetDeclDeleted(Destructor, ClassLoc);
10612
Douglas Gregor7454c562010-07-02 20:37:36 +000010613 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010614 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010615 PushOnScopeChains(Destructor, S, false);
10616 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010617
Douglas Gregorf1203042010-07-01 19:09:28 +000010618 return Destructor;
10619}
10620
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010621void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010622 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010623 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010624 !Destructor->doesThisDeclarationHaveABody() &&
10625 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010626 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010627 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010628 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010629
Douglas Gregor54818f02010-05-12 16:39:35 +000010630 if (Destructor->isInvalidDecl())
10631 return;
10632
Eli Friedmaneaf34142012-10-18 20:14:08 +000010633 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010634
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010635 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010636 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10637 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010638
Douglas Gregor54818f02010-05-12 16:39:35 +000010639 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010640 Diag(CurrentLocation, diag::note_member_synthesized_at)
10641 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10642
10643 Destructor->setInvalidDecl();
10644 return;
10645 }
10646
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010647 // The exception specification is needed because we are defining the
10648 // function.
10649 ResolveExceptionSpec(CurrentLocation,
10650 Destructor->getType()->castAs<FunctionProtoType>());
10651
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010652 SourceLocation Loc = Destructor->getLocEnd().isValid()
10653 ? Destructor->getLocEnd()
10654 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010655 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010656 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010657 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010658
10659 if (ASTMutationListener *L = getASTMutationListener()) {
10660 L->CompletedImplicitDefinition(Destructor);
10661 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010662}
10663
Richard Smith84973e52012-04-21 18:42:51 +000010664/// \brief Perform any semantic analysis which needs to be delayed until all
10665/// pending class member declarations have been parsed.
10666void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010667 // If the context is an invalid C++ class, just suppress these checks.
10668 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10669 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010670 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010671 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010672 return;
10673 }
Reid Kleckner61195e12017-01-05 01:08:22 +000010674 checkForMultipleExportedDefaultConstructors(*this, Record);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010675 }
10676}
10677
Hans Wennborg99000c22015-08-15 01:18:16 +000010678void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Kleckner5b640342016-02-26 19:51:02 +000010679 referenceDLLExportedClassMethods();
10680}
10681
10682void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010683 if (!DelayedDllExportClasses.empty()) {
10684 // Calling ReferenceDllExportedMethods might cause the current function to
10685 // be called again, so use a local copy of DelayedDllExportClasses.
10686 SmallVector<CXXRecordDecl *, 4> WorkList;
10687 std::swap(DelayedDllExportClasses, WorkList);
10688 for (CXXRecordDecl *Class : WorkList)
10689 ReferenceDllExportedMethods(*this, Class);
10690 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010691}
10692
Richard Smithd3b5c9082012-07-27 04:22:15 +000010693void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10694 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010695 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010696 "adjusting dtor exception specs was introduced in c++11");
10697
Sebastian Redl623ea822011-05-19 05:13:44 +000010698 // C++11 [class.dtor]p3:
10699 // A declaration of a destructor that does not have an exception-
10700 // specification is implicitly considered to have the same exception-
10701 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010702 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010703 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010704 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010705 return;
10706
Chandler Carruth9a797572011-09-20 04:55:26 +000010707 // Replace the destructor's type, building off the existing one. Fortunately,
10708 // the only thing of interest in the destructor type is its extended info.
10709 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010710 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010711 EPI.ExceptionSpec.Type = EST_Unevaluated;
10712 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010713 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010714
Sebastian Redl623ea822011-05-19 05:13:44 +000010715 // FIXME: If the destructor has a body that could throw, and the newly created
10716 // spec doesn't allow exceptions, we should emit a warning, because this
10717 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010718 // However, we don't have a body or an exception specification yet, so it
10719 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010720}
10721
Pavel Labath58934982013-08-30 08:52:28 +000010722namespace {
10723/// \brief An abstract base class for all helper classes used in building the
10724// copy/move operators. These classes serve as factory functions and help us
10725// avoid using the same Expr* in the AST twice.
10726class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010727 ExprBuilder(const ExprBuilder&) = delete;
10728 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010729
10730protected:
10731 static Expr *assertNotNull(Expr *E) {
10732 assert(E && "Expression construction must not fail.");
10733 return E;
10734 }
10735
10736public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010737 ExprBuilder() {}
10738 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010739
10740 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10741};
10742
10743class RefBuilder: public ExprBuilder {
10744 VarDecl *Var;
10745 QualType VarType;
10746
10747public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010748 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010749 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010750 }
10751
10752 RefBuilder(VarDecl *Var, QualType VarType)
10753 : Var(Var), VarType(VarType) {}
10754};
10755
10756class ThisBuilder: public ExprBuilder {
10757public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010758 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010759 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010760 }
10761};
10762
10763class CastBuilder: public ExprBuilder {
10764 const ExprBuilder &Builder;
10765 QualType Type;
10766 ExprValueKind Kind;
10767 const CXXCastPath &Path;
10768
10769public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010770 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010771 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10772 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010773 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010774 }
10775
10776 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10777 const CXXCastPath &Path)
10778 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10779};
10780
10781class DerefBuilder: public ExprBuilder {
10782 const ExprBuilder &Builder;
10783
10784public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010785 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010786 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010787 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010788 }
10789
10790 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10791};
10792
10793class MemberBuilder: public ExprBuilder {
10794 const ExprBuilder &Builder;
10795 QualType Type;
10796 CXXScopeSpec SS;
10797 bool IsArrow;
10798 LookupResult &MemberLookup;
10799
10800public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010801 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010802 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010803 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010804 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010805 }
10806
10807 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10808 LookupResult &MemberLookup)
10809 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10810 MemberLookup(MemberLookup) {}
10811};
10812
10813class MoveCastBuilder: public ExprBuilder {
10814 const ExprBuilder &Builder;
10815
10816public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010817 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010818 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10819 }
10820
10821 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10822};
10823
10824class LvalueConvBuilder: public ExprBuilder {
10825 const ExprBuilder &Builder;
10826
10827public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010828 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010829 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010830 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010831 }
10832
10833 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10834};
10835
10836class SubscriptBuilder: public ExprBuilder {
10837 const ExprBuilder &Base;
10838 const ExprBuilder &Index;
10839
10840public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010841 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010842 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010843 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010844 }
10845
10846 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10847 : Base(Base), Index(Index) {}
10848};
10849
10850} // end anonymous namespace
10851
Richard Smith41ae3282012-11-14 00:50:40 +000010852/// When generating a defaulted copy or move assignment operator, if a field
10853/// should be copied with __builtin_memcpy rather than via explicit assignments,
10854/// do so. This optimization only applies for arrays of scalars, and for arrays
10855/// of class type where the selected copy/move-assignment operator is trivial.
10856static StmtResult
10857buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010858 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010859 // Compute the size of the memory buffer to be copied.
10860 QualType SizeType = S.Context.getSizeType();
10861 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10862 S.Context.getTypeSizeInChars(T).getQuantity());
10863
10864 // Take the address of the field references for "from" and "to". We
10865 // directly construct UnaryOperators here because semantic analysis
10866 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010867 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010868 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10869 S.Context.getPointerType(From->getType()),
10870 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010871 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010872 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10873 S.Context.getPointerType(To->getType()),
10874 VK_RValue, OK_Ordinary, Loc);
10875
10876 const Type *E = T->getBaseElementTypeUnsafe();
10877 bool NeedsCollectableMemCpy =
10878 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10879
10880 // Create a reference to the __builtin_objc_memmove_collectable function
10881 StringRef MemCpyName = NeedsCollectableMemCpy ?
10882 "__builtin_objc_memmove_collectable" :
10883 "__builtin_memcpy";
10884 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10885 Sema::LookupOrdinaryName);
10886 S.LookupName(R, S.TUScope, true);
10887
10888 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10889 if (!MemCpy)
10890 // Something went horribly wrong earlier, and we will have complained
10891 // about it.
10892 return StmtError();
10893
10894 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010895 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010896 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10897
10898 Expr *CallArgs[] = {
10899 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10900 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010901 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010902 Loc, CallArgs, Loc);
10903
10904 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010905 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010906}
10907
Sebastian Redl22653ba2011-08-30 19:58:05 +000010908/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010909/// \c To.
10910///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010911/// This routine is used to copy/move the members of a class with an
10912/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010913/// copied are arrays, this routine builds for loops to copy them.
10914///
10915/// \param S The Sema object used for type-checking.
10916///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010917/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010918///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010919/// \param T The type of the expressions being copied/moved. Both expressions
10920/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010921///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010922/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010923///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010924/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010925///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010926/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010927/// Otherwise, it's a non-static member subobject.
10928///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010929/// \param Copying Whether we're copying or moving.
10930///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010931/// \param Depth Internal parameter recording the depth of the recursion.
10932///
Richard Smith41ae3282012-11-14 00:50:40 +000010933/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10934/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010935static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010936buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010937 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010938 bool CopyingBaseSubobject, bool Copying,
10939 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010940 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010941 // Each subobject is assigned in the manner appropriate to its type:
10942 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010943 // - if the subobject is of class type, as if by a call to operator= with
10944 // the subobject as the object expression and the corresponding
10945 // subobject of x as a single function argument (as if by explicit
10946 // qualification; that is, ignoring any possible virtual overriding
10947 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010948 //
10949 // C++03 [class.copy]p13:
10950 // - if the subobject is of class type, the copy assignment operator for
10951 // the class is used (as if by explicit qualification; that is,
10952 // ignoring any possible virtual overriding functions in more derived
10953 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010954 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10955 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010956
Douglas Gregorb139cd52010-05-01 20:49:11 +000010957 // Look for operator=.
10958 DeclarationName Name
10959 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10960 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10961 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010962
Richard Smith52c0b582012-11-13 00:54:12 +000010963 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10964 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010965 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010966 LookupResult::Filter F = OpLookup.makeFilter();
10967 while (F.hasNext()) {
10968 NamedDecl *D = F.next();
10969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10970 if (Method->isCopyAssignmentOperator() ||
10971 (!Copying && Method->isMoveAssignmentOperator()))
10972 continue;
10973
10974 F.erase();
10975 }
10976 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010977 }
Richard Smith52c0b582012-11-13 00:54:12 +000010978
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010979 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010980 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010981 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010982 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010983 // ambiguities), we need to cast "this" to that subobject type; to
10984 // ensure that we don't go through the virtual call mechanism, we need
10985 // to qualify the operator= name with the base class (see below). However,
10986 // this means that if the base class has a protected copy assignment
10987 // operator, the protected member access check will fail. So, we
10988 // rewrite "protected" access to "public" access in this case, since we
10989 // know by construction that we're calling from a derived class.
10990 if (CopyingBaseSubobject) {
10991 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10992 L != LEnd; ++L) {
10993 if (L.getAccess() == AS_protected)
10994 L.setAccess(AS_public);
10995 }
10996 }
Richard Smith52c0b582012-11-13 00:54:12 +000010997
Douglas Gregorb139cd52010-05-01 20:49:11 +000010998 // Create the nested-name-specifier that will be used to qualify the
10999 // reference to operator=; this is required to suppress the virtual
11000 // call mechanism.
11001 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000011002 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000011003 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000011004 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000011005 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000011006 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000011007
Douglas Gregorb139cd52010-05-01 20:49:11 +000011008 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000011009 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000011010 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11011 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011012 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000011013 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011014 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011015 /*SuppressQualifierCheck=*/true);
11016 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011017 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011018
Douglas Gregorb139cd52010-05-01 20:49:11 +000011019 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000011020
Pavel Labath58934982013-08-30 08:52:28 +000011021 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000011022 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011023 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000011024 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011025 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011026 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011027
Richard Smith41ae3282012-11-14 00:50:40 +000011028 // If we built a call to a trivial 'operator=' while copying an array,
11029 // bail out. We'll replace the whole shebang with a memcpy.
11030 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11031 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000011032 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000011033
Richard Smith52c0b582012-11-13 00:54:12 +000011034 // Convert to an expression-statement, and clean up any produced
11035 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000011036 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011037 }
John McCallab8c2732010-03-16 06:11:48 +000011038
Richard Smith52c0b582012-11-13 00:54:12 +000011039 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000011040 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000011041 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011042 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000011043 ExprResult Assignment = S.CreateBuiltinBinOp(
11044 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011045 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011046 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000011047 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011048 }
Richard Smith52c0b582012-11-13 00:54:12 +000011049
11050 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000011051 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000011052
Douglas Gregorb139cd52010-05-01 20:49:11 +000011053 // Construct a loop over the array bounds, e.g.,
11054 //
11055 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11056 //
11057 // that will copy each of the array elements.
11058 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000011059
Douglas Gregorb139cd52010-05-01 20:49:11 +000011060 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000011061 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011062 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000011063 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011064 llvm::raw_svector_ostream OS(Str);
11065 OS << "__i" << Depth;
11066 IterationVarName = &S.Context.Idents.get(OS.str());
11067 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000011068 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011069 IterationVarName, SizeType,
11070 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011071 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000011072
Douglas Gregorb139cd52010-05-01 20:49:11 +000011073 // Initialize the iteration variable to zero.
11074 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011075 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011076
Pavel Labath58934982013-08-30 08:52:28 +000011077 // Creates a reference to the iteration variable.
11078 RefBuilder IterationVarRef(IterationVar, SizeType);
11079 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000011080
Douglas Gregorb139cd52010-05-01 20:49:11 +000011081 // Create the DeclStmt that holds the iteration variable.
11082 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011083
Douglas Gregorb139cd52010-05-01 20:49:11 +000011084 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000011085 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11086 MoveCastBuilder FromIndexMove(FromIndexCopy);
11087 const ExprBuilder *FromIndex;
11088 if (Copying)
11089 FromIndex = &FromIndexCopy;
11090 else
11091 FromIndex = &FromIndexMove;
11092
11093 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011094
11095 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000011096 StmtResult Copy =
11097 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000011098 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000011099 Copying, Depth + 1);
11100 // Bail out if copying fails or if we determined that we should use memcpy.
11101 if (Copy.isInvalid() || !Copy.get())
11102 return Copy;
11103
11104 // Create the comparison against the array bound.
11105 llvm::APInt Upper
11106 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11107 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000011108 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000011109 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11110 BO_NE, S.Context.BoolTy,
Adam Nemet484aa452017-03-27 19:17:25 +000011111 VK_RValue, OK_Ordinary, Loc, FPOptions());
Richard Smith41ae3282012-11-14 00:50:40 +000011112
11113 // Create the pre-increment of the iteration variable.
11114 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000011115 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11116 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011117
Douglas Gregorb139cd52010-05-01 20:49:11 +000011118 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000011119 return S.ActOnForStmt(
11120 Loc, Loc, InitStmt,
11121 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11122 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011123}
11124
Richard Smith41ae3282012-11-14 00:50:40 +000011125static StmtResult
11126buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000011127 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000011128 bool CopyingBaseSubobject, bool Copying) {
11129 // Maybe we should use a memcpy?
11130 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11131 T.isTriviallyCopyableType(S.Context))
11132 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11133
11134 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11135 CopyingBaseSubobject,
11136 Copying, 0));
11137
11138 // If we ended up picking a trivial assignment operator for an array of a
11139 // non-trivially-copyable class type, just emit a memcpy.
11140 if (!Result.isInvalid() && !Result.get())
11141 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11142
11143 return Result;
11144}
11145
Alexis Hunt119f3652011-05-14 05:23:20 +000011146CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11147 // Note: The following rules are largely analoguous to the copy
11148 // constructor rules. Note that virtual bases are not taken into account
11149 // for determining the argument type of the operator. Note also that
11150 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000011151 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000011152
Richard Smith8bf22e52012-11-29 01:34:07 +000011153 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11154 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011155 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011156
Alexis Hunt119f3652011-05-14 05:23:20 +000011157 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11158 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000011159 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11160 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000011161 ArgType = ArgType.withConst();
11162 ArgType = Context.getLValueReferenceType(ArgType);
11163
Richard Smith99005e62013-05-07 03:19:20 +000011164 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11165 CXXCopyAssignment,
11166 Const);
11167
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011168 // An implicitly-declared copy assignment operator is an inline public
11169 // member of its class.
11170 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000011171 SourceLocation ClassLoc = ClassDecl->getLocation();
11172 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011173 CXXMethodDecl *CopyAssignment =
11174 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011175 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11176 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011177 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000011178 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011179 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011180
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011181 if (getLangOpts().CUDA) {
11182 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11183 CopyAssignment,
11184 /* ConstRHS */ Const,
11185 /* Diagnose */ false);
11186 }
11187
Richard Smithd3b5c9082012-07-27 04:22:15 +000011188 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011189 FunctionProtoType::ExtProtoInfo EPI =
11190 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011191 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011192
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011193 // Add the parameter to the operator.
11194 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011195 ClassLoc, ClassLoc,
11196 /*Id=*/nullptr, ArgType,
11197 /*TInfo=*/nullptr, SC_None,
11198 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011199 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011200
Richard Smith6b02d462012-12-08 08:32:28 +000011201 CopyAssignment->setTrivial(
11202 ClassDecl->needsOverloadResolutionForCopyAssignment()
11203 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11204 : ClassDecl->hasTrivialCopyAssignment());
11205
Richard Smith6b02d462012-12-08 08:32:28 +000011206 // Note that we have added this copy-assignment operator.
11207 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11208
Richard Smith12e79312016-05-13 06:47:56 +000011209 Scope *S = getScopeForContext(ClassDecl);
11210 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11211
11212 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11213 SetDeclDeleted(CopyAssignment, ClassLoc);
11214
11215 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011216 PushOnScopeChains(CopyAssignment, S, false);
11217 ClassDecl->addDecl(CopyAssignment);
11218
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011219 return CopyAssignment;
11220}
11221
Richard Smithd577fbb2013-06-13 03:23:42 +000011222/// Diagnose an implicit copy operation for a class which is odr-used, but
11223/// which is deprecated because the class has a user-declared copy constructor,
11224/// copy assignment operator, or destructor.
11225static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11226 SourceLocation UseLoc) {
11227 assert(CopyOp->isImplicit());
11228
11229 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011230 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011231
11232 // In Microsoft mode, assignment operations don't affect constructors and
11233 // vice versa.
11234 if (RD->hasUserDeclaredDestructor()) {
11235 UserDeclaredOperation = RD->getDestructor();
11236 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11237 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011238 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011239 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011240 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011241 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011242 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011243 break;
11244 }
11245 }
11246 assert(UserDeclaredOperation);
11247 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11248 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011249 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011250 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011251 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011252 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011253 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011254 break;
11255 }
11256 }
11257 assert(UserDeclaredOperation);
11258 }
11259
11260 if (UserDeclaredOperation) {
11261 S.Diag(UserDeclaredOperation->getLocation(),
11262 diag::warn_deprecated_copy_operation)
11263 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11264 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11265 S.Diag(UseLoc, diag::note_member_synthesized_at)
11266 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11267 : Sema::CXXCopyAssignment)
11268 << RD;
11269 }
11270}
11271
Douglas Gregorb139cd52010-05-01 20:49:11 +000011272void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11273 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011274 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011275 CopyAssignOperator->isOverloadedOperator() &&
11276 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011277 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11278 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011279 "DefineImplicitCopyAssignment called for wrong function");
11280
11281 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11282
11283 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11284 CopyAssignOperator->setInvalidDecl();
11285 return;
11286 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011287
11288 // C++11 [class.copy]p18:
11289 // The [definition of an implicitly declared copy assignment operator] is
11290 // deprecated if the class has a user-declared copy constructor or a
11291 // user-declared destructor.
11292 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11293 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11294
Eli Friedman276dd182013-09-05 00:02:25 +000011295 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011296
Eli Friedmaneaf34142012-10-18 20:14:08 +000011297 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011298 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011299
11300 // C++0x [class.copy]p30:
11301 // The implicitly-defined or explicitly-defaulted copy assignment operator
11302 // for a non-union class X performs memberwise copy assignment of its
11303 // subobjects. The direct base classes of X are assigned first, in the
11304 // order of their declaration in the base-specifier-list, and then the
11305 // immediate non-static data members of X are assigned, in the order in
11306 // which they were declared in the class definition.
11307
11308 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011309 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011310
11311 // The parameter for the "other" object, which we are copying from.
11312 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11313 Qualifiers OtherQuals = Other->getType().getQualifiers();
11314 QualType OtherRefType = Other->getType();
11315 if (const LValueReferenceType *OtherRef
11316 = OtherRefType->getAs<LValueReferenceType>()) {
11317 OtherRefType = OtherRef->getPointeeType();
11318 OtherQuals = OtherRefType.getQualifiers();
11319 }
11320
11321 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011322 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11323 ? CopyAssignOperator->getLocEnd()
11324 : CopyAssignOperator->getLocation();
11325
Pavel Labath58934982013-08-30 08:52:28 +000011326 // Builds a DeclRefExpr for the "other" object.
11327 RefBuilder OtherRef(Other, OtherRefType);
11328
11329 // Builds the "this" pointer.
11330 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011331
11332 // Assign base classes.
11333 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011334 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011335 // Form the assignment:
11336 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011337 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011338 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011339 Invalid = true;
11340 continue;
11341 }
11342
John McCallcf142162010-08-07 06:22:56 +000011343 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011344 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011345
Douglas Gregorb139cd52010-05-01 20:49:11 +000011346 // Construct the "from" expression, which is an implicit cast to the
11347 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011348 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11349 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011350
11351 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011352 DerefBuilder DerefThis(This);
11353 CastBuilder To(DerefThis,
11354 Context.getCVRQualifiedType(
11355 BaseType, CopyAssignOperator->getTypeQualifiers()),
11356 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011357
11358 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011359 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011360 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011361 /*CopyingBaseSubobject=*/true,
11362 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011363 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011364 Diag(CurrentLocation, diag::note_member_synthesized_at)
11365 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11366 CopyAssignOperator->setInvalidDecl();
11367 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011368 }
11369
11370 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011371 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011372 }
11373
Douglas Gregorb139cd52010-05-01 20:49:11 +000011374 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011375 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011376 // FIXME: We should form some kind of AST representation for the implied
11377 // memcpy in a union copy operation.
11378 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011379 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011380
11381 if (Field->isInvalidDecl()) {
11382 Invalid = true;
11383 continue;
11384 }
11385
Douglas Gregorb139cd52010-05-01 20:49:11 +000011386 // Check for members of reference type; we can't copy those.
11387 if (Field->getType()->isReferenceType()) {
11388 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11389 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11390 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011391 Diag(CurrentLocation, diag::note_member_synthesized_at)
11392 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011393 Invalid = true;
11394 continue;
11395 }
11396
11397 // Check for members of const-qualified, non-class type.
11398 QualType BaseType = Context.getBaseElementType(Field->getType());
11399 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11400 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11401 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11402 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011403 Diag(CurrentLocation, diag::note_member_synthesized_at)
11404 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011405 Invalid = true;
11406 continue;
11407 }
John McCall1b1a1db2011-06-17 00:18:42 +000011408
11409 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011410 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11411 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011412
11413 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011414 if (FieldType->isIncompleteArrayType()) {
11415 assert(ClassDecl->hasFlexibleArrayMember() &&
11416 "Incomplete array type is not valid");
11417 continue;
11418 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011419
11420 // Build references to the field in the object we're copying from and to.
11421 CXXScopeSpec SS; // Intentionally empty
11422 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11423 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011424 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011425 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011426
11427 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11428
11429 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011430
Douglas Gregorb139cd52010-05-01 20:49:11 +000011431 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011432 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011433 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011434 /*CopyingBaseSubobject=*/false,
11435 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011436 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011437 Diag(CurrentLocation, diag::note_member_synthesized_at)
11438 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11439 CopyAssignOperator->setInvalidDecl();
11440 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011441 }
11442
11443 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011444 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011445 }
11446
11447 if (!Invalid) {
11448 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011449 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011450
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011451 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011452 if (Return.isInvalid())
11453 Invalid = true;
11454 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011455 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011456
11457 if (Trap.hasErrorOccurred()) {
11458 Diag(CurrentLocation, diag::note_member_synthesized_at)
11459 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11460 Invalid = true;
11461 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011462 }
11463 }
11464
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011465 // The exception specification is needed because we are defining the
11466 // function.
11467 ResolveExceptionSpec(CurrentLocation,
11468 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11469
Douglas Gregorb139cd52010-05-01 20:49:11 +000011470 if (Invalid) {
11471 CopyAssignOperator->setInvalidDecl();
11472 return;
11473 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011474
11475 StmtResult Body;
11476 {
11477 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011478 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011479 /*isStmtExpr=*/false);
11480 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11481 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011482 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011483
11484 if (ASTMutationListener *L = getASTMutationListener()) {
11485 L->CompletedImplicitDefinition(CopyAssignOperator);
11486 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011487}
11488
Sebastian Redl22653ba2011-08-30 19:58:05 +000011489CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011490 assert(ClassDecl->needsImplicitMoveAssignment());
11491
Richard Smith8bf22e52012-11-29 01:34:07 +000011492 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11493 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011494 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011495
Sebastian Redl22653ba2011-08-30 19:58:05 +000011496 // Note: The following rules are largely analoguous to the move
11497 // constructor rules.
11498
Sebastian Redl22653ba2011-08-30 19:58:05 +000011499 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11500 QualType RetType = Context.getLValueReferenceType(ArgType);
11501 ArgType = Context.getRValueReferenceType(ArgType);
11502
Richard Smith99005e62013-05-07 03:19:20 +000011503 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11504 CXXMoveAssignment,
11505 false);
11506
Sebastian Redl22653ba2011-08-30 19:58:05 +000011507 // An implicitly-declared move assignment operator is an inline public
11508 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011509 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11510 SourceLocation ClassLoc = ClassDecl->getLocation();
11511 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011512 CXXMethodDecl *MoveAssignment =
11513 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011514 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011515 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011516 MoveAssignment->setAccess(AS_public);
11517 MoveAssignment->setDefaulted();
11518 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011519
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011520 if (getLangOpts().CUDA) {
11521 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11522 MoveAssignment,
11523 /* ConstRHS */ false,
11524 /* Diagnose */ false);
11525 }
11526
Richard Smithd3b5c9082012-07-27 04:22:15 +000011527 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011528 FunctionProtoType::ExtProtoInfo EPI =
11529 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011530 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011531
Sebastian Redl22653ba2011-08-30 19:58:05 +000011532 // Add the parameter to the operator.
11533 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011534 ClassLoc, ClassLoc,
11535 /*Id=*/nullptr, ArgType,
11536 /*TInfo=*/nullptr, SC_None,
11537 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011538 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011539
Richard Smith6b02d462012-12-08 08:32:28 +000011540 MoveAssignment->setTrivial(
11541 ClassDecl->needsOverloadResolutionForMoveAssignment()
11542 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11543 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011544
Richard Smith12e79312016-05-13 06:47:56 +000011545 // Note that we have added this copy-assignment operator.
11546 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11547
11548 Scope *S = getScopeForContext(ClassDecl);
11549 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11550
Richard Smithd951a1d2012-02-18 02:02:13 +000011551 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011552 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11553 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011554 }
11555
Richard Smith12e79312016-05-13 06:47:56 +000011556 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011557 PushOnScopeChains(MoveAssignment, S, false);
11558 ClassDecl->addDecl(MoveAssignment);
11559
Sebastian Redl22653ba2011-08-30 19:58:05 +000011560 return MoveAssignment;
11561}
11562
Richard Smithb2504bd2013-11-04 04:26:14 +000011563/// Check if we're implicitly defining a move assignment operator for a class
11564/// with virtual bases. Such a move assignment might move-assign the virtual
11565/// base multiple times.
11566static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11567 SourceLocation CurrentLocation) {
11568 assert(!Class->isDependentContext() && "should not define dependent move");
11569
11570 // Only a virtual base could get implicitly move-assigned multiple times.
11571 // Only a non-trivial move assignment can observe this. We only want to
11572 // diagnose if we implicitly define an assignment operator that assigns
11573 // two base classes, both of which move-assign the same virtual base.
11574 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11575 Class->getNumBases() < 2)
11576 return;
11577
11578 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11579 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11580 VBaseMap VBases;
11581
Aaron Ballman574705e2014-03-13 15:41:46 +000011582 for (auto &BI : Class->bases()) {
11583 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011584 while (!Worklist.empty()) {
11585 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11586 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11587
11588 // If the base has no non-trivial move assignment operators,
11589 // we don't care about moves from it.
11590 if (!Base->hasNonTrivialMoveAssignment())
11591 continue;
11592
11593 // If there's nothing virtual here, skip it.
11594 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11595 continue;
11596
11597 // If we're not actually going to call a move assignment for this base,
11598 // or the selected move assignment is trivial, skip it.
Richard Smith8bae1be2017-02-24 02:07:20 +000011599 Sema::SpecialMemberOverloadResult SMOR =
Richard Smithb2504bd2013-11-04 04:26:14 +000011600 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11601 /*ConstArg*/false, /*VolatileArg*/false,
11602 /*RValueThis*/true, /*ConstThis*/false,
11603 /*VolatileThis*/false);
Richard Smith8bae1be2017-02-24 02:07:20 +000011604 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11605 !SMOR.getMethod()->isMoveAssignmentOperator())
Richard Smithb2504bd2013-11-04 04:26:14 +000011606 continue;
11607
11608 if (BaseSpec->isVirtual()) {
11609 // We're going to move-assign this virtual base, and its move
11610 // assignment operator is not trivial. If this can happen for
11611 // multiple distinct direct bases of Class, diagnose it. (If it
11612 // only happens in one base, we'll diagnose it when synthesizing
11613 // that base class's move assignment operator.)
11614 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011615 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011616 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011617 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011618 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11619 << Class << Base;
11620 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11621 << (Base->getCanonicalDecl() ==
11622 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11623 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011624 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011625 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011626 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11627 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011628
11629 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011630 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011631 }
11632 } else {
11633 // Only walk over bases that have defaulted move assignment operators.
11634 // We assume that any user-provided move assignment operator handles
11635 // the multiple-moves-of-vbase case itself somehow.
Richard Smith8bae1be2017-02-24 02:07:20 +000011636 if (!SMOR.getMethod()->isDefaulted())
Richard Smithb2504bd2013-11-04 04:26:14 +000011637 continue;
11638
11639 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011640 for (auto &BI : Base->bases())
11641 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011642 }
11643 }
11644 }
11645}
11646
Sebastian Redl22653ba2011-08-30 19:58:05 +000011647void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11648 CXXMethodDecl *MoveAssignOperator) {
11649 assert((MoveAssignOperator->isDefaulted() &&
11650 MoveAssignOperator->isOverloadedOperator() &&
11651 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011652 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11653 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011654 "DefineImplicitMoveAssignment called for wrong function");
11655
11656 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11657
11658 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11659 MoveAssignOperator->setInvalidDecl();
11660 return;
11661 }
11662
Eli Friedman276dd182013-09-05 00:02:25 +000011663 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011664
Eli Friedmaneaf34142012-10-18 20:14:08 +000011665 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011666 DiagnosticErrorTrap Trap(Diags);
11667
11668 // C++0x [class.copy]p28:
11669 // The implicitly-defined or move assignment operator for a non-union class
11670 // X performs memberwise move assignment of its subobjects. The direct base
11671 // classes of X are assigned first, in the order of their declaration in the
11672 // base-specifier-list, and then the immediate non-static data members of X
11673 // are assigned, in the order in which they were declared in the class
11674 // definition.
11675
Richard Smithb2504bd2013-11-04 04:26:14 +000011676 // Issue a warning if our implicit move assignment operator will move
11677 // from a virtual base more than once.
11678 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011679
Sebastian Redl22653ba2011-08-30 19:58:05 +000011680 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011681 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011682
11683 // The parameter for the "other" object, which we are move from.
11684 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11685 QualType OtherRefType = Other->getType()->
11686 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011687 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011688 "Bad argument type of defaulted move assignment");
11689
11690 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011691 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11692 ? MoveAssignOperator->getLocEnd()
11693 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011694
Pavel Labath58934982013-08-30 08:52:28 +000011695 // Builds a reference to the "other" object.
11696 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011697 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011698 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011699
Pavel Labath58934982013-08-30 08:52:28 +000011700 // Builds the "this" pointer.
11701 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011702
Sebastian Redl22653ba2011-08-30 19:58:05 +000011703 // Assign base classes.
11704 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011705 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011706 // C++11 [class.copy]p28:
11707 // It is unspecified whether subobjects representing virtual base classes
11708 // are assigned more than once by the implicitly-defined copy assignment
11709 // operator.
11710 // FIXME: Do not assign to a vbase that will be assigned by some other base
11711 // class. For a move-assignment, this can result in the vbase being moved
11712 // multiple times.
11713
Sebastian Redl22653ba2011-08-30 19:58:05 +000011714 // Form the assignment:
11715 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011716 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011717 if (!BaseType->isRecordType()) {
11718 Invalid = true;
11719 continue;
11720 }
11721
11722 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011723 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011724
11725 // Construct the "from" expression, which is an implicit cast to the
11726 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011727 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011728
11729 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011730 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011731
11732 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011733 CastBuilder To(DerefThis,
11734 Context.getCVRQualifiedType(
11735 BaseType, MoveAssignOperator->getTypeQualifiers()),
11736 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011737
11738 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011739 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011740 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011741 /*CopyingBaseSubobject=*/true,
11742 /*Copying=*/false);
11743 if (Move.isInvalid()) {
11744 Diag(CurrentLocation, diag::note_member_synthesized_at)
11745 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11746 MoveAssignOperator->setInvalidDecl();
11747 return;
11748 }
11749
11750 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011751 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011752 }
11753
Sebastian Redl22653ba2011-08-30 19:58:05 +000011754 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011755 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011756 // FIXME: We should form some kind of AST representation for the implied
11757 // memcpy in a union copy operation.
11758 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011759 continue;
11760
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011761 if (Field->isInvalidDecl()) {
11762 Invalid = true;
11763 continue;
11764 }
11765
Sebastian Redl22653ba2011-08-30 19:58:05 +000011766 // Check for members of reference type; we can't move those.
11767 if (Field->getType()->isReferenceType()) {
11768 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11769 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11770 Diag(Field->getLocation(), diag::note_declared_at);
11771 Diag(CurrentLocation, diag::note_member_synthesized_at)
11772 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11773 Invalid = true;
11774 continue;
11775 }
11776
11777 // Check for members of const-qualified, non-class type.
11778 QualType BaseType = Context.getBaseElementType(Field->getType());
11779 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11780 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11781 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11782 Diag(Field->getLocation(), diag::note_declared_at);
11783 Diag(CurrentLocation, diag::note_member_synthesized_at)
11784 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11785 Invalid = true;
11786 continue;
11787 }
11788
11789 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011790 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11791 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011792
11793 QualType FieldType = Field->getType().getNonReferenceType();
11794 if (FieldType->isIncompleteArrayType()) {
11795 assert(ClassDecl->hasFlexibleArrayMember() &&
11796 "Incomplete array type is not valid");
11797 continue;
11798 }
11799
11800 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011801 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11802 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011803 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011804 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011805 MemberBuilder From(MoveOther, OtherRefType,
11806 /*IsArrow=*/false, MemberLookup);
11807 MemberBuilder To(This, getCurrentThisType(),
11808 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011809
Pavel Labath58934982013-08-30 08:52:28 +000011810 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011811 "Member reference with rvalue base must be rvalue except for reference "
11812 "members, which aren't allowed for move assignment.");
11813
Sebastian Redl22653ba2011-08-30 19:58:05 +000011814 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011815 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011816 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011817 /*CopyingBaseSubobject=*/false,
11818 /*Copying=*/false);
11819 if (Move.isInvalid()) {
11820 Diag(CurrentLocation, diag::note_member_synthesized_at)
11821 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11822 MoveAssignOperator->setInvalidDecl();
11823 return;
11824 }
Richard Smith11d19592012-11-12 23:33:00 +000011825
Sebastian Redl22653ba2011-08-30 19:58:05 +000011826 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011827 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011828 }
11829
11830 if (!Invalid) {
11831 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011832 ExprResult ThisObj =
11833 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11834
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011835 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011836 if (Return.isInvalid())
11837 Invalid = true;
11838 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011839 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011840
11841 if (Trap.hasErrorOccurred()) {
11842 Diag(CurrentLocation, diag::note_member_synthesized_at)
11843 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11844 Invalid = true;
11845 }
11846 }
11847 }
11848
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011849 // The exception specification is needed because we are defining the
11850 // function.
11851 ResolveExceptionSpec(CurrentLocation,
11852 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11853
Sebastian Redl22653ba2011-08-30 19:58:05 +000011854 if (Invalid) {
11855 MoveAssignOperator->setInvalidDecl();
11856 return;
11857 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011858
11859 StmtResult Body;
11860 {
11861 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011862 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011863 /*isStmtExpr=*/false);
11864 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11865 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011866 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011867
11868 if (ASTMutationListener *L = getASTMutationListener()) {
11869 L->CompletedImplicitDefinition(MoveAssignOperator);
11870 }
11871}
11872
Alexis Hunt913820d2011-05-13 06:10:58 +000011873CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11874 CXXRecordDecl *ClassDecl) {
11875 // C++ [class.copy]p4:
11876 // If the class definition does not explicitly declare a copy
11877 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011878 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011879
Richard Smith8bf22e52012-11-29 01:34:07 +000011880 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11881 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011882 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011883
Alexis Hunt913820d2011-05-13 06:10:58 +000011884 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11885 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011886 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011887 if (Const)
11888 ArgType = ArgType.withConst();
11889 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011890
Richard Smithb5800092012-06-10 05:43:50 +000011891 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11892 CXXCopyConstructor,
11893 Const);
11894
Douglas Gregor54be3392010-07-01 17:57:27 +000011895 DeclarationName Name
11896 = Context.DeclarationNames.getCXXConstructorName(
11897 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011898 SourceLocation ClassLoc = ClassDecl->getLocation();
11899 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011900
11901 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011902 // member of its class.
11903 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011904 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011905 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011906 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011907 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011908 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011909
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011910 if (getLangOpts().CUDA) {
11911 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11912 CopyConstructor,
11913 /* ConstRHS */ Const,
11914 /* Diagnose */ false);
11915 }
11916
Richard Smithd3b5c9082012-07-27 04:22:15 +000011917 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011918 FunctionProtoType::ExtProtoInfo EPI =
11919 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011920 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011921 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011922
Douglas Gregor54be3392010-07-01 17:57:27 +000011923 // Add the parameter to the constructor.
11924 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011925 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011926 /*IdentifierInfo=*/nullptr,
11927 ArgType, /*TInfo=*/nullptr,
11928 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011929 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011930
Richard Smith6b02d462012-12-08 08:32:28 +000011931 CopyConstructor->setTrivial(
11932 ClassDecl->needsOverloadResolutionForCopyConstructor()
11933 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11934 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011935
Richard Smith6b02d462012-12-08 08:32:28 +000011936 // Note that we have declared this constructor.
11937 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11938
Richard Smith12e79312016-05-13 06:47:56 +000011939 Scope *S = getScopeForContext(ClassDecl);
11940 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11941
11942 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11943 SetDeclDeleted(CopyConstructor, ClassLoc);
11944
11945 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011946 PushOnScopeChains(CopyConstructor, S, false);
11947 ClassDecl->addDecl(CopyConstructor);
11948
Douglas Gregor54be3392010-07-01 17:57:27 +000011949 return CopyConstructor;
11950}
11951
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011952void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011953 CXXConstructorDecl *CopyConstructor) {
11954 assert((CopyConstructor->isDefaulted() &&
11955 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011956 !CopyConstructor->doesThisDeclarationHaveABody() &&
11957 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011958 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011959
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011960 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011961 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011962
Richard Smithd577fbb2013-06-13 03:23:42 +000011963 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011964 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011965 // deprecated if the class has a user-declared copy assignment operator
11966 // or a user-declared destructor.
11967 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11968 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11969
Eli Friedmaneaf34142012-10-18 20:14:08 +000011970 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011971 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011972
David Blaikie3fc2f912013-01-17 05:26:25 +000011973 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011974 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011975 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011976 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011977 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011978 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011979 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11980 ? CopyConstructor->getLocEnd()
11981 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011982 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011983 CopyConstructor->setBody(
11984 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011985 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011986
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011987 // The exception specification is needed because we are defining the
11988 // function.
11989 ResolveExceptionSpec(CurrentLocation,
11990 CopyConstructor->getType()->castAs<FunctionProtoType>());
11991
Eli Friedman276dd182013-09-05 00:02:25 +000011992 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011993 MarkVTableUsed(CurrentLocation, ClassDecl);
11994
Sebastian Redlab238a72011-04-24 16:28:06 +000011995 if (ASTMutationListener *L = getASTMutationListener()) {
11996 L->CompletedImplicitDefinition(CopyConstructor);
11997 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011998}
11999
Sebastian Redl22653ba2011-08-30 19:58:05 +000012000CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12001 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000012002 assert(ClassDecl->needsImplicitMoveConstructor());
12003
Richard Smith8bf22e52012-11-29 01:34:07 +000012004 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12005 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000012006 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000012007
Sebastian Redl22653ba2011-08-30 19:58:05 +000012008 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12009 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012010
Richard Smithb5800092012-06-10 05:43:50 +000012011 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12012 CXXMoveConstructor,
12013 false);
12014
Sebastian Redl22653ba2011-08-30 19:58:05 +000012015 DeclarationName Name
12016 = Context.DeclarationNames.getCXXConstructorName(
12017 Context.getCanonicalType(ClassType));
12018 SourceLocation ClassLoc = ClassDecl->getLocation();
12019 DeclarationNameInfo NameInfo(Name, ClassLoc);
12020
Richard Smith99005e62013-05-07 03:19:20 +000012021 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000012022 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000012023 // member of its class.
12024 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000012025 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000012026 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000012027 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012028 MoveConstructor->setAccess(AS_public);
12029 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000012030
Eli Bendersky9a220fc2014-09-29 20:38:29 +000012031 if (getLangOpts().CUDA) {
12032 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12033 MoveConstructor,
12034 /* ConstRHS */ false,
12035 /* Diagnose */ false);
12036 }
12037
Richard Smithd3b5c9082012-07-27 04:22:15 +000012038 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000012039 FunctionProtoType::ExtProtoInfo EPI =
12040 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012041 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012042 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012043
Sebastian Redl22653ba2011-08-30 19:58:05 +000012044 // Add the parameter to the constructor.
12045 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12046 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012047 /*IdentifierInfo=*/nullptr,
12048 ArgType, /*TInfo=*/nullptr,
12049 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012050 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012051
Richard Smith6b02d462012-12-08 08:32:28 +000012052 MoveConstructor->setTrivial(
12053 ClassDecl->needsOverloadResolutionForMoveConstructor()
12054 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12055 : ClassDecl->hasTrivialMoveConstructor());
12056
Richard Smith12e79312016-05-13 06:47:56 +000012057 // Note that we have declared this constructor.
12058 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12059
12060 Scope *S = getScopeForContext(ClassDecl);
12061 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12062
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012063 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012064 ClassDecl->setImplicitMoveConstructorIsDeleted();
12065 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012066 }
12067
Richard Smith12e79312016-05-13 06:47:56 +000012068 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012069 PushOnScopeChains(MoveConstructor, S, false);
12070 ClassDecl->addDecl(MoveConstructor);
12071
12072 return MoveConstructor;
12073}
12074
12075void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12076 CXXConstructorDecl *MoveConstructor) {
12077 assert((MoveConstructor->isDefaulted() &&
12078 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012079 !MoveConstructor->doesThisDeclarationHaveABody() &&
12080 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012081 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12082
12083 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12084 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12085
Eli Friedmaneaf34142012-10-18 20:14:08 +000012086 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012087 DiagnosticErrorTrap Trap(Diags);
12088
David Blaikie3fc2f912013-01-17 05:26:25 +000012089 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012090 Trap.hasErrorOccurred()) {
12091 Diag(CurrentLocation, diag::note_member_synthesized_at)
12092 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12093 MoveConstructor->setInvalidDecl();
12094 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012095 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12096 ? MoveConstructor->getLocEnd()
12097 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012098 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012099 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012100 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012101 }
12102
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012103 // The exception specification is needed because we are defining the
12104 // function.
12105 ResolveExceptionSpec(CurrentLocation,
12106 MoveConstructor->getType()->castAs<FunctionProtoType>());
12107
Eli Friedman276dd182013-09-05 00:02:25 +000012108 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012109 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012110
12111 if (ASTMutationListener *L = getASTMutationListener()) {
12112 L->CompletedImplicitDefinition(MoveConstructor);
12113 }
12114}
12115
Douglas Gregor74f7d502012-02-15 19:33:52 +000012116bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012117 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012118}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012119
12120void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012121 SourceLocation CurrentLocation,
12122 CXXConversionDecl *Conv) {
12123 CXXRecordDecl *Lambda = Conv->getParent();
12124 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12125 // If we are defining a specialization of a conversion to function-ptr
12126 // cache the deduced template arguments for this specialization
12127 // so that we can use them to retrieve the corresponding call-operator
12128 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012129 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12130
Faisal Vali571df122013-09-29 08:45:24 +000012131 // Retrieve the corresponding call-operator specialization.
12132 if (Lambda->isGenericLambda()) {
12133 assert(Conv->isFunctionTemplateSpecialization());
12134 FunctionTemplateDecl *CallOpTemplate =
12135 CallOp->getDescribedFunctionTemplate();
12136 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012137 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012138 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012139 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012140 InsertPos);
12141 assert(CallOpSpec &&
12142 "Conversion operator must have a corresponding call operator");
12143 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12144 }
12145 // Mark the call operator referenced (and add to pending instantiations
12146 // if necessary).
12147 // For both the conversion and static-invoker template specializations
12148 // we construct their body's in this function, so no need to add them
12149 // to the PendingInstantiations.
12150 MarkFunctionReferenced(CurrentLocation, CallOp);
12151
Eli Friedmaneaf34142012-10-18 20:14:08 +000012152 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012153 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012154
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012155 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012156 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12157 // ... and get the corresponding specialization for a generic lambda.
12158 if (Lambda->isGenericLambda()) {
12159 assert(DeducedTemplateArgs &&
12160 "Must have deduced template arguments from Conversion Operator");
12161 FunctionTemplateDecl *InvokeTemplate =
12162 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012163 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012164 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012165 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012166 InsertPos);
12167 assert(InvokeSpec &&
12168 "Must have a corresponding static invoker specialization");
12169 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12170 }
12171 // Construct the body of the conversion function { return __invoke; }.
12172 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012173 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012174 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012175 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012176 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12177 Conv->getLocation(),
12178 Conv->getLocation()));
12179
12180 Conv->markUsed(Context);
12181 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012182
Faisal Vali571df122013-09-29 08:45:24 +000012183 // Fill in the __invoke function with a dummy implementation. IR generation
12184 // will fill in the actual details.
12185 Invoker->markUsed(Context);
12186 Invoker->setReferenced();
12187 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12188
Douglas Gregord3b672c2012-02-16 01:06:16 +000012189 if (ASTMutationListener *L = getASTMutationListener()) {
12190 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012191 L->CompletedImplicitDefinition(Invoker);
12192 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012193}
12194
Faisal Vali571df122013-09-29 08:45:24 +000012195
12196
Douglas Gregord3b672c2012-02-16 01:06:16 +000012197void Sema::DefineImplicitLambdaToBlockPointerConversion(
12198 SourceLocation CurrentLocation,
12199 CXXConversionDecl *Conv)
12200{
Faisal Vali850da1a2013-09-29 17:08:32 +000012201 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012202
Eli Friedman276dd182013-09-05 00:02:25 +000012203 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012204
Eli Friedmaneaf34142012-10-18 20:14:08 +000012205 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012206 DiagnosticErrorTrap Trap(Diags);
12207
Douglas Gregored90df32012-02-22 05:02:47 +000012208 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012209 Expr *This = ActOnCXXThis(CurrentLocation).get();
12210 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012211
Eli Friedman98b01ed2012-03-01 04:01:32 +000012212 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12213 Conv->getLocation(),
12214 Conv, DerefThis);
12215
12216 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12217 // behavior. Note that only the general conversion function does this
12218 // (since it's unusable otherwise); in the case where we inline the
12219 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012220 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012221 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12222 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012223 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012224
12225 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012226 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012227 Conv->setInvalidDecl();
12228 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012229 }
Douglas Gregored90df32012-02-22 05:02:47 +000012230
Douglas Gregored90df32012-02-22 05:02:47 +000012231 // Create the return statement that returns the block from the conversion
12232 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012233 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012234 if (Return.isInvalid()) {
12235 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12236 Conv->setInvalidDecl();
12237 return;
12238 }
12239
12240 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012241 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012242 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Brian Kelley4afdfe82017-03-29 17:18:05 +000012243 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012244 Conv->getLocation()));
12245
Douglas Gregored90df32012-02-22 05:02:47 +000012246 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012247 if (ASTMutationListener *L = getASTMutationListener()) {
12248 L->CompletedImplicitDefinition(Conv);
12249 }
12250}
12251
Douglas Gregord2f70072012-03-10 06:53:13 +000012252/// \brief Determine whether the given list arguments contains exactly one
12253/// "real" (non-default) argument.
12254static bool hasOneRealArgument(MultiExprArg Args) {
12255 switch (Args.size()) {
12256 case 0:
12257 return false;
12258
12259 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012260 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012261 return false;
12262
12263 // fall through
12264 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012265 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012266 }
12267
12268 return false;
12269}
12270
John McCalldadc5752010-08-24 06:29:42 +000012271ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012272Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012273 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012274 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012275 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012276 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012277 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012278 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012279 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012280 unsigned ConstructKind,
12281 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012282 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012283
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012284 // C++0x [class.copy]p34:
12285 // When certain criteria are met, an implementation is allowed to
12286 // omit the copy/move construction of a class object, even if the
12287 // copy/move constructor and/or destructor for the object have
12288 // side effects. [...]
12289 // - when a temporary class object that has not been bound to a
12290 // reference (12.2) would be copied/moved to a class object
12291 // with the same cv-unqualified type, the copy/move operation
12292 // can be omitted by constructing the temporary object
12293 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012294 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012295 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012296 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012297 Elidable = SubExpr->isTemporaryObject(
12298 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012299 }
Mike Stump11289f42009-09-09 15:08:12 +000012300
Richard Smithc2bebe92016-05-11 20:37:46 +000012301 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12302 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012303 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012304 IsListInitialization,
12305 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012306 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012307}
12308
John McCalldadc5752010-08-24 06:29:42 +000012309ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012310Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012311 NamedDecl *FoundDecl,
12312 CXXConstructorDecl *Constructor,
12313 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012314 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012315 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012316 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012317 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012318 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012319 unsigned ConstructKind,
12320 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012321 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012322 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012323 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12324 return ExprError();
12325 }
Richard Smith5179eb72016-06-28 19:03:57 +000012326
Richard Smithc83bf822016-06-10 00:58:19 +000012327 return BuildCXXConstructExpr(
12328 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12329 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12330 RequiresZeroInit, ConstructKind, ParenRange);
12331}
12332
12333/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12334/// including handling of its default argument expressions.
12335ExprResult
12336Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12337 CXXConstructorDecl *Constructor,
12338 bool Elidable,
12339 MultiExprArg ExprArgs,
12340 bool HadMultipleCandidates,
12341 bool IsListInitialization,
12342 bool IsStdInitListInitialization,
12343 bool RequiresZeroInit,
12344 unsigned ConstructKind,
12345 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012346 assert(declaresSameEntity(
12347 Constructor->getParent(),
12348 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12349 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012350 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012351 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12352 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012354 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012355 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012356 ExprArgs, HadMultipleCandidates, IsListInitialization,
12357 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012358 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12359 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012360}
12361
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012362ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12363 assert(Field->hasInClassInitializer());
12364
12365 // If we already have the in-class initializer nothing needs to be done.
12366 if (Field->getInClassInitializer())
12367 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12368
Richard Smithd6a15082017-01-07 00:48:55 +000012369 // If we might have already tried and failed to instantiate, don't try again.
12370 if (Field->isInvalidDecl())
12371 return ExprError();
12372
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012373 // Maybe we haven't instantiated the in-class initializer. Go check the
12374 // pattern FieldDecl to see if it has one.
12375 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12376
12377 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12378 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12379 DeclContext::lookup_result Lookup =
12380 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012381
12382 // Lookup can return at most two results: the pattern for the field, or the
12383 // injected class name of the parent record. No other member can have the
12384 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012385 // In modules mode, lookup can return multiple results (coming from
12386 // different modules).
12387 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012388 "more than two lookup results for field name");
12389 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12390 if (!Pattern) {
12391 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12392 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012393 for (auto L : Lookup)
12394 if (isa<FieldDecl>(L)) {
12395 Pattern = cast<FieldDecl>(L);
12396 break;
12397 }
12398 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012399 }
12400
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012401 if (InstantiateInClassInitializer(Loc, Field, Pattern,
Richard Smithd6a15082017-01-07 00:48:55 +000012402 getTemplateInstantiationArgs(Field))) {
12403 // Don't diagnose this again.
12404 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012405 return ExprError();
Richard Smithd6a15082017-01-07 00:48:55 +000012406 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012407 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12408 }
12409
12410 // DR1351:
12411 // If the brace-or-equal-initializer of a non-static data member
12412 // invokes a defaulted default constructor of its class or of an
12413 // enclosing class in a potentially evaluated subexpression, the
12414 // program is ill-formed.
12415 //
12416 // This resolution is unworkable: the exception specification of the
12417 // default constructor can be needed in an unevaluated context, in
12418 // particular, in the operand of a noexcept-expression, and we can be
12419 // unable to compute an exception specification for an enclosed class.
12420 //
12421 // Any attempt to resolve the exception specification of a defaulted default
12422 // constructor before the initializer is lexically complete will ultimately
12423 // come here at which point we can diagnose it.
12424 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012425 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12426 << OutermostClass << Field;
12427 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Richard Smith8d148352017-01-23 23:14:23 +000012428 // Recover by marking the field invalid, unless we're in a SFINAE context.
12429 if (!isSFINAEContext())
12430 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012431 return ExprError();
12432}
12433
John McCall03c48482010-02-02 09:10:11 +000012434void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012435 if (VD->isInvalidDecl()) return;
12436
John McCall03c48482010-02-02 09:10:11 +000012437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012438 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012439 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012440 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012441
Chandler Carruth86d17d32011-03-27 21:26:48 +000012442 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012443 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012444 CheckDestructorAccess(VD->getLocation(), Destructor,
12445 PDiag(diag::err_access_dtor_var)
12446 << VD->getDeclName()
12447 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012448 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012449
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012450 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012451 if (!VD->hasGlobalStorage()) return;
12452
12453 // Emit warning for non-trivial dtor in global scope (a real global,
12454 // class-static, function-static).
12455 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12456
12457 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012458 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012459 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012460}
12461
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012462/// \brief Given a constructor and the set of arguments provided for the
12463/// constructor, convert the arguments and add any required default arguments
12464/// to form a proper call to this constructor.
12465///
12466/// \returns true if an error occurred, false otherwise.
12467bool
12468Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12469 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012470 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012471 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012472 bool AllowExplicit,
12473 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012474 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12475 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012476 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012477
12478 const FunctionProtoType *Proto
12479 = Constructor->getType()->getAs<FunctionProtoType>();
12480 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012481 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012482
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012483 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012484 if (NumArgs < NumParams)
12485 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012486 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012487 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012488
12489 VariadicCallType CallType =
12490 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012491 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012492 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012493 Proto, 0,
12494 llvm::makeArrayRef(Args, NumArgs),
12495 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012496 CallType, AllowExplicit,
12497 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012498 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012499
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012500 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012501
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012502 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012503 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012504 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012505
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012506 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012507}
12508
Anders Carlssone363c8e2009-12-12 00:32:00 +000012509static inline bool
12510CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12511 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012512 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012513 if (isa<NamespaceDecl>(DC)) {
12514 return SemaRef.Diag(FnDecl->getLocation(),
12515 diag::err_operator_new_delete_declared_in_namespace)
12516 << FnDecl->getDeclName();
12517 }
12518
12519 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012520 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012521 return SemaRef.Diag(FnDecl->getLocation(),
12522 diag::err_operator_new_delete_declared_static)
12523 << FnDecl->getDeclName();
12524 }
12525
Anders Carlsson60659a82009-12-12 02:43:16 +000012526 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012527}
12528
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012529static inline bool
12530CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12531 CanQualType ExpectedResultType,
12532 CanQualType ExpectedFirstParamType,
12533 unsigned DependentParamTypeDiag,
12534 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012535 QualType ResultType =
12536 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012537
12538 // Check that the result type is not dependent.
12539 if (ResultType->isDependentType())
12540 return SemaRef.Diag(FnDecl->getLocation(),
12541 diag::err_operator_new_delete_dependent_result_type)
12542 << FnDecl->getDeclName() << ExpectedResultType;
12543
12544 // Check that the result type is what we expect.
12545 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12546 return SemaRef.Diag(FnDecl->getLocation(),
12547 diag::err_operator_new_delete_invalid_result_type)
12548 << FnDecl->getDeclName() << ExpectedResultType;
12549
12550 // A function template must have at least 2 parameters.
12551 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12552 return SemaRef.Diag(FnDecl->getLocation(),
12553 diag::err_operator_new_delete_template_too_few_parameters)
12554 << FnDecl->getDeclName();
12555
12556 // The function decl must have at least 1 parameter.
12557 if (FnDecl->getNumParams() == 0)
12558 return SemaRef.Diag(FnDecl->getLocation(),
12559 diag::err_operator_new_delete_too_few_parameters)
12560 << FnDecl->getDeclName();
12561
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012562 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012563 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12564 if (FirstParamType->isDependentType())
12565 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12566 << FnDecl->getDeclName() << ExpectedFirstParamType;
12567
12568 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012569 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012570 ExpectedFirstParamType)
12571 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12572 << FnDecl->getDeclName() << ExpectedFirstParamType;
12573
12574 return false;
12575}
12576
Anders Carlsson12308f42009-12-11 23:23:22 +000012577static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012578CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012579 // C++ [basic.stc.dynamic.allocation]p1:
12580 // A program is ill-formed if an allocation function is declared in a
12581 // namespace scope other than global scope or declared static in global
12582 // scope.
12583 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12584 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012585
12586 CanQualType SizeTy =
12587 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12588
12589 // C++ [basic.stc.dynamic.allocation]p1:
12590 // The return type shall be void*. The first parameter shall have type
12591 // std::size_t.
12592 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12593 SizeTy,
12594 diag::err_operator_new_dependent_param_type,
12595 diag::err_operator_new_param_type))
12596 return true;
12597
12598 // C++ [basic.stc.dynamic.allocation]p1:
12599 // The first parameter shall not have an associated default argument.
12600 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012601 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012602 diag::err_operator_new_default_arg)
12603 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12604
12605 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012606}
12607
12608static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012609CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012610 // C++ [basic.stc.dynamic.deallocation]p1:
12611 // A program is ill-formed if deallocation functions are declared in a
12612 // namespace scope other than global scope or declared static in global
12613 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012614 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12615 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012616
12617 // C++ [basic.stc.dynamic.deallocation]p2:
12618 // Each deallocation function shall return void and its first parameter
12619 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012620 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12621 SemaRef.Context.VoidPtrTy,
12622 diag::err_operator_delete_dependent_param_type,
12623 diag::err_operator_delete_param_type))
12624 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012625
Anders Carlsson12308f42009-12-11 23:23:22 +000012626 return false;
12627}
12628
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012629/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12630/// of this overloaded operator is well-formed. If so, returns false;
12631/// otherwise, emits appropriate diagnostics and returns true.
12632bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012633 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012634 "Expected an overloaded operator declaration");
12635
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012636 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12637
Mike Stump11289f42009-09-09 15:08:12 +000012638 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012639 // The allocation and deallocation functions, operator new,
12640 // operator new[], operator delete and operator delete[], are
12641 // described completely in 3.7.3. The attributes and restrictions
12642 // found in the rest of this subclause do not apply to them unless
12643 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012644 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012645 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012646
Anders Carlsson22f443f2009-12-12 00:26:23 +000012647 if (Op == OO_New || Op == OO_Array_New)
12648 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012649
12650 // C++ [over.oper]p6:
12651 // An operator function shall either be a non-static member
12652 // function or be a non-member function and have at least one
12653 // parameter whose type is a class, a reference to a class, an
12654 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012655 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12656 if (MethodDecl->isStatic())
12657 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012658 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012659 } else {
12660 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012661 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012662 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012663 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12664 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012665 ClassOrEnumParam = true;
12666 break;
12667 }
12668 }
12669
Douglas Gregord69246b2008-11-17 16:14:12 +000012670 if (!ClassOrEnumParam)
12671 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012672 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012673 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012674 }
12675
12676 // C++ [over.oper]p8:
12677 // An operator function cannot have default arguments (8.3.6),
12678 // except where explicitly stated below.
12679 //
Mike Stump11289f42009-09-09 15:08:12 +000012680 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012681 // (C++ [over.call]p1).
12682 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012683 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012684 if (Param->hasDefaultArg())
12685 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012686 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012687 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012688 }
12689 }
12690
Douglas Gregor6cf08062008-11-10 13:38:07 +000012691 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12692 { false, false, false }
12693#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12694 , { Unary, Binary, MemberOnly }
12695#include "clang/Basic/OperatorKinds.def"
12696 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012697
Douglas Gregor6cf08062008-11-10 13:38:07 +000012698 bool CanBeUnaryOperator = OperatorUses[Op][0];
12699 bool CanBeBinaryOperator = OperatorUses[Op][1];
12700 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012701
12702 // C++ [over.oper]p8:
12703 // [...] Operator functions cannot have more or fewer parameters
12704 // than the number required for the corresponding operator, as
12705 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012706 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012707 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012708 if (Op != OO_Call &&
12709 ((NumParams == 1 && !CanBeUnaryOperator) ||
12710 (NumParams == 2 && !CanBeBinaryOperator) ||
12711 (NumParams < 1) || (NumParams > 2))) {
12712 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012713 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012714 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012715 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012716 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012717 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012718 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012719 assert(CanBeBinaryOperator &&
12720 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012721 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012722 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012723
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012724 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012725 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012726 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012727
Douglas Gregord69246b2008-11-17 16:14:12 +000012728 // Overloaded operators other than operator() cannot be variadic.
12729 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012730 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012731 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012732 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012733 }
12734
12735 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012736 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12737 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012738 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012739 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012740 }
12741
12742 // C++ [over.inc]p1:
12743 // The user-defined function called operator++ implements the
12744 // prefix and postfix ++ operator. If this function is a member
12745 // function with no parameters, or a non-member function with one
12746 // parameter of class or enumeration type, it defines the prefix
12747 // increment operator ++ for objects of that type. If the function
12748 // is a member function with one parameter (which shall be of type
12749 // int) or a non-member function with two parameters (the second
12750 // of which shall be of type int), it defines the postfix
12751 // increment operator ++ for objects of that type.
12752 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12753 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012754 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012755
Richard Smith538b52a2014-01-30 22:24:05 +000012756 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12757 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012758 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012759 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012760 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012761 }
12762
Douglas Gregord69246b2008-11-17 16:14:12 +000012763 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012764}
Chris Lattner3b024a32008-12-17 07:09:26 +000012765
Richard Smithc28aee62016-02-17 00:04:04 +000012766static bool
12767checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12768 FunctionTemplateDecl *TpDecl) {
12769 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12770
12771 // Must have one or two template parameters.
12772 if (TemplateParams->size() == 1) {
12773 NonTypeTemplateParmDecl *PmDecl =
12774 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12775
12776 // The template parameter must be a char parameter pack.
12777 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12778 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12779 return false;
12780
12781 } else if (TemplateParams->size() == 2) {
12782 TemplateTypeParmDecl *PmType =
12783 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12784 NonTypeTemplateParmDecl *PmArgs =
12785 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12786
12787 // The second template parameter must be a parameter pack with the
12788 // first template parameter as its type.
12789 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12790 PmArgs->isTemplateParameterPack()) {
12791 const TemplateTypeParmType *TArgs =
12792 PmArgs->getType()->getAs<TemplateTypeParmType>();
12793 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12794 TArgs->getIndex() == PmType->getIndex()) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000012795 if (!SemaRef.inTemplateInstantiation())
Richard Smithc28aee62016-02-17 00:04:04 +000012796 SemaRef.Diag(TpDecl->getLocation(),
12797 diag::ext_string_literal_operator_template);
12798 return false;
12799 }
12800 }
12801 }
12802
12803 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12804 diag::err_literal_operator_template)
12805 << TpDecl->getTemplateParameters()->getSourceRange();
12806 return true;
12807}
12808
Alexis Huntc88db062010-01-13 09:01:02 +000012809/// CheckLiteralOperatorDeclaration - Check whether the declaration
12810/// of this literal operator function is well-formed. If so, returns
12811/// false; otherwise, emits appropriate diagnostics and returns true.
12812bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012813 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012814 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12815 << FnDecl->getDeclName();
12816 return true;
12817 }
12818
Richard Smith72eebee2012-03-04 09:41:16 +000012819 if (FnDecl->isExternC()) {
12820 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012821 if (const LinkageSpecDecl *LSD =
12822 FnDecl->getDeclContext()->getExternCContext())
12823 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012824 return true;
12825 }
12826
Richard Smithbcc22fc2012-03-09 08:00:36 +000012827 // This might be the definition of a literal operator template.
12828 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012829
Richard Smithbcc22fc2012-03-09 08:00:36 +000012830 // This might be a specialization of a literal operator template.
12831 if (!TpDecl)
12832 TpDecl = FnDecl->getPrimaryTemplate();
12833
Richard Smithb8b41d32013-10-07 19:57:58 +000012834 // template <char...> type operator "" name() and
12835 // template <class T, T...> type operator "" name() are the only valid
12836 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012837 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012838 if (FnDecl->param_size() != 0) {
12839 Diag(FnDecl->getLocation(),
12840 diag::err_literal_operator_template_with_params);
12841 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012842 }
Richard Smithc28aee62016-02-17 00:04:04 +000012843
12844 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12845 return true;
12846
12847 } else if (FnDecl->param_size() == 1) {
12848 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12849
12850 QualType ParamType = Param->getType().getUnqualifiedType();
12851
12852 // Only unsigned long long int, long double, any character type, and const
12853 // char * are allowed as the only parameters.
12854 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12855 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12856 Context.hasSameType(ParamType, Context.CharTy) ||
12857 Context.hasSameType(ParamType, Context.WideCharTy) ||
12858 Context.hasSameType(ParamType, Context.Char16Ty) ||
12859 Context.hasSameType(ParamType, Context.Char32Ty)) {
12860 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12861 QualType InnerType = Ptr->getPointeeType();
12862
12863 // Pointer parameter must be a const char *.
12864 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12865 Context.CharTy) &&
12866 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12867 Diag(Param->getSourceRange().getBegin(),
12868 diag::err_literal_operator_param)
12869 << ParamType << "'const char *'" << Param->getSourceRange();
12870 return true;
12871 }
12872
12873 } else if (ParamType->isRealFloatingType()) {
12874 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12875 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12876 return true;
12877
12878 } else if (ParamType->isIntegerType()) {
12879 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12880 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12881 return true;
12882
12883 } else {
12884 Diag(Param->getSourceRange().getBegin(),
12885 diag::err_literal_operator_invalid_param)
12886 << ParamType << Param->getSourceRange();
12887 return true;
12888 }
12889
12890 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012891 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12892
Richard Smithc28aee62016-02-17 00:04:04 +000012893 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012894
Richard Smithc28aee62016-02-17 00:04:04 +000012895 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12896
12897 // Two parameter function must have a pointer to const as a
12898 // first parameter; let's strip those qualifiers.
12899 const PointerType *PT = FirstParamType->getAs<PointerType>();
12900
12901 if (!PT) {
12902 Diag((*Param)->getSourceRange().getBegin(),
12903 diag::err_literal_operator_param)
12904 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12905 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012906 }
12907
Richard Smithc28aee62016-02-17 00:04:04 +000012908 QualType PointeeType = PT->getPointeeType();
12909 // First parameter must be const
12910 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12911 Diag((*Param)->getSourceRange().getBegin(),
12912 diag::err_literal_operator_param)
12913 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12914 return true;
12915 }
Alexis Huntc88db062010-01-13 09:01:02 +000012916
Richard Smithc28aee62016-02-17 00:04:04 +000012917 QualType InnerType = PointeeType.getUnqualifiedType();
12918 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12919 // are allowed as the first parameter to a two-parameter function
12920 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12921 Context.hasSameType(InnerType, Context.WideCharTy) ||
12922 Context.hasSameType(InnerType, Context.Char16Ty) ||
12923 Context.hasSameType(InnerType, Context.Char32Ty))) {
12924 Diag((*Param)->getSourceRange().getBegin(),
12925 diag::err_literal_operator_param)
12926 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12927 return true;
12928 }
12929
12930 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012931 ++Param;
12932
Richard Smithc28aee62016-02-17 00:04:04 +000012933 // The second parameter must be a std::size_t.
12934 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12935 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12936 Diag((*Param)->getSourceRange().getBegin(),
12937 diag::err_literal_operator_param)
12938 << SecondParamType << Context.getSizeType()
12939 << (*Param)->getSourceRange();
12940 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012941 }
Richard Smithc28aee62016-02-17 00:04:04 +000012942 } else {
12943 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012944 return true;
12945 }
12946
Richard Smithc28aee62016-02-17 00:04:04 +000012947 // Parameters are good.
12948
Richard Smith768cecc2012-03-09 08:16:22 +000012949 // A parameter-declaration-clause containing a default argument is not
12950 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012951 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012952 if (Param->hasDefaultArg()) {
12953 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012954 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012955 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012956 break;
12957 }
12958 }
12959
Richard Smith0df56f42012-03-08 02:39:21 +000012960 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012961 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12962 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012963 // C++11 [usrlit.suffix]p1:
12964 // Literal suffix identifiers that do not start with an underscore
12965 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012966 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
Eric Fiseliercb2f3262016-12-30 04:51:10 +000012967 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012968 }
Richard Smith0df56f42012-03-08 02:39:21 +000012969
Alexis Huntc88db062010-01-13 09:01:02 +000012970 return false;
12971}
12972
Douglas Gregor07665a62009-01-05 19:45:36 +000012973/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12974/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012975/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12976/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012977/// the '{' brace. Otherwise, this linkage specification does not
12978/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012979Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012980 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012981 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012982 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12983 if (!Lit->isAscii()) {
12984 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12985 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012986 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012987 }
12988
12989 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012990 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012991 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012992 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012993 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012994 Language = LinkageSpecDecl::lang_cxx;
12995 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012996 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12997 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012998 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012999 }
Mike Stump11289f42009-09-09 15:08:12 +000013000
Chris Lattner438e5012008-12-17 07:13:27 +000013001 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000013002
Richard Smith4ee696d2014-02-17 23:25:27 +000013003 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13004 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000013005 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013006 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000013007 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000013008 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000013009}
13010
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000013011/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000013012/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13013/// valid, it's the position of the closing '}' brace in a linkage
13014/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000013015Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013016 Decl *LinkageSpec,
13017 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013018 if (RBraceLoc.isValid()) {
13019 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13020 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013021 }
Richard Smith4ee696d2014-02-17 23:25:27 +000013022 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000013023 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000013024}
13025
Michael Han84324352013-02-22 17:15:32 +000013026Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13027 AttributeList *AttrList,
13028 SourceLocation SemiLoc) {
13029 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13030 // Attribute declarations appertain to empty declaration so we handle
13031 // them here.
13032 if (AttrList)
13033 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000013034
Michael Han84324352013-02-22 17:15:32 +000013035 CurContext->addDecl(ED);
13036 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000013037}
13038
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013039/// \brief Perform semantic analysis for the variable declaration that
13040/// occurs within a C++ catch clause, returning the newly-created
13041/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000013042VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000013043 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000013044 SourceLocation StartLoc,
13045 SourceLocation Loc,
13046 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013047 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013048 QualType ExDeclType = TInfo->getType();
13049
Sebastian Redl54c04d42008-12-22 19:15:10 +000013050 // Arrays and functions decay.
13051 if (ExDeclType->isArrayType())
13052 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13053 else if (ExDeclType->isFunctionType())
13054 ExDeclType = Context.getPointerType(ExDeclType);
13055
13056 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13057 // The exception-declaration shall not denote a pointer or reference to an
13058 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013059 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013060 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013061 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013062 Invalid = true;
13063 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013064
David Majnemere56d1a02016-06-08 16:05:07 +000013065 if (ExDeclType->isVariablyModifiedType()) {
13066 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13067 Invalid = true;
13068 }
13069
Sebastian Redl54c04d42008-12-22 19:15:10 +000013070 QualType BaseType = ExDeclType;
13071 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013072 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013073 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013074 BaseType = Ptr->getPointeeType();
13075 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013076 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013077 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013078 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013079 BaseType = Ref->getPointeeType();
13080 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013081 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013082 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013083 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013084 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013085 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013086
Mike Stump11289f42009-09-09 15:08:12 +000013087 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013088 RequireNonAbstractType(Loc, ExDeclType,
13089 diag::err_abstract_type_in_decl,
13090 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013091 Invalid = true;
13092
John McCall2ca705e2010-07-24 00:37:23 +000013093 // Only the non-fragile NeXT runtime currently supports C++ catches
13094 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013095 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013096 QualType T = ExDeclType;
13097 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13098 T = RT->getPointeeType();
13099
13100 if (T->isObjCObjectType()) {
13101 Diag(Loc, diag::err_objc_object_catch);
13102 Invalid = true;
13103 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013104 // FIXME: should this be a test for macosx-fragile specifically?
13105 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013106 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013107 }
13108 }
13109
Abramo Bagnaradff19302011-03-08 08:55:46 +000013110 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013111 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013112 ExDecl->setExceptionVariable(true);
13113
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013114 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013115 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013116 Invalid = true;
13117
Douglas Gregor750734c2011-07-06 18:14:43 +000013118 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013119 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013120 // Insulate this from anything else we might currently be parsing.
Faisal Valid143a0c2017-04-01 21:30:49 +000013121 EnterExpressionEvaluationContext scope(
13122 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
John McCalleaef89b2013-03-22 02:10:40 +000013123
Douglas Gregor6de584c2010-03-05 23:38:39 +000013124 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013125 // The object declared in an exception-declaration or, if the
13126 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013127 // copy-initialized (8.5) from the exception object. [...]
13128 // The object is destroyed when the handler exits, after the destruction
13129 // of any automatic objects initialized within the handler.
13130 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013131 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013132 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013133 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013134
13135 InitializedEntity entity =
13136 InitializedEntity::InitializeVariable(ExDecl);
13137 InitializationKind initKind =
13138 InitializationKind::CreateCopy(Loc, SourceLocation());
13139
13140 Expr *opaqueValue =
13141 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013142 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13143 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013144 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013145 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013146 else {
13147 // If the constructor used was non-trivial, set this as the
13148 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013149 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013150 if (!construct->getConstructor()->isTrivial()) {
13151 Expr *init = MaybeCreateExprWithCleanups(construct);
13152 ExDecl->setInit(init);
13153 }
13154
13155 // And make sure it's destructable.
13156 FinalizeVarWithDestructor(ExDecl, recordType);
13157 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013158 }
13159 }
13160
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013161 if (Invalid)
13162 ExDecl->setInvalidDecl();
13163
13164 return ExDecl;
13165}
13166
13167/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13168/// handler.
John McCall48871652010-08-21 09:40:31 +000013169Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013170 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013171 bool Invalid = D.isInvalidType();
13172
13173 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013174 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13175 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013176 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13177 D.getIdentifierLoc());
13178 Invalid = true;
13179 }
13180
Sebastian Redl54c04d42008-12-22 19:15:10 +000013181 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013182 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013183 LookupOrdinaryName,
13184 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013185 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013186 // it contains any previous declaration, except for function parameters in
13187 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013188 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013189 if (isDeclInScope(PrevDecl, CurContext, S)) {
13190 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13191 << D.getIdentifier();
13192 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13193 Invalid = true;
13194 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013195 // Maybe we will complain about the shadowed template parameter.
13196 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013197 }
13198
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013199 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013200 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13201 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013202 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013203 }
13204
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013205 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013206 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013207 D.getIdentifierLoc(),
13208 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013209 if (Invalid)
13210 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013211
Sebastian Redl54c04d42008-12-22 19:15:10 +000013212 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013213 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013214 PushOnScopeChains(ExDecl, S);
13215 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013216 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013217
Douglas Gregor758a8692009-06-17 21:51:59 +000013218 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013219 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013220}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013221
Abramo Bagnaraea947882011-03-08 16:41:52 +000013222Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013223 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013224 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013225 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013226 StringLiteral *AssertMessage =
13227 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013228
Richard Smithded9c2e2012-07-11 22:37:56 +000013229 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013230 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013231
13232 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13233 AssertMessage, RParenLoc, false);
13234}
13235
13236Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13237 Expr *AssertExpr,
13238 StringLiteral *AssertMessage,
13239 SourceLocation RParenLoc,
13240 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013241 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013242 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13243 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013244 // In a static_assert-declaration, the constant-expression shall be a
13245 // constant expression that can be contextually converted to bool.
13246 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13247 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013248 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013249
Richard Smith902ca212011-12-14 23:32:26 +000013250 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013251 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013252 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013253 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013254 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013255
Richard Smithded9c2e2012-07-11 22:37:56 +000013256 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013257 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013258 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013259 if (AssertMessage)
13260 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013261 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013262 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013263 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013264 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013265 }
Mike Stump11289f42009-09-09 15:08:12 +000013266
Abramo Bagnaraea947882011-03-08 16:41:52 +000013267 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013268 AssertExpr, AssertMessage, RParenLoc,
13269 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013270
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013271 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013272 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013273}
Sebastian Redlf769df52009-03-24 22:27:57 +000013274
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013275/// \brief Perform semantic analysis of the given friend type declaration.
13276///
13277/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013278FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013279 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013280 TypeSourceInfo *TSInfo) {
13281 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13282
13283 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013284 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013285
Richard Smithc8239732011-10-18 21:39:00 +000013286 // C++03 [class.friend]p2:
13287 // An elaborated-type-specifier shall be used in a friend declaration
13288 // for a class.*
13289 //
13290 // * The class-key of the elaborated-type-specifier is required.
Richard Smith696e3122017-02-23 01:43:54 +000013291 if (!CodeSynthesisContexts.empty()) {
13292 // Do not complain about the form of friend template types during any kind
13293 // of code synthesis. For template instantiation, we will have complained
13294 // when the template was defined.
Nick Lewycky36722d22013-02-06 05:59:33 +000013295 } else {
13296 if (!T->isElaboratedTypeSpecifier()) {
13297 // If we evaluated the type to a record type, suggest putting
13298 // a tag in front.
13299 if (const RecordType *RT = T->getAs<RecordType>()) {
13300 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013301
13302 SmallString<16> InsertionText(" ");
13303 InsertionText += RD->getKindName();
13304
Nick Lewycky36722d22013-02-06 05:59:33 +000013305 Diag(TypeRange.getBegin(),
13306 getLangOpts().CPlusPlus11 ?
13307 diag::warn_cxx98_compat_unelaborated_friend_type :
13308 diag::ext_unelaborated_friend_type)
13309 << (unsigned) RD->getTagKind()
13310 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013311 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013312 InsertionText);
13313 } else {
13314 Diag(FriendLoc,
13315 getLangOpts().CPlusPlus11 ?
13316 diag::warn_cxx98_compat_nonclass_type_friend :
13317 diag::ext_nonclass_type_friend)
13318 << T
13319 << TypeRange;
13320 }
13321 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013322 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013323 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013324 diag::warn_cxx98_compat_enum_friend :
13325 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013326 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013327 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013328 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013329
Nick Lewycky36722d22013-02-06 05:59:33 +000013330 // C++11 [class.friend]p3:
13331 // A friend declaration that does not declare a function shall have one
13332 // of the following forms:
13333 // friend elaborated-type-specifier ;
13334 // friend simple-type-specifier ;
13335 // friend typename-specifier ;
13336 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13337 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13338 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013339
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013340 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013341 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013342 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013343 return FriendDecl::Create(Context, CurContext,
13344 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13345 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013346}
13347
John McCallace48cd2010-10-19 01:40:49 +000013348/// Handle a friend tag declaration where the scope specifier was
13349/// templated.
13350Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13351 unsigned TagSpec, SourceLocation TagLoc,
13352 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013353 IdentifierInfo *Name,
13354 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013355 AttributeList *Attr,
13356 MultiTemplateParamsArg TempParamLists) {
13357 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13358
Richard Smithf445f192017-02-09 21:04:43 +000013359 bool IsMemberSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013360 bool Invalid = false;
13361
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013362 if (TemplateParameterList *TemplateParams =
13363 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013364 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Richard Smithf445f192017-02-09 21:04:43 +000013365 IsMemberSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013366 if (TemplateParams->size() > 0) {
13367 // This is a declaration of a class template.
13368 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013369 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013370
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013371 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13372 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013373 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013374 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013375 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013376 } else {
13377 // The "template<>" header is extraneous.
13378 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13379 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Richard Smithf445f192017-02-09 21:04:43 +000013380 IsMemberSpecialization = true;
John McCallace48cd2010-10-19 01:40:49 +000013381 }
13382 }
13383
Craig Topperc3ec1492014-05-26 06:22:03 +000013384 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013385
John McCallace48cd2010-10-19 01:40:49 +000013386 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013387 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013388 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013389 isAllExplicitSpecializations = false;
13390 break;
13391 }
13392 }
13393
13394 // FIXME: don't ignore attributes.
13395
13396 // If it's explicit specializations all the way down, just forget
13397 // about the template header and build an appropriate non-templated
13398 // friend. TODO: for source fidelity, remember the headers.
13399 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013400 if (SS.isEmpty()) {
13401 bool Owned = false;
13402 bool IsDependent = false;
13403 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013404 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013405 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013406 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013407 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013408 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013409 /*UnderlyingType=*/TypeResult(),
13410 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013411 }
Richard Smith649c7b062014-01-08 00:56:48 +000013412
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013413 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013414 ElaboratedTypeKeyword Keyword
13415 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013416 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013417 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013418 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013419 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013420
13421 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13422 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013423 DependentNameTypeLoc TL =
13424 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013425 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013426 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013427 TL.setNameLoc(NameLoc);
13428 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013429 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013430 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013431 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013432 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013433 }
13434
13435 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013436 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013437 Friend->setAccess(AS_public);
13438 CurContext->addDecl(Friend);
13439 return Friend;
13440 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013441
13442 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13443
13444
John McCallace48cd2010-10-19 01:40:49 +000013445
13446 // Handle the case of a templated-scope friend class. e.g.
13447 // template <class T> class A<T>::B;
13448 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013449 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13450 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013451 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13452 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13453 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013454 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013455 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013456 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013457 TL.setNameLoc(NameLoc);
13458
13459 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013460 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013461 Friend->setAccess(AS_public);
13462 Friend->setUnsupportedFriend(true);
13463 CurContext->addDecl(Friend);
13464 return Friend;
13465}
13466
13467
John McCall11083da2009-09-16 22:47:08 +000013468/// Handle a friend type declaration. This works in tandem with
13469/// ActOnTag.
13470///
13471/// Notes on friend class templates:
13472///
13473/// We generally treat friend class declarations as if they were
13474/// declaring a class. So, for example, the elaborated type specifier
13475/// in a friend declaration is required to obey the restrictions of a
13476/// class-head (i.e. no typedefs in the scope chain), template
13477/// parameters are required to match up with simple template-ids, &c.
13478/// However, unlike when declaring a template specialization, it's
13479/// okay to refer to a template specialization without an empty
13480/// template parameter declaration, e.g.
13481/// friend class A<T>::B<unsigned>;
13482/// We permit this as a special case; if there are any template
13483/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013484/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013485Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013486 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013487 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013488
13489 assert(DS.isFriendSpecified());
13490 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13491
John McCall11083da2009-09-16 22:47:08 +000013492 // Try to convert the decl specifier to a type. This works for
13493 // friend templates because ActOnTag never produces a ClassTemplateDecl
13494 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013495 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013496 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13497 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013498 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013499 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013500
Douglas Gregor6c110f32010-12-16 01:14:37 +000013501 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013502 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013503
John McCall11083da2009-09-16 22:47:08 +000013504 // This is definitely an error in C++98. It's probably meant to
13505 // be forbidden in C++0x, too, but the specification is just
13506 // poorly written.
13507 //
13508 // The problem is with declarations like the following:
13509 // template <T> friend A<T>::foo;
13510 // where deciding whether a class C is a friend or not now hinges
13511 // on whether there exists an instantiation of A that causes
13512 // 'foo' to equal C. There are restrictions on class-heads
13513 // (which we declare (by fiat) elaborated friend declarations to
13514 // be) that makes this tractable.
13515 //
13516 // FIXME: handle "template <> friend class A<T>;", which
13517 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013518 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013519 Diag(Loc, diag::err_tagless_friend_type_template)
13520 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013521 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013522 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013523
John McCallaa74a0c2009-08-28 07:59:38 +000013524 // C++98 [class.friend]p1: A friend of a class is a function
13525 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013526 // This is fixed in DR77, which just barely didn't make the C++03
13527 // deadline. It's also a very silly restriction that seriously
13528 // affects inner classes and which nobody else seems to implement;
13529 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013530 //
13531 // But note that we could warn about it: it's always useless to
13532 // friend one of your own members (it's not, however, worthless to
13533 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013534
John McCall11083da2009-09-16 22:47:08 +000013535 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013536 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013537 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013538 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013539 TSI,
John McCall11083da2009-09-16 22:47:08 +000013540 DS.getFriendSpecLoc());
13541 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013542 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013543
13544 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013545 return nullptr;
13546
John McCall11083da2009-09-16 22:47:08 +000013547 D->setAccess(AS_public);
13548 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013549
John McCall48871652010-08-21 09:40:31 +000013550 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013551}
13552
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013553NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13554 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013555 const DeclSpec &DS = D.getDeclSpec();
13556
13557 assert(DS.isFriendSpecified());
13558 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13559
13560 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013561 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013562
13563 // C++ [class.friend]p1
13564 // A friend of a class is a function or class....
13565 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013566 // It *doesn't* see through dependent types, which is correct
13567 // according to [temp.arg.type]p3:
13568 // If a declaration acquires a function type through a
13569 // type dependent on a template-parameter and this causes
13570 // a declaration that does not use the syntactic form of a
13571 // function declarator to have a function type, the program
13572 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013573 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013574 Diag(Loc, diag::err_unexpected_friend);
13575
13576 // It might be worthwhile to try to recover by creating an
13577 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013578 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013579 }
13580
13581 // C++ [namespace.memdef]p3
13582 // - If a friend declaration in a non-local class first declares a
13583 // class or function, the friend class or function is a member
13584 // of the innermost enclosing namespace.
13585 // - The name of the friend is not found by simple name lookup
13586 // until a matching declaration is provided in that namespace
13587 // scope (either before or after the class declaration granting
13588 // friendship).
13589 // - If a friend function is called, its name may be found by the
13590 // name lookup that considers functions from namespaces and
13591 // classes associated with the types of the function arguments.
13592 // - When looking for a prior declaration of a class or a function
13593 // declared as a friend, scopes outside the innermost enclosing
13594 // namespace scope are not considered.
13595
John McCallde3fd222010-10-12 23:13:28 +000013596 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013597 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13598 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013599 assert(Name);
13600
Douglas Gregor6c110f32010-12-16 01:14:37 +000013601 // Check for unexpanded parameter packs.
13602 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13603 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13604 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013605 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013606
John McCall07e91c02009-08-06 02:15:43 +000013607 // The context we found the declaration in, or in which we should
13608 // create the declaration.
13609 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013610 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013611 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013612 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013613
Richard Smith114394f2013-08-09 04:35:01 +000013614 // There are five cases here.
13615 // - There's no scope specifier and we're in a local class. Only look
13616 // for functions declared in the immediately-enclosing block scope.
13617 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013618 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013619 if ((SS.isInvalid() || !SS.isSet()) &&
13620 (FunctionContainingLocalClass =
13621 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13622 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013623 // If a friend declaration appears in a local class and the name
13624 // specified is an unqualified name, a prior declaration is
13625 // looked up without considering scopes that are outside the
13626 // innermost enclosing non-class scope. For a friend function
13627 // declaration, if there is no prior declaration, the program is
13628 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013629
13630 // Find the innermost enclosing non-class scope. This is the block
13631 // scope containing the local class definition (or for a nested class,
13632 // the outer local class).
13633 DCScope = S->getFnParent();
13634
13635 // Look up the function name in the scope.
13636 Previous.clear(LookupLocalFriendName);
13637 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13638
13639 if (!Previous.empty()) {
13640 // All possible previous declarations must have the same context:
13641 // either they were declared at block scope or they are members of
13642 // one of the enclosing local classes.
13643 DC = Previous.getRepresentativeDecl()->getDeclContext();
13644 } else {
13645 // This is ill-formed, but provide the context that we would have
13646 // declared the function in, if we were permitted to, for error recovery.
13647 DC = FunctionContainingLocalClass;
13648 }
Richard Smith541b38b2013-09-20 01:15:31 +000013649 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013650
13651 // C++ [class.friend]p6:
13652 // A function can be defined in a friend declaration of a class if and
13653 // only if the class is a non-local class (9.8), the function name is
13654 // unqualified, and the function has namespace scope.
13655 if (D.isFunctionDefinition()) {
13656 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13657 }
13658
13659 // - There's no scope specifier, in which case we just go to the
13660 // appropriate scope and look for a function or function template
13661 // there as appropriate.
13662 } else if (SS.isInvalid() || !SS.isSet()) {
13663 // C++11 [namespace.memdef]p3:
13664 // If the name in a friend declaration is neither qualified nor
13665 // a template-id and the declaration is a function or an
13666 // elaborated-type-specifier, the lookup to determine whether
13667 // the entity has been previously declared shall not consider
13668 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013669 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013670
John McCallf7cfb222010-10-13 05:45:15 +000013671 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013672 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013673
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013674 // Skip class contexts. If someone can cite chapter and verse
13675 // for this behavior, that would be nice --- it's what GCC and
13676 // EDG do, and it seems like a reasonable intent, but the spec
13677 // really only says that checks for unqualified existing
13678 // declarations should stop at the nearest enclosing namespace,
13679 // not that they should only consider the nearest enclosing
13680 // namespace.
13681 while (DC->isRecord())
13682 DC = DC->getParent();
13683
13684 DeclContext *LookupDC = DC;
13685 while (LookupDC->isTransparentContext())
13686 LookupDC = LookupDC->getParent();
13687
13688 while (true) {
13689 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013690
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013691 if (!Previous.empty()) {
13692 DC = LookupDC;
13693 break;
John McCallf4776592010-10-14 22:22:28 +000013694 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013695
13696 if (isTemplateId) {
13697 if (isa<TranslationUnitDecl>(LookupDC)) break;
13698 } else {
13699 if (LookupDC->isFileContext()) break;
13700 }
13701 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013702 }
13703
John McCallccbc0322010-10-13 06:22:15 +000013704 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013705
John McCallde3fd222010-10-12 23:13:28 +000013706 // - There's a non-dependent scope specifier, in which case we
13707 // compute it and do a previous lookup there for a function
13708 // or function template.
13709 } else if (!SS.getScopeRep()->isDependent()) {
13710 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013711 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013712
Craig Topperc3ec1492014-05-26 06:22:03 +000013713 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013714
13715 LookupQualifiedName(Previous, DC);
13716
13717 // Ignore things found implicitly in the wrong scope.
13718 // TODO: better diagnostics for this case. Suggesting the right
13719 // qualified scope would be nice...
13720 LookupResult::Filter F = Previous.makeFilter();
13721 while (F.hasNext()) {
13722 NamedDecl *D = F.next();
13723 if (!DC->InEnclosingNamespaceSetOf(
13724 D->getDeclContext()->getRedeclContext()))
13725 F.erase();
13726 }
13727 F.done();
13728
13729 if (Previous.empty()) {
13730 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013731 Diag(Loc, diag::err_qualified_friend_not_found)
13732 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013733 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013734 }
13735
13736 // C++ [class.friend]p1: A friend of a class is a function or
13737 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013738 if (DC->Equals(CurContext))
13739 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013740 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013741 diag::warn_cxx98_compat_friend_is_member :
13742 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013743
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013744 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013745 // C++ [class.friend]p6:
13746 // A function can be defined in a friend declaration of a class if and
13747 // only if the class is a non-local class (9.8), the function name is
13748 // unqualified, and the function has namespace scope.
13749 SemaDiagnosticBuilder DB
13750 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13751
13752 DB << SS.getScopeRep();
13753 if (DC->isFileContext())
13754 DB << FixItHint::CreateRemoval(SS.getRange());
13755 SS.clear();
13756 }
John McCallde3fd222010-10-12 23:13:28 +000013757
13758 // - There's a scope specifier that does not match any template
13759 // parameter lists, in which case we use some arbitrary context,
13760 // create a method or method template, and wait for instantiation.
13761 // - There's a scope specifier that does match some template
13762 // parameter lists, which we don't handle right now.
13763 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013764 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013765 // C++ [class.friend]p6:
13766 // A function can be defined in a friend declaration of a class if and
13767 // only if the class is a non-local class (9.8), the function name is
13768 // unqualified, and the function has namespace scope.
13769 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13770 << SS.getScopeRep();
13771 }
13772
John McCallde3fd222010-10-12 23:13:28 +000013773 DC = CurContext;
13774 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013775 }
David Majnemere14d5302015-09-30 22:07:43 +000013776
John McCallf7cfb222010-10-13 05:45:15 +000013777 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013778 int DiagArg = -1;
13779 switch (D.getName().getKind()) {
13780 case UnqualifiedId::IK_ConstructorTemplateId:
13781 case UnqualifiedId::IK_ConstructorName:
13782 DiagArg = 0;
13783 break;
13784 case UnqualifiedId::IK_DestructorName:
13785 DiagArg = 1;
13786 break;
13787 case UnqualifiedId::IK_ConversionFunctionId:
13788 DiagArg = 2;
13789 break;
Richard Smith35845152017-02-07 01:37:30 +000013790 case UnqualifiedId::IK_DeductionGuideName:
13791 DiagArg = 3;
13792 break;
David Majnemere14d5302015-09-30 22:07:43 +000013793 case UnqualifiedId::IK_Identifier:
13794 case UnqualifiedId::IK_ImplicitSelfParam:
13795 case UnqualifiedId::IK_LiteralOperatorId:
13796 case UnqualifiedId::IK_OperatorFunctionId:
13797 case UnqualifiedId::IK_TemplateId:
13798 break;
David Majnemere14d5302015-09-30 22:07:43 +000013799 }
John McCall07e91c02009-08-06 02:15:43 +000013800 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013801 if (DiagArg >= 0) {
13802 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013803 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013804 }
John McCall07e91c02009-08-06 02:15:43 +000013805 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013806
Douglas Gregordd847ba2011-11-03 16:37:14 +000013807 // FIXME: This is an egregious hack to cope with cases where the scope stack
13808 // does not contain the declaration context, i.e., in an out-of-line
13809 // definition of a class.
13810 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13811 if (!DCScope) {
13812 FakeDCScope.setEntity(DC);
13813 DCScope = &FakeDCScope;
13814 }
Richard Smith114394f2013-08-09 04:35:01 +000013815
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013816 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013817 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013818 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013819 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013820
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013821 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013822
Richard Smith114394f2013-08-09 04:35:01 +000013823 // If we performed typo correction, we might have added a scope specifier
13824 // and changed the decl context.
13825 DC = ND->getDeclContext();
13826
John McCall759e32b2009-08-31 22:39:49 +000013827 // Add the function declaration to the appropriate lookup tables,
13828 // adjusting the redeclarations list as necessary. We don't
13829 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013830 //
John McCall759e32b2009-08-31 22:39:49 +000013831 // Also update the scope-based lookup if the target context's
13832 // lookup context is in lexical scope.
13833 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013834 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013835 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013836 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013837 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013838 }
John McCallaa74a0c2009-08-28 07:59:38 +000013839
13840 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013841 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013842 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013843 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013844 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013845
John McCalla0a96892012-08-10 03:15:35 +000013846 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013847 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013848 } else {
13849 if (DC->isRecord()) CheckFriendAccess(ND);
13850
John McCall2c2eb122010-10-16 06:59:13 +000013851 FunctionDecl *FD;
13852 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13853 FD = FTD->getTemplatedDecl();
13854 else
13855 FD = cast<FunctionDecl>(ND);
13856
David Majnemer502b0ed2013-06-25 23:09:30 +000013857 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13858 // default argument expression, that declaration shall be a definition
13859 // and shall be the only declaration of the function or function
13860 // template in the translation unit.
13861 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013862 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013863 // if we're in a dependent context. If the function is known to be a
13864 // redeclaration, we will have narrowed Previous down to the right decl.
13865 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013866 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013867 Diag(Previous.getRepresentativeDecl()->getLocation(),
13868 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013869 } else if (!D.isFunctionDefinition())
13870 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13871 }
13872
John McCall2c2eb122010-10-16 06:59:13 +000013873 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013874 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13875 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13876 << SS.getScopeRep() << SS.getRange()
13877 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013878 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013879 }
John McCall2c2eb122010-10-16 06:59:13 +000013880 }
John McCallde3fd222010-10-12 23:13:28 +000013881
John McCall48871652010-08-21 09:40:31 +000013882 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013883}
13884
John McCall48871652010-08-21 09:40:31 +000013885void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13886 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013887
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013888 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013889 if (!Fn) {
13890 Diag(DelLoc, diag::err_deleted_non_function);
13891 return;
13892 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013893
Douglas Gregorec9fd132012-01-14 16:38:05 +000013894 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013895 // Don't consider the implicit declaration we generate for explicit
13896 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013897 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13898 Prev->getPreviousDecl()) &&
13899 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013900 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013901 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13902 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13903 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013904 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013905 // If the declaration wasn't the first, we delete the function anyway for
13906 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013907 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013908 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013909
Nico Rieck9de0a572014-05-29 16:51:19 +000013910 // dllimport/dllexport cannot be deleted.
13911 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13912 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13913 Fn->setInvalidDecl();
13914 }
13915
Richard Smithb4d2a152013-04-02 19:38:47 +000013916 if (Fn->isDeleted())
13917 return;
13918
13919 // See if we're deleting a function which is already known to override a
13920 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013921 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013922 bool IssuedDiagnostic = false;
13923 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13924 E = MD->end_overridden_methods();
13925 I != E; ++I) {
13926 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13927 if (!IssuedDiagnostic) {
13928 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13929 IssuedDiagnostic = true;
13930 }
13931 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13932 }
13933 }
Richard Smithf3cec652016-10-31 18:18:29 +000013934 // If this function was implicitly deleted because it was defaulted,
13935 // explain why it was deleted.
13936 if (IssuedDiagnostic && MD->isDefaulted())
13937 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13938 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000013939 }
13940
Richard Smithb63b6ee2014-01-22 01:43:19 +000013941 // C++11 [basic.start.main]p3:
13942 // A program that defines main as deleted [...] is ill-formed.
13943 if (Fn->isMain())
13944 Diag(DelLoc, diag::err_deleted_main);
13945
Eric Fiselier525a3512016-10-31 23:07:15 +000013946 // C++11 [dcl.fct.def.delete]p4:
13947 // A deleted function is implicitly inline.
13948 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013949 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013950}
Sebastian Redl4c018662009-04-27 21:33:24 +000013951
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013952void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013953 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013954
13955 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013956 if (MD->getParent()->isDependentType()) {
13957 MD->setDefaulted();
13958 MD->setExplicitlyDefaulted();
13959 return;
13960 }
13961
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013962 CXXSpecialMember Member = getSpecialMember(MD);
13963 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013964 if (!MD->isInvalidDecl())
13965 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013966 return;
13967 }
13968
13969 MD->setDefaulted();
13970 MD->setExplicitlyDefaulted();
13971
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013972 // If this definition appears within the record, do the checking when
13973 // the record is complete.
13974 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013975 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013976 // Ask the template instantiation pattern that actually had the
13977 // '= default' on it.
13978 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013979
Richard Smith3901dfe2013-03-27 00:22:47 +000013980 // If the method was defaulted on its first declaration, we will have
13981 // already performed the checking in CheckCompletedCXXClass. Such a
13982 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013983 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013984 return;
13985
Richard Smithd3b5c9082012-07-27 04:22:15 +000013986 CheckExplicitlyDefaultedSpecialMember(MD);
13987
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013988 if (!MD->isInvalidDecl())
13989 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013990 } else {
13991 Diag(DefaultLoc, diag::err_default_special_members);
13992 }
13993}
13994
Sebastian Redl4c018662009-04-27 21:33:24 +000013995static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013996 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013997 if (!SubStmt)
13998 continue;
13999 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014000 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000014001 diag::err_return_in_constructor_handler);
14002 if (!isa<Expr>(SubStmt))
14003 SearchForReturnInStmt(Self, SubStmt);
14004 }
14005}
14006
14007void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14008 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14009 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14010 SearchForReturnInStmt(*this, Handler);
14011 }
14012}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014013
David Blaikie68f71a32013-01-18 23:03:15 +000014014bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000014015 const CXXMethodDecl *Old) {
14016 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14017 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14018
14019 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14020
14021 // If the calling conventions match, everything is fine
14022 if (NewCC == OldCC)
14023 return false;
14024
Hans Wennborg2545efe2013-12-11 17:42:11 +000014025 // If the calling conventions mismatch because the new function is static,
14026 // suppress the calling convention mismatch error; the error about static
14027 // function override (err_static_overrides_virtual from
14028 // Sema::CheckFunctionDeclaration) is more clear.
14029 if (New->getStorageClass() == SC_Static)
14030 return false;
14031
Reid Kleckner78af0702013-08-27 23:08:25 +000014032 Diag(New->getLocation(),
14033 diag::err_conflicting_overriding_cc_attributes)
14034 << New->getDeclName() << New->getType() << Old->getType();
14035 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14036 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000014037}
14038
Mike Stump11289f42009-09-09 15:08:12 +000014039bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014040 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000014041 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14042 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014043
Chandler Carruth284bb2e2010-02-15 11:53:20 +000014044 if (Context.hasSameType(NewTy, OldTy) ||
14045 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014046 return false;
Mike Stump11289f42009-09-09 15:08:12 +000014047
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014048 // Check if the return types are covariant
14049 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000014050
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014051 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014052 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14053 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014054 NewClassTy = NewPT->getPointeeType();
14055 OldClassTy = OldPT->getPointeeType();
14056 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014057 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14058 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14059 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14060 NewClassTy = NewRT->getPointeeType();
14061 OldClassTy = OldRT->getPointeeType();
14062 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014063 }
14064 }
Mike Stump11289f42009-09-09 15:08:12 +000014065
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014066 // The return types aren't either both pointers or references to a class type.
14067 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014068 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014069 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014070 << New->getDeclName() << NewTy << OldTy
14071 << New->getReturnTypeSourceRange();
14072 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14073 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014074
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014075 return true;
14076 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014077
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014078 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014079 // C++14 [class.virtual]p8:
14080 // If the class type in the covariant return type of D::f differs from
14081 // that of B::f, the class type in the return type of D::f shall be
14082 // complete at the point of declaration of D::f or shall be the class
14083 // type D.
14084 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14085 if (!RT->isBeingDefined() &&
14086 RequireCompleteType(New->getLocation(), NewClassTy,
14087 diag::err_covariant_return_incomplete,
14088 New->getDeclName()))
14089 return true;
14090 }
14091
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014092 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014093 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014094 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14095 << New->getDeclName() << NewTy << OldTy
14096 << New->getReturnTypeSourceRange();
14097 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14098 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014099 return true;
14100 }
Mike Stump11289f42009-09-09 15:08:12 +000014101
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014102 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014103 if (CheckDerivedToBaseConversion(
14104 NewClassTy, OldClassTy,
14105 diag::err_covariant_return_inaccessible_base,
14106 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14107 New->getLocation(), New->getReturnTypeSourceRange(),
14108 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014109 // FIXME: this note won't trigger for delayed access control
14110 // diagnostics, and it's impossible to get an undelayed error
14111 // here from access control during the original parse because
14112 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014113 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14114 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014115 return true;
14116 }
14117 }
Mike Stump11289f42009-09-09 15:08:12 +000014118
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014119 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014120 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014121 Diag(New->getLocation(),
14122 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014123 << New->getDeclName() << NewTy << OldTy
14124 << New->getReturnTypeSourceRange();
14125 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14126 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014127 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014128 }
Mike Stump11289f42009-09-09 15:08:12 +000014129
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014130
14131 // The new class type must have the same or less qualifiers as the old type.
14132 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14133 Diag(New->getLocation(),
14134 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014135 << New->getDeclName() << NewTy << OldTy
14136 << New->getReturnTypeSourceRange();
14137 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14138 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014139 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014140 }
Mike Stump11289f42009-09-09 15:08:12 +000014141
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014142 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014143}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014144
Douglas Gregor21920e372009-12-01 17:24:26 +000014145/// \brief Mark the given method pure.
14146///
14147/// \param Method the method to be marked pure.
14148///
14149/// \param InitRange the source range that covers the "0" initializer.
14150bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014151 SourceLocation EndLoc = InitRange.getEnd();
14152 if (EndLoc.isValid())
14153 Method->setRangeEnd(EndLoc);
14154
Douglas Gregor21920e372009-12-01 17:24:26 +000014155 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14156 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014157 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014158 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014159
14160 if (!Method->isInvalidDecl())
14161 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14162 << Method->getDeclName() << InitRange;
14163 return true;
14164}
14165
Richard Smith9ba0fec2015-06-30 01:28:56 +000014166void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14167 if (D->getFriendObjectKind())
14168 Diag(D->getLocation(), diag::err_pure_friend);
14169 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14170 CheckPureMethod(M, ZeroLoc);
14171 else
14172 Diag(D->getLocation(), diag::err_illegal_initializer);
14173}
14174
Douglas Gregor926410d2012-02-21 02:22:07 +000014175/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014176static bool isStaticDataMember(const Decl *D) {
14177 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14178 return Var->isStaticDataMember();
14179
14180 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014181}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014182
John McCall1f4ee7b2009-12-19 09:28:58 +000014183/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14184/// an initializer for the out-of-line declaration 'Dcl'. The scope
14185/// is a fresh scope pushed for just this purpose.
14186///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014187/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14188/// static data member of class X, names should be looked up in the scope of
14189/// class X.
John McCall48871652010-08-21 09:40:31 +000014190void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014191 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014192 if (!D || D->isInvalidDecl())
14193 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014194
Richard Smitha2302242013-12-05 07:51:02 +000014195 // We will always have a nested name specifier here, but this declaration
14196 // might not be out of line if the specifier names the current namespace:
14197 // extern int n;
14198 // int ::n = 0;
14199 if (D->isOutOfLine())
14200 EnterDeclaratorContext(S, D->getDeclContext());
14201
Douglas Gregor926410d2012-02-21 02:22:07 +000014202 // If we are parsing the initializer for a static data member, push a
14203 // new expression evaluation context that is associated with this static
14204 // data member.
14205 if (isStaticDataMember(D))
Faisal Valid143a0c2017-04-01 21:30:49 +000014206 PushExpressionEvaluationContext(
14207 ExpressionEvaluationContext::PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014208}
14209
14210/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014211/// initializer for the out-of-line declaration 'D'.
14212void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014213 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014214 if (!D || D->isInvalidDecl())
14215 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014216
Douglas Gregor926410d2012-02-21 02:22:07 +000014217 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014218 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014219
Richard Smitha2302242013-12-05 07:51:02 +000014220 if (D->isOutOfLine())
14221 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014222}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014223
14224/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14225/// C++ if/switch/while/for statement.
14226/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014227DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014228 // C++ 6.4p2:
14229 // The declarator shall not specify a function or an array.
14230 // The type-specifier-seq shall not contain typedef and shall not declare a
14231 // new class or enumeration.
14232 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14233 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014234
14235 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014236 if (!Dcl)
14237 return true;
14238
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014239 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14240 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014241 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014242 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014243 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014244
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014245 return Dcl;
14246}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014247
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014248void Sema::LoadExternalVTableUses() {
14249 if (!ExternalSource)
14250 return;
14251
14252 SmallVector<ExternalVTableUse, 4> VTables;
14253 ExternalSource->ReadUsedVTables(VTables);
14254 SmallVector<VTableUse, 4> NewUses;
14255 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14256 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14257 = VTablesUsed.find(VTables[I].Record);
14258 // Even if a definition wasn't required before, it may be required now.
14259 if (Pos != VTablesUsed.end()) {
14260 if (!Pos->second && VTables[I].DefinitionRequired)
14261 Pos->second = true;
14262 continue;
14263 }
14264
14265 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14266 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14267 }
14268
14269 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14270}
14271
Douglas Gregor88d292c2010-05-13 16:44:06 +000014272void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14273 bool DefinitionRequired) {
14274 // Ignore any vtable uses in unevaluated operands or for classes that do
14275 // not have a vtable.
14276 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014277 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014278 return;
14279
Douglas Gregor88d292c2010-05-13 16:44:06 +000014280 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014281 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014282 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14283 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14284 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14285 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014286 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014287 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014288 // list, since we may have already processed the first entry.
14289 if (DefinitionRequired && !Pos.first->second) {
14290 Pos.first->second = true;
14291 } else {
14292 // Otherwise, we can early exit.
14293 return;
14294 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014295 } else {
14296 // The Microsoft ABI requires that we perform the destructor body
14297 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14298 // the deleting destructor is emitted with the vtable, not with the
14299 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014300 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014301 CXXDestructorDecl *DD = Class->getDestructor();
14302 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14303 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14304 // If this is an out-of-line declaration, marking it referenced will
14305 // not do anything. Manually call CheckDestructor to look up operator
14306 // delete().
14307 ContextRAII SavedContext(*this, DD);
14308 CheckDestructor(DD);
14309 } else {
14310 MarkFunctionReferenced(Loc, Class->getDestructor());
14311 }
Hans Wennborg34804352016-04-13 20:21:15 +000014312 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014313 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014314 }
14315
14316 // Local classes need to have their virtual members marked
14317 // immediately. For all other classes, we mark their virtual members
14318 // at the end of the translation unit.
14319 if (Class->isLocalClass())
14320 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014321 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014322 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014323}
14324
Douglas Gregor88d292c2010-05-13 16:44:06 +000014325bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014326 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014327 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014328 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014329
Douglas Gregor88d292c2010-05-13 16:44:06 +000014330 // Note: The VTableUses vector could grow as a result of marking
14331 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014332 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014333 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014334 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014335 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014336 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014337 if (!Class)
14338 continue;
Reid Klecknerb792e062016-12-06 21:44:41 +000014339 TemplateSpecializationKind ClassTSK =
14340 Class->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014341
14342 SourceLocation Loc = VTableUses[I].second;
14343
Richard Smithd3b5c9082012-07-27 04:22:15 +000014344 bool DefineVTable = true;
14345
Douglas Gregor88d292c2010-05-13 16:44:06 +000014346 // If this class has a key function, but that key function is
14347 // defined in another translation unit, we don't need to emit the
14348 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014349 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014350 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014351 // The key function is in another translation unit.
14352 DefineVTable = false;
14353 TemplateSpecializationKind TSK =
14354 KeyFunction->getTemplateSpecializationKind();
14355 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14356 TSK != TSK_ImplicitInstantiation &&
14357 "Instantiations don't have key functions");
14358 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014359 } else if (!KeyFunction) {
14360 // If we have a class with no key function that is the subject
14361 // of an explicit instantiation declaration, suppress the
14362 // vtable; it will live with the explicit instantiation
14363 // definition.
Reid Klecknerb792e062016-12-06 21:44:41 +000014364 bool IsExplicitInstantiationDeclaration =
14365 ClassTSK == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014366 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014367 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014368 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014369 if (TSK == TSK_ExplicitInstantiationDeclaration)
14370 IsExplicitInstantiationDeclaration = true;
14371 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14372 IsExplicitInstantiationDeclaration = false;
14373 break;
14374 }
14375 }
14376
14377 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014378 DefineVTable = false;
14379 }
14380
14381 // The exception specifications for all virtual members may be needed even
14382 // if we are not providing an authoritative form of the vtable in this TU.
14383 // We may choose to emit it available_externally anyway.
14384 if (!DefineVTable) {
14385 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14386 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014387 }
14388
14389 // Mark all of the virtual members of this class as referenced, so
14390 // that we can build a vtable. Then, tell the AST consumer that a
14391 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014392 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014393 MarkVirtualMembersReferenced(Loc, Class);
14394 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014395 if (VTablesUsed[Canonical])
14396 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014397
Reid Klecknerb792e062016-12-06 21:44:41 +000014398 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14399 // no key function or the key function is inlined. Don't warn in C++ ABIs
14400 // that lack key functions, since the user won't be able to make one.
14401 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14402 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014403 const FunctionDecl *KeyFunctionDef = nullptr;
Reid Klecknerb792e062016-12-06 21:44:41 +000014404 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14405 KeyFunctionDef->isInlined())) {
14406 Diag(Class->getLocation(),
14407 ClassTSK == TSK_ExplicitInstantiationDefinition
14408 ? diag::warn_weak_template_vtable
14409 : diag::warn_weak_vtable)
14410 << Class;
14411 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014412 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014413 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014414 VTableUses.clear();
14415
Douglas Gregor97509692011-04-22 22:25:37 +000014416 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014417}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014418
Richard Smithd3b5c9082012-07-27 04:22:15 +000014419void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14420 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014421 for (const auto *I : RD->methods())
14422 if (I->isVirtual() && !I->isPure())
14423 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014424}
14425
Rafael Espindola5b334082010-03-26 00:36:59 +000014426void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14427 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014428 // Mark all functions which will appear in RD's vtable as used.
14429 CXXFinalOverriderMap FinalOverriders;
14430 RD->getFinalOverriders(FinalOverriders);
14431 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14432 E = FinalOverriders.end();
14433 I != E; ++I) {
14434 for (OverridingMethods::const_iterator OI = I->second.begin(),
14435 OE = I->second.end();
14436 OI != OE; ++OI) {
14437 assert(OI->second.size() > 0 && "no final overrider");
14438 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014439
Richard Smith4ff9ff92012-07-07 06:59:51 +000014440 // C++ [basic.def.odr]p2:
14441 // [...] A virtual member function is used if it is not pure. [...]
14442 if (!Overrider->isPure())
14443 MarkFunctionReferenced(Loc, Overrider);
14444 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014445 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014446
14447 // Only classes that have virtual bases need a VTT.
14448 if (RD->getNumVBases() == 0)
14449 return;
14450
Aaron Ballman574705e2014-03-13 15:41:46 +000014451 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014452 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014453 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014454 if (Base->getNumVBases() == 0)
14455 continue;
14456 MarkVirtualMembersReferenced(Loc, Base);
14457 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014458}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014459
14460/// SetIvarInitializers - This routine builds initialization ASTs for the
14461/// Objective-C implementation whose ivars need be initialized.
14462void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014463 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014464 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014465 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014466 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014467 CollectIvarsToConstructOrDestruct(OID, ivars);
14468 if (ivars.empty())
14469 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014470 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014471 for (unsigned i = 0; i < ivars.size(); i++) {
14472 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014473 if (Field->isInvalidDecl())
14474 continue;
14475
Alexis Hunt1d792652011-01-08 20:30:50 +000014476 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014477 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14478 InitializationKind InitKind =
14479 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014480
14481 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14482 ExprResult MemberInit =
14483 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014484 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014485 // Note, MemberInit could actually come back empty if no initialization
14486 // is required (e.g., because it would call a trivial default constructor)
14487 if (!MemberInit.get() || MemberInit.isInvalid())
14488 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014489
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014490 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014491 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14492 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014493 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014494 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014495 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014496
14497 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014498 if (const RecordType *RecordTy =
14499 Context.getBaseElementType(Field->getType())
14500 ->getAs<RecordType>()) {
14501 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014502 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014503 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014504 CheckDestructorAccess(Field->getLocation(), Destructor,
14505 PDiag(diag::err_access_dtor_ivar)
14506 << Context.getBaseElementType(Field->getType()));
14507 }
14508 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014509 }
14510 ObjCImplementation->setIvarInitializers(Context,
14511 AllToInit.data(), AllToInit.size());
14512 }
14513}
Alexis Hunt6118d662011-05-04 05:57:24 +000014514
Alexis Hunt27a761d2011-05-04 23:29:54 +000014515static
14516void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14517 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14518 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14519 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14520 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014521 if (Ctor->isInvalidDecl())
14522 return;
14523
Richard Smith802c4b72012-08-23 06:16:52 +000014524 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14525
14526 // Target may not be determinable yet, for instance if this is a dependent
14527 // call in an uninstantiated template.
14528 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014529 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014530 (void)Target->hasBody(FNTarget);
14531 Target = const_cast<CXXConstructorDecl*>(
14532 cast_or_null<CXXConstructorDecl>(FNTarget));
14533 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014534
14535 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14536 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014537 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014538
David Blaikie82e95a32014-11-19 07:49:47 +000014539 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014540 return;
14541
14542 // We know that beyond here, we aren't chaining into a cycle.
14543 if (!Target || !Target->isDelegatingConstructor() ||
14544 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014545 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014546 Current.clear();
14547 // We've hit a cycle.
14548 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14549 Current.count(TCanonical)) {
14550 // If we haven't diagnosed this cycle yet, do so now.
14551 if (!Invalid.count(TCanonical)) {
14552 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014553 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014554 << Ctor;
14555
Richard Smith802c4b72012-08-23 06:16:52 +000014556 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014557 if (TCanonical != Canonical)
14558 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14559
14560 CXXConstructorDecl *C = Target;
14561 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014562 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014563 (void)C->getTargetConstructor()->hasBody(FNTarget);
14564 assert(FNTarget && "Ctor cycle through bodiless function");
14565
Richard Smith802c4b72012-08-23 06:16:52 +000014566 C = const_cast<CXXConstructorDecl*>(
14567 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014568 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14569 }
14570 }
14571
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014572 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014573 Current.clear();
14574 } else {
14575 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14576 }
14577}
14578
14579
Alexis Hunt6118d662011-05-04 05:57:24 +000014580void Sema::CheckDelegatingCtorCycles() {
14581 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14582
Douglas Gregorbae31202011-07-27 21:57:17 +000014583 for (DelegatingCtorDeclsType::iterator
14584 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014585 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014586 I != E; ++I)
14587 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014588
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014589 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14590 CE = Invalid.end();
14591 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014592 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014593}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014594
Douglas Gregor3024f072012-04-16 07:05:22 +000014595namespace {
14596 /// \brief AST visitor that finds references to the 'this' expression.
14597 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14598 Sema &S;
14599
14600 public:
14601 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14602
14603 bool VisitCXXThisExpr(CXXThisExpr *E) {
14604 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14605 << E->isImplicit();
14606 return false;
14607 }
14608 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014609}
Douglas Gregor3024f072012-04-16 07:05:22 +000014610
14611bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14612 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14613 if (!TSInfo)
14614 return false;
14615
14616 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014617 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014618 if (!ProtoTL)
14619 return false;
14620
14621 // C++11 [expr.prim.general]p3:
14622 // [The expression this] shall not appear before the optional
14623 // cv-qualifier-seq and it shall not appear within the declaration of a
14624 // static member function (although its type and value category are defined
14625 // within a static member function as they are within a non-static member
14626 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014627 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014628 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014629 FindCXXThisExpr Finder(*this);
14630
14631 // If the return type came after the cv-qualifier-seq, check it now.
14632 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014633 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014634 return true;
14635
14636 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014637 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14638 return true;
14639
14640 return checkThisInStaticMemberFunctionAttributes(Method);
14641}
14642
14643bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14644 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14645 if (!TSInfo)
14646 return false;
14647
14648 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014649 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014650 if (!ProtoTL)
14651 return false;
14652
David Blaikie6adc78e2013-02-18 22:06:02 +000014653 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014654 FindCXXThisExpr Finder(*this);
14655
Douglas Gregor3024f072012-04-16 07:05:22 +000014656 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014657 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014658 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014659 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014660 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014661 case EST_DynamicNone:
14662 case EST_MSAny:
14663 case EST_None:
14664 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014665
Douglas Gregor3024f072012-04-16 07:05:22 +000014666 case EST_ComputedNoexcept:
14667 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14668 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014669
Douglas Gregor3024f072012-04-16 07:05:22 +000014670 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014671 for (const auto &E : Proto->exceptions()) {
14672 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014673 return true;
14674 }
14675 break;
14676 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014677
14678 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014679}
14680
14681bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14682 FindCXXThisExpr Finder(*this);
14683
14684 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014685 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014686 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014687 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014688 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014689 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014690 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014691 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014692 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014693 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014694 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014695 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014696 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014697 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014698 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014699 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014700 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014701 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014702 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014703 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014704 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014705 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014706 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014707 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014708 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014709 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014710 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014711 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014712 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014713 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014714 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014715
14716 if (Arg && !Finder.TraverseStmt(Arg))
14717 return true;
14718
14719 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14720 if (!Finder.TraverseStmt(Args[I]))
14721 return true;
14722 }
14723 }
14724
14725 return false;
14726}
14727
Richard Smith2e321552014-11-12 02:00:47 +000014728void Sema::checkExceptionSpecification(
14729 bool IsTopLevel, ExceptionSpecificationType EST,
14730 ArrayRef<ParsedType> DynamicExceptions,
14731 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14732 SmallVectorImpl<QualType> &Exceptions,
14733 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014734 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014735 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014736 if (EST == EST_Dynamic) {
14737 Exceptions.reserve(DynamicExceptions.size());
14738 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14739 // FIXME: Preserve type source info.
14740 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14741
Richard Smith2e321552014-11-12 02:00:47 +000014742 if (IsTopLevel) {
14743 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14744 collectUnexpandedParameterPacks(ET, Unexpanded);
14745 if (!Unexpanded.empty()) {
14746 DiagnoseUnexpandedParameterPacks(
14747 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14748 Unexpanded);
14749 continue;
14750 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014751 }
14752
14753 // Check that the type is valid for an exception spec, and
14754 // drop it if not.
14755 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14756 Exceptions.push_back(ET);
14757 }
Richard Smith8acb4282014-07-31 21:57:55 +000014758 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014759 return;
14760 }
Richard Smith8acb4282014-07-31 21:57:55 +000014761
Douglas Gregor433e0532012-04-16 18:27:27 +000014762 if (EST == EST_ComputedNoexcept) {
14763 // If an error occurred, there's no expression here.
14764 if (NoexceptExpr) {
14765 assert((NoexceptExpr->isTypeDependent() ||
14766 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14767 Context.BoolTy) &&
14768 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014769 if (IsTopLevel && NoexceptExpr &&
14770 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014771 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014772 return;
14773 }
Richard Smith8acb4282014-07-31 21:57:55 +000014774
Douglas Gregor433e0532012-04-16 18:27:27 +000014775 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014776 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014777 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014778 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014779 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014780 }
14781 return;
14782 }
14783}
14784
Richard Smith0b3a4622014-11-13 20:01:57 +000014785void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14786 ExceptionSpecificationType EST,
14787 SourceRange SpecificationRange,
14788 ArrayRef<ParsedType> DynamicExceptions,
14789 ArrayRef<SourceRange> DynamicExceptionRanges,
14790 Expr *NoexceptExpr) {
14791 if (!MethodD)
14792 return;
14793
14794 // Dig out the method we're referring to.
14795 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14796 MethodD = FunTmpl->getTemplatedDecl();
14797
14798 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14799 if (!Method)
14800 return;
14801
14802 // Check the exception specification.
14803 llvm::SmallVector<QualType, 4> Exceptions;
14804 FunctionProtoType::ExceptionSpecInfo ESI;
14805 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14806 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14807 ESI);
14808
14809 // Update the exception specification on the function type.
14810 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14811
14812 if (Method->isStatic())
14813 checkThisInStaticMemberFunctionExceptionSpec(Method);
14814
14815 if (Method->isVirtual()) {
14816 // Check overrides, which we previously had to delay.
14817 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14818 OEnd = Method->end_overridden_methods();
14819 O != OEnd; ++O)
14820 CheckOverridingFunctionExceptionSpec(Method, *O);
14821 }
14822}
14823
John McCall5e77d762013-04-16 07:28:30 +000014824/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14825///
14826MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14827 SourceLocation DeclStart,
14828 Declarator &D, Expr *BitWidth,
14829 InClassInitStyle InitStyle,
14830 AccessSpecifier AS,
14831 AttributeList *MSPropertyAttr) {
14832 IdentifierInfo *II = D.getIdentifier();
14833 if (!II) {
14834 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014835 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014836 }
14837 SourceLocation Loc = D.getIdentifierLoc();
14838
14839 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14840 QualType T = TInfo->getType();
14841 if (getLangOpts().CPlusPlus) {
14842 CheckExtraCXXDefaultArguments(D);
14843
14844 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14845 UPPC_DataMemberType)) {
14846 D.setInvalidType();
14847 T = Context.IntTy;
14848 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14849 }
14850 }
14851
14852 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14853
Richard Smith62f19e72016-06-25 00:15:56 +000014854 if (D.getDeclSpec().isInlineSpecified())
14855 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14856 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014857 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14858 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14859 diag::err_invalid_thread)
14860 << DeclSpec::getSpecifierName(TSCS);
14861
14862 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014863 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014864 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14865 LookupName(Previous, S);
14866 switch (Previous.getResultKind()) {
14867 case LookupResult::Found:
14868 case LookupResult::FoundUnresolvedValue:
14869 PrevDecl = Previous.getAsSingle<NamedDecl>();
14870 break;
14871
14872 case LookupResult::FoundOverloaded:
14873 PrevDecl = Previous.getRepresentativeDecl();
14874 break;
14875
14876 case LookupResult::NotFound:
14877 case LookupResult::NotFoundInCurrentInstantiation:
14878 case LookupResult::Ambiguous:
14879 break;
14880 }
14881
14882 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14883 // Maybe we will complain about the shadowed template parameter.
14884 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14885 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014886 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014887 }
14888
14889 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014890 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014891
14892 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014893 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014894 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14895 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014896 ProcessDeclAttributes(TUScope, NewPD, D);
14897 NewPD->setAccess(AS);
14898
14899 if (NewPD->isInvalidDecl())
14900 Record->setInvalidDecl();
14901
14902 if (D.getDeclSpec().isModulePrivateSpecified())
14903 NewPD->setModulePrivate();
14904
14905 if (NewPD->isInvalidDecl() && PrevDecl) {
14906 // Don't introduce NewFD into scope; there's already something
14907 // with the same name in the same scope.
14908 } else if (II) {
14909 PushOnScopeChains(NewPD, S);
14910 } else
14911 Record->addDecl(NewPD);
14912
14913 return NewPD;
14914}