blob: 0f7f0ffa75afa09a8b03f4dad69862c4950c1194 [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()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000398 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000399 SourceRange SR;
400 if (Toks->size() > 1)
401 SR = SourceRange((*Toks)[1].getLocation(),
402 Toks->back().getLocation());
403 else
404 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000405 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000406 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000407 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000408 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000409 } else if (Param->getDefaultArg()) {
410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000412 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000413 }
414 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000415 } else if (chunk.Kind != DeclaratorChunk::Paren) {
416 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000417 }
418 }
419}
420
David Majnemer502b0ed2013-06-25 23:09:30 +0000421static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424 if (!PVD->hasDefaultArg())
425 return false;
426 if (!PVD->hasInheritedDefaultArg())
427 return true;
428 }
429 return false;
430}
431
Craig Toppere4794282012-09-21 04:33:26 +0000432/// MergeCXXFunctionDecl - Merge two declarations of the same C++
433/// function, once we already know that they have the same
434/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000436bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000438 bool Invalid = false;
439
Richard Smithc7d48d12015-05-20 17:50:35 +0000440 // The declaration context corresponding to the scope is the semantic
441 // parent, unless this is a local function declaration, in which case
442 // it is that surrounding function.
443 DeclContext *ScopeDC = New->isLocalExternDecl()
444 ? New->getLexicalDeclContext()
445 : New->getDeclContext();
446
447 // Find the previous declaration for the purpose of default arguments.
448 FunctionDecl *PrevForDefaultArgs = Old;
449 for (/**/; PrevForDefaultArgs;
450 // Don't bother looking back past the latest decl if this is a local
451 // extern declaration; nothing else could work.
452 PrevForDefaultArgs = New->isLocalExternDecl()
453 ? nullptr
454 : PrevForDefaultArgs->getPreviousDecl()) {
455 // Ignore hidden declarations.
456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457 continue;
458
459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460 !New->isCXXClassMember()) {
461 // Ignore default arguments of old decl if they are not in
462 // the same scope and this is not an out-of-line definition of
463 // a member function.
464 continue;
465 }
466
467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468 // If only one of these is a local function declaration, then they are
469 // declared in different scopes, even though isDeclInScope may think
470 // they're in the same scope. (If both are local, the scope check is
471 // sufficent, and if neither is local, then they are in the same scope.)
472 continue;
473 }
474
Nico Webera6916892016-06-10 18:53:04 +0000475 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000476 break;
477 }
478
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000480 // For non-template functions, default arguments can be added in
481 // later declarations of a function in the same
482 // scope. Declarations in different scopes have completely
483 // distinct sets of default arguments. That is, declarations in
484 // inner scopes do not acquire default arguments from
485 // declarations in outer scopes, and vice versa. In a given
486 // function declaration, all parameters subsequent to a
487 // parameter with a default argument shall have default
488 // arguments supplied in this or previous declarations. A
489 // default argument shall not be redefined by a later
490 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000491 //
492 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000493 // Except for member functions of class templates, the default arguments
494 // in a member function definition that appears outside of the class
495 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000496 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000497 for (unsigned p = 0, NumParams = PrevForDefaultArgs
498 ? PrevForDefaultArgs->getNumParams()
499 : 0;
500 p < NumParams; ++p) {
501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000502 ParmVarDecl *NewParam = New->getParamDecl(p);
503
Richard Smithc7d48d12015-05-20 17:50:35 +0000504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000505 bool NewParamHasDfl = NewParam->hasDefaultArg();
506
James Molloye9430032012-03-13 08:55:35 +0000507 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000508 unsigned DiagDefaultParamID =
509 diag::err_param_default_argument_redefinition;
510
511 // MSVC accepts that default parameters be redefined for member functions
512 // of template class. The new default parameter's value is ignored.
513 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000514 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000516 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000517 // Merge the old default argument into the new parameter.
518 NewParam->setHasInheritedDefaultArg();
519 if (OldParam->hasUninstantiatedDefaultArg())
520 NewParam->setUninstantiatedDefaultArg(
521 OldParam->getUninstantiatedDefaultArg());
522 else
523 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000525 Invalid = false;
526 }
527 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000528
Francois Pichet8cb243a2011-04-10 04:58:30 +0000529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530 // hint here. Alternatively, we could walk the type-source information
531 // for NewParam to find the last source location in the type... but it
532 // isn't worth the effort right now. This is the kind of test case that
533 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000534 // int f(int);
535 // void g(int (*fp)(int) = f);
536 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000537 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000538 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000539
540 // Look for the function declaration where the default argument was
541 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000542 for (auto Older = PrevForDefaultArgs;
543 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000544 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000545 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000546 }
547
Douglas Gregorc732aba2009-09-11 18:44:32 +0000548 Diag(OldParam->getLocation(), diag::note_previous_definition)
549 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000550 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000551 // Merge the old default argument into the new parameter.
552 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000553 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000554 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000555 if (OldParam->hasUnparsedDefaultArg())
556 NewParam->setUnparsedDefaultArg();
557 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000558 NewParam->setUninstantiatedDefaultArg(
559 OldParam->getUninstantiatedDefaultArg());
560 else
John McCalle61b02b2010-05-04 01:53:42 +0000561 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000562 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000563 if (New->getDescribedFunctionTemplate()) {
564 // Paragraph 4, quoted above, only applies to non-template functions.
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_template_redecl)
567 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000568 Diag(PrevForDefaultArgs->getLocation(),
569 diag::note_template_prev_declaration)
570 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000571 } else if (New->getTemplateSpecializationKind()
572 != TSK_ImplicitInstantiation &&
573 New->getTemplateSpecializationKind() != TSK_Undeclared) {
574 // C++ [temp.expr.spec]p21:
575 // Default function arguments shall not be specified in a declaration
576 // or a definition for one of the following explicit specializations:
577 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000578 // - the explicit specialization of a member function template;
579 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000580 // template where the class template specialization to which the
581 // member function specialization belongs is implicitly
582 // instantiated.
583 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
584 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
585 << New->getDeclName()
586 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000587 } else if (New->getDeclContext()->isDependentContext()) {
588 // C++ [dcl.fct.default]p6 (DR217):
589 // Default arguments for a member function of a class template shall
590 // be specified on the initial declaration of the member function
591 // within the class template.
592 //
593 // Reading the tea leaves a bit in DR217 and its reference to DR205
594 // leads me to the conclusion that one cannot add default function
595 // arguments for an out-of-line definition of a member function of a
596 // dependent type.
597 int WhichKind = 2;
598 if (CXXRecordDecl *Record
599 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
600 if (Record->getDescribedClassTemplate())
601 WhichKind = 0;
602 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
603 WhichKind = 1;
604 else
605 WhichKind = 2;
606 }
607
608 Diag(NewParam->getLocation(),
609 diag::err_param_default_argument_member_template_redecl)
610 << WhichKind
611 << NewParam->getDefaultArgRange();
612 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000613 }
614 }
615
Richard Smith58c3cc12012-11-28 03:45:24 +0000616 // DR1344: If a default argument is added outside a class definition and that
617 // default argument makes the function a special member function, the program
618 // is ill-formed. This can only happen for constructors.
619 if (isa<CXXConstructorDecl>(New) &&
620 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
621 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
622 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
623 if (NewSM != OldSM) {
624 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
625 assert(NewParam->hasDefaultArg());
626 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
627 << NewParam->getDefaultArgRange() << NewSM;
628 Diag(Old->getLocation(), diag::note_previous_declaration);
629 }
630 }
631
David Majnemeree4f4022014-03-30 06:44:54 +0000632 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000633 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000634 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000635 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000636 if (New->isConstexpr() != Old->isConstexpr()) {
637 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
638 << New << New->isConstexpr();
639 Diag(Old->getLocation(), diag::note_previous_declaration);
640 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000641 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
642 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000643 // C++11 [dcl.fcn.spec]p4:
644 // If the definition of a function appears in a translation unit before its
645 // first declaration as inline, the program is ill-formed.
646 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
647 Diag(Def->getLocation(), diag::note_previous_definition);
648 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000649 }
650
David Majnemer502b0ed2013-06-25 23:09:30 +0000651 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000652 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000653 // the only declaration of the function or function template in the
654 // translation unit.
655 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
656 functionDeclHasDefaultArgument(Old)) {
657 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
658 Diag(Old->getLocation(), diag::note_previous_declaration);
659 Invalid = true;
660 }
661
Douglas Gregorf40863c2010-02-12 07:32:17 +0000662 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000663 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000664
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000665 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000666}
667
Richard Smith7873de02016-08-11 22:25:46 +0000668NamedDecl *
669Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
670 MultiTemplateParamsArg TemplateParamLists) {
671 assert(D.isDecompositionDeclarator());
672 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
673
674 // The syntax only allows a decomposition declarator as a simple-declaration
675 // or a for-range-declaration, but we parse it in more cases than that.
676 if (!D.mayHaveDecompositionDeclarator()) {
677 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
678 << Decomp.getSourceRange();
679 return nullptr;
680 }
681
682 if (!TemplateParamLists.empty()) {
683 // FIXME: There's no rule against this, but there are also no rules that
684 // would actually make it usable, so we reject it for now.
685 Diag(TemplateParamLists.front()->getTemplateLoc(),
686 diag::err_decomp_decl_template);
687 return nullptr;
688 }
689
690 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
691 ? diag::warn_cxx14_compat_decomp_decl
692 : diag::ext_decomp_decl)
693 << Decomp.getSourceRange();
694
695 // The semantic context is always just the current context.
696 DeclContext *const DC = CurContext;
697
698 // C++1z [dcl.dcl]/8:
699 // The decl-specifier-seq shall contain only the type-specifier auto
700 // and cv-qualifiers.
701 auto &DS = D.getDeclSpec();
702 {
703 SmallVector<StringRef, 8> BadSpecifiers;
704 SmallVector<SourceLocation, 8> BadSpecifierLocs;
705 if (auto SCS = DS.getStorageClassSpec()) {
706 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
707 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
708 }
709 if (auto TSCS = DS.getThreadStorageClassSpec()) {
710 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
711 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
712 }
713 if (DS.isConstexprSpecified()) {
714 BadSpecifiers.push_back("constexpr");
715 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
716 }
717 if (DS.isInlineSpecified()) {
718 BadSpecifiers.push_back("inline");
719 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
720 }
721 if (!BadSpecifiers.empty()) {
722 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
723 Err << (int)BadSpecifiers.size()
724 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
725 // Don't add FixItHints to remove the specifiers; we do still respect
726 // them when building the underlying variable.
727 for (auto Loc : BadSpecifierLocs)
728 Err << SourceRange(Loc, Loc);
729 }
730 // We can't recover from it being declared as a typedef.
731 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
732 return nullptr;
733 }
734
735 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
736 QualType R = TInfo->getType();
737
738 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
739 UPPC_DeclarationType))
740 D.setInvalidType();
741
742 // The syntax only allows a single ref-qualifier prior to the decomposition
743 // declarator. No other declarator chunks are permitted. Also check the type
744 // specifier here.
745 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
746 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
747 (D.getNumTypeObjects() == 1 &&
748 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
749 Diag(Decomp.getLSquareLoc(),
750 (D.hasGroupingParens() ||
751 (D.getNumTypeObjects() &&
752 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
753 ? diag::err_decomp_decl_parens
754 : diag::err_decomp_decl_type)
755 << R;
756
757 // In most cases, there's no actual problem with an explicitly-specified
758 // type, but a function type won't work here, and ActOnVariableDeclarator
759 // shouldn't be called for such a type.
760 if (R->isFunctionType())
761 D.setInvalidType();
762 }
763
764 // Build the BindingDecls.
765 SmallVector<BindingDecl*, 8> Bindings;
766
767 // Build the BindingDecls.
768 for (auto &B : D.getDecompositionDeclarator().bindings()) {
769 // Check for name conflicts.
770 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
771 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
772 ForRedeclaration);
773 LookupName(Previous, S,
774 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
775
776 // It's not permitted to shadow a template parameter name.
777 if (Previous.isSingleResult() &&
778 Previous.getFoundDecl()->isTemplateParameter()) {
779 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
780 Previous.getFoundDecl());
781 Previous.clear();
782 }
783
784 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
785 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
786 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
787 /*AllowInlineNamespace*/false);
788 if (!Previous.empty()) {
789 auto *Old = Previous.getRepresentativeDecl();
790 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
791 Diag(Old->getLocation(), diag::note_previous_definition);
792 }
793
Richard Smith32cb8c92016-08-12 00:53:41 +0000794 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000795 PushOnScopeChains(BD, S, true);
796 Bindings.push_back(BD);
797 ParsingInitForAutoVars.insert(BD);
798 }
799
800 // There are no prior lookup results for the variable itself, because it
801 // is unnamed.
802 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
803 Decomp.getLSquareLoc());
804 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
805
806 // Build the variable that holds the non-decomposed object.
807 bool AddToScope = true;
808 NamedDecl *New =
809 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
810 MultiTemplateParamsArg(), AddToScope, Bindings);
811 CurContext->addHiddenDecl(New);
812
813 if (isInOpenMPDeclareTargetContext())
814 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
815
816 return New;
817}
818
819static bool checkSimpleDecomposition(
820 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
821 QualType DecompType, llvm::APSInt NumElems, QualType ElemType,
822 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
823 if ((int64_t)Bindings.size() != NumElems) {
824 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
825 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
826 << (NumElems < Bindings.size());
827 return true;
828 }
829
830 unsigned I = 0;
831 for (auto *B : Bindings) {
832 SourceLocation Loc = B->getLocation();
833 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
834 if (E.isInvalid())
835 return true;
836 E = GetInit(Loc, E.get(), I++);
837 if (E.isInvalid())
838 return true;
839 B->setBinding(ElemType, E.get());
840 }
841
842 return false;
843}
844
845static bool checkArrayLikeDecomposition(Sema &S,
846 ArrayRef<BindingDecl *> Bindings,
847 ValueDecl *Src, QualType DecompType,
848 llvm::APSInt NumElems,
849 QualType ElemType) {
850 return checkSimpleDecomposition(
851 S, Bindings, Src, DecompType, NumElems, ElemType,
852 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
853 ExprResult E = S.ActOnIntegerConstant(Loc, I);
854 if (E.isInvalid())
855 return ExprError();
856 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
857 });
858}
859
860static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
861 ValueDecl *Src, QualType DecompType,
862 const ConstantArrayType *CAT) {
863 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
864 llvm::APSInt(CAT->getSize()),
865 CAT->getElementType());
866}
867
868static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
869 ValueDecl *Src, QualType DecompType,
870 const VectorType *VT) {
871 return checkArrayLikeDecomposition(
872 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
873 S.Context.getQualifiedType(VT->getElementType(),
874 DecompType.getQualifiers()));
875}
876
877static bool checkComplexDecomposition(Sema &S,
878 ArrayRef<BindingDecl *> Bindings,
879 ValueDecl *Src, QualType DecompType,
880 const ComplexType *CT) {
881 return checkSimpleDecomposition(
882 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
883 S.Context.getQualifiedType(CT->getElementType(),
884 DecompType.getQualifiers()),
885 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
886 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
887 });
888}
889
890static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
891 TemplateArgumentListInfo &Args) {
892 SmallString<128> SS;
893 llvm::raw_svector_ostream OS(SS);
894 bool First = true;
895 for (auto &Arg : Args.arguments()) {
896 if (!First)
897 OS << ", ";
898 Arg.getArgument().print(PrintingPolicy, OS);
899 First = false;
900 }
901 return OS.str();
902}
903
904static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
905 SourceLocation Loc, StringRef Trait,
906 TemplateArgumentListInfo &Args,
907 unsigned DiagID) {
908 auto DiagnoseMissing = [&] {
909 if (DiagID)
910 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
911 Args);
912 return true;
913 };
914
915 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
916 NamespaceDecl *Std = S.getStdNamespace();
917 if (!Std)
918 return DiagnoseMissing();
919
920 // Look up the trait itself, within namespace std. We can diagnose various
921 // problems with this lookup even if we've been asked to not diagnose a
922 // missing specialization, because this can only fail if the user has been
923 // declaring their own names in namespace std or we don't support the
924 // standard library implementation in use.
925 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
926 Loc, Sema::LookupOrdinaryName);
927 if (!S.LookupQualifiedName(Result, Std))
928 return DiagnoseMissing();
929 if (Result.isAmbiguous())
930 return true;
931
932 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
933 if (!TraitTD) {
934 Result.suppressDiagnostics();
935 NamedDecl *Found = *Result.begin();
936 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
937 S.Diag(Found->getLocation(), diag::note_declared_at);
938 return true;
939 }
940
941 // Build the template-id.
942 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
943 if (TraitTy.isNull())
944 return true;
945 if (!S.isCompleteType(Loc, TraitTy)) {
946 if (DiagID)
947 S.RequireCompleteType(
948 Loc, TraitTy, DiagID,
949 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
950 return true;
951 }
952
953 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
954 assert(RD && "specialization of class template is not a class?");
955
956 // Look up the member of the trait type.
957 S.LookupQualifiedName(TraitMemberLookup, RD);
958 return TraitMemberLookup.isAmbiguous();
959}
960
961static TemplateArgumentLoc
962getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
963 uint64_t I) {
964 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
965 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
966}
967
968static TemplateArgumentLoc
969getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
970 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
971}
972
973namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
974
975static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
976 llvm::APSInt &Size) {
977 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
978
979 DeclarationName Value = S.PP.getIdentifierInfo("value");
980 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
981
982 // Form template argument list for tuple_size<T>.
983 TemplateArgumentListInfo Args(Loc, Loc);
984 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
985
986 // If there's no tuple_size specialization, it's not tuple-like.
987 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
988 return IsTupleLike::NotTupleLike;
989
990 // FIXME: According to the standard, we're not supposed to diagnose if any
991 // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
992 // results in an error), but this is subject to a pending CWG issue / NB
993 // comment, which says we do diagnose if tuple_size<T> is complete but
994 // tuple_size<T>::value is not an ICE.
995
996 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
997 LookupResult &R;
998 TemplateArgumentListInfo &Args;
999 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1000 : R(R), Args(Args) {}
1001 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1002 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1003 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1004 }
1005 } Diagnoser(R, Args);
1006
1007 if (R.empty()) {
1008 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1009 return IsTupleLike::Error;
1010 }
1011
1012 ExprResult E =
1013 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1014 if (E.isInvalid())
1015 return IsTupleLike::Error;
1016
1017 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1018 if (E.isInvalid())
1019 return IsTupleLike::Error;
1020
1021 return IsTupleLike::TupleLike;
1022}
1023
1024/// \return std::tuple_element<I, T>::type.
1025static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1026 unsigned I, QualType T) {
1027 // Form template argument list for tuple_element<I, T>.
1028 TemplateArgumentListInfo Args(Loc, Loc);
1029 Args.addArgument(
1030 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1031 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1032
1033 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1034 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1035 if (lookupStdTypeTraitMember(
1036 S, R, Loc, "tuple_element", Args,
1037 diag::err_decomp_decl_std_tuple_element_not_specialized))
1038 return QualType();
1039
1040 auto *TD = R.getAsSingle<TypeDecl>();
1041 if (!TD) {
1042 R.suppressDiagnostics();
1043 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1044 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1045 if (!R.empty())
1046 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1047 return QualType();
1048 }
1049
1050 return S.Context.getTypeDeclType(TD);
1051}
1052
1053namespace {
1054struct BindingDiagnosticTrap {
1055 Sema &S;
1056 DiagnosticErrorTrap Trap;
1057 BindingDecl *BD;
1058
1059 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1060 : S(S), Trap(S.Diags), BD(BD) {}
1061 ~BindingDiagnosticTrap() {
1062 if (Trap.hasErrorOccurred())
1063 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1064 }
1065};
1066}
1067
Richard Smith3997b1b2016-08-12 01:55:21 +00001068static bool checkTupleLikeDecomposition(Sema &S,
1069 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001070 VarDecl *Src, QualType DecompType,
Richard Smith3997b1b2016-08-12 01:55:21 +00001071 llvm::APSInt TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001072 if ((int64_t)Bindings.size() != TupleSize) {
1073 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1074 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1075 << (TupleSize < Bindings.size());
1076 return true;
1077 }
1078
1079 if (Bindings.empty())
1080 return false;
1081
1082 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1083
1084 // [dcl.decomp]p3:
1085 // The unqualified-id get is looked up in the scope of E by class member
1086 // access lookup
1087 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1088 bool UseMemberGet = false;
1089 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1090 if (auto *RD = DecompType->getAsCXXRecordDecl())
1091 S.LookupQualifiedName(MemberGet, RD);
1092 if (MemberGet.isAmbiguous())
1093 return true;
1094 UseMemberGet = !MemberGet.empty();
1095 S.FilterAcceptableTemplateNames(MemberGet);
1096 }
1097
1098 unsigned I = 0;
1099 for (auto *B : Bindings) {
1100 BindingDiagnosticTrap Trap(S, B);
1101 SourceLocation Loc = B->getLocation();
1102
1103 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1104 if (E.isInvalid())
1105 return true;
1106
1107 // e is an lvalue if the type of the entity is an lvalue reference and
1108 // an xvalue otherwise
1109 if (!Src->getType()->isLValueReferenceType())
1110 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1111 E.get(), nullptr, VK_XValue);
1112
1113 TemplateArgumentListInfo Args(Loc, Loc);
1114 Args.addArgument(
1115 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1116
1117 if (UseMemberGet) {
1118 // if [lookup of member get] finds at least one declaration, the
1119 // initializer is e.get<i-1>().
1120 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1121 CXXScopeSpec(), SourceLocation(), nullptr,
1122 MemberGet, &Args, nullptr);
1123 if (E.isInvalid())
1124 return true;
1125
1126 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1127 } else {
1128 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1129 // in the associated namespaces.
1130 Expr *Get = UnresolvedLookupExpr::Create(
1131 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1132 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1133 UnresolvedSetIterator(), UnresolvedSetIterator());
1134
1135 Expr *Arg = E.get();
1136 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1137 }
1138 if (E.isInvalid())
1139 return true;
1140 Expr *Init = E.get();
1141
1142 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1143 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1144 if (T.isNull())
1145 return true;
1146
1147 // each vi is a variable of type "reference to T" initialized with the
1148 // initializer, where the reference is an lvalue reference if the
1149 // initializer is an lvalue and an rvalue reference otherwise
1150 QualType RefType =
1151 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1152 if (RefType.isNull())
1153 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001154 auto *RefVD = VarDecl::Create(
1155 S.Context, Src->getDeclContext(), Loc, Loc,
1156 B->getDeclName().getAsIdentifierInfo(), RefType,
1157 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1158 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1159 RefVD->setTSCSpec(Src->getTSCSpec());
1160 RefVD->setImplicit();
1161 if (Src->isInlineSpecified())
1162 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001163 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001164
Richard Smith97fcf4b2016-08-14 23:15:52 +00001165 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001166 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1167 InitializationSequence Seq(S, Entity, Kind, Init);
1168 E = Seq.Perform(S, Entity, Kind, Init);
1169 if (E.isInvalid())
1170 return true;
Richard Smithda383632016-08-15 01:33:41 +00001171 E = S.ActOnFinishFullExpr(E.get(), Loc);
1172 if (E.isInvalid())
1173 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001174 RefVD->setInit(E.get());
1175 RefVD->checkInitIsICE();
1176
Richard Smith97fcf4b2016-08-14 23:15:52 +00001177 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1178 DeclarationNameInfo(B->getDeclName(), Loc),
1179 RefVD);
1180 if (E.isInvalid())
1181 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001182
1183 B->setBinding(T, E.get());
1184 I++;
1185 }
1186
1187 return false;
1188}
1189
1190/// Find the base class to decompose in a built-in decomposition of a class type.
1191/// This base class search is, unfortunately, not quite like any other that we
1192/// perform anywhere else in C++.
1193static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1194 SourceLocation Loc,
1195 const CXXRecordDecl *RD,
1196 CXXCastPath &BasePath) {
1197 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1198 CXXBasePath &Path) {
1199 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1200 };
1201
1202 const CXXRecordDecl *ClassWithFields = nullptr;
1203 if (RD->hasDirectFields())
1204 // [dcl.decomp]p4:
1205 // Otherwise, all of E's non-static data members shall be public direct
1206 // members of E ...
1207 ClassWithFields = RD;
1208 else {
1209 // ... or of ...
1210 CXXBasePaths Paths;
1211 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1212 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1213 // If no classes have fields, just decompose RD itself. (This will work
1214 // if and only if zero bindings were provided.)
1215 return RD;
1216 }
1217
1218 CXXBasePath *BestPath = nullptr;
1219 for (auto &P : Paths) {
1220 if (!BestPath)
1221 BestPath = &P;
1222 else if (!S.Context.hasSameType(P.back().Base->getType(),
1223 BestPath->back().Base->getType())) {
1224 // ... the same ...
1225 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1226 << false << RD << BestPath->back().Base->getType()
1227 << P.back().Base->getType();
1228 return nullptr;
1229 } else if (P.Access < BestPath->Access) {
1230 BestPath = &P;
1231 }
1232 }
1233
1234 // ... unambiguous ...
1235 QualType BaseType = BestPath->back().Base->getType();
1236 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1237 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1238 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1239 return nullptr;
1240 }
1241
1242 // ... public base class of E.
1243 if (BestPath->Access != AS_public) {
1244 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1245 << RD << BaseType;
1246 for (auto &BS : *BestPath) {
1247 if (BS.Base->getAccessSpecifier() != AS_public) {
1248 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1249 << (BS.Base->getAccessSpecifier() == AS_protected)
1250 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1251 break;
1252 }
1253 }
1254 return nullptr;
1255 }
1256
1257 ClassWithFields = BaseType->getAsCXXRecordDecl();
1258 S.BuildBasePathArray(Paths, BasePath);
1259 }
1260
1261 // The above search did not check whether the selected class itself has base
1262 // classes with fields, so check that now.
1263 CXXBasePaths Paths;
1264 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1265 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1266 << (ClassWithFields == RD) << RD << ClassWithFields
1267 << Paths.front().back().Base->getType();
1268 return nullptr;
1269 }
1270
1271 return ClassWithFields;
1272}
1273
1274static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1275 ValueDecl *Src, QualType DecompType,
1276 const CXXRecordDecl *RD) {
1277 CXXCastPath BasePath;
1278 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1279 if (!RD)
1280 return true;
1281 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1282 DecompType.getQualifiers());
1283
1284 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1285 unsigned NumFields = std::distance(RD->field_begin(), RD->field_end());
1286 assert(Bindings.size() != NumFields);
1287 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1288 << DecompType << (unsigned)Bindings.size() << NumFields
1289 << (NumFields < Bindings.size());
1290 return true;
1291 };
1292
1293 // all of E's non-static data members shall be public [...] members,
1294 // E shall not have an anonymous union member, ...
1295 unsigned I = 0;
1296 for (auto *FD : RD->fields()) {
1297 if (FD->isUnnamedBitfield())
1298 continue;
1299
1300 if (FD->isAnonymousStructOrUnion()) {
1301 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1302 << DecompType << FD->getType()->isUnionType();
1303 S.Diag(FD->getLocation(), diag::note_declared_at);
1304 return true;
1305 }
1306
1307 // We have a real field to bind.
1308 if (I >= Bindings.size())
1309 return DiagnoseBadNumberOfBindings();
1310 auto *B = Bindings[I++];
1311
1312 SourceLocation Loc = B->getLocation();
1313 if (FD->getAccess() != AS_public) {
1314 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1315
1316 // Determine whether the access specifier was explicit.
1317 bool Implicit = true;
1318 for (const auto *D : RD->decls()) {
1319 if (declaresSameEntity(D, FD))
1320 break;
1321 if (isa<AccessSpecDecl>(D)) {
1322 Implicit = false;
1323 break;
1324 }
1325 }
1326
1327 S.Diag(FD->getLocation(), diag::note_access_natural)
1328 << (FD->getAccess() == AS_protected) << Implicit;
1329 return true;
1330 }
1331
1332 // Initialize the binding to Src.FD.
1333 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1334 if (E.isInvalid())
1335 return true;
1336 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1337 VK_LValue, &BasePath);
1338 if (E.isInvalid())
1339 return true;
1340 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1341 CXXScopeSpec(), FD,
1342 DeclAccessPair::make(FD, FD->getAccess()),
1343 DeclarationNameInfo(FD->getDeclName(), Loc));
1344 if (E.isInvalid())
1345 return true;
1346
1347 // If the type of the member is T, the referenced type is cv T, where cv is
1348 // the cv-qualification of the decomposition expression.
1349 //
1350 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1351 // 'const' to the type of the field.
1352 Qualifiers Q = DecompType.getQualifiers();
1353 if (FD->isMutable())
1354 Q.removeConst();
1355 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1356 }
1357
1358 if (I != Bindings.size())
1359 return DiagnoseBadNumberOfBindings();
1360
1361 return false;
1362}
1363
Richard Smith3997b1b2016-08-12 01:55:21 +00001364void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001365 QualType DecompType = DD->getType();
1366
1367 // If the type of the decomposition is dependent, then so is the type of
1368 // each binding.
1369 if (DecompType->isDependentType()) {
1370 for (auto *B : DD->bindings())
1371 B->setType(Context.DependentTy);
1372 return;
1373 }
1374
1375 DecompType = DecompType.getNonReferenceType();
1376 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1377
1378 // C++1z [dcl.decomp]/2:
1379 // If E is an array type [...]
1380 // As an extension, we also support decomposition of built-in complex and
1381 // vector types.
1382 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1383 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1384 DD->setInvalidDecl();
1385 return;
1386 }
1387 if (auto *VT = DecompType->getAs<VectorType>()) {
1388 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1389 DD->setInvalidDecl();
1390 return;
1391 }
1392 if (auto *CT = DecompType->getAs<ComplexType>()) {
1393 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1394 DD->setInvalidDecl();
1395 return;
1396 }
1397
1398 // C++1z [dcl.decomp]/3:
1399 // if the expression std::tuple_size<E>::value is a well-formed integral
1400 // constant expression, [...]
1401 llvm::APSInt TupleSize(32);
1402 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1403 case IsTupleLike::Error:
1404 DD->setInvalidDecl();
1405 return;
1406
1407 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001408 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001409 DD->setInvalidDecl();
1410 return;
1411
1412 case IsTupleLike::NotTupleLike:
1413 break;
1414 }
1415
1416 // C++1z [dcl.dcl]/8:
1417 // [E shall be of array or non-union class type]
1418 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1419 if (!RD || RD->isUnion()) {
1420 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1421 << DD << !RD << DecompType;
1422 DD->setInvalidDecl();
1423 return;
1424 }
1425
1426 // C++1z [dcl.decomp]/4:
1427 // all of E's non-static data members shall be [...] direct members of
1428 // E or of the same unambiguous public base class of E, ...
1429 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1430 DD->setInvalidDecl();
1431}
1432
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001433/// \brief Merge the exception specifications of two variable declarations.
1434///
1435/// This is called when there's a redeclaration of a VarDecl. The function
1436/// checks if the redeclaration might have an exception specification and
1437/// validates compatibility and merges the specs if necessary.
1438void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1439 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001440 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001441 return;
1442
1443 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1444 "Should only be called if types are otherwise the same.");
1445
1446 QualType NewType = New->getType();
1447 QualType OldType = Old->getType();
1448
1449 // We're only interested in pointers and references to functions, as well
1450 // as pointers to member functions.
1451 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1452 NewType = R->getPointeeType();
1453 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1454 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1455 NewType = P->getPointeeType();
1456 OldType = OldType->getAs<PointerType>()->getPointeeType();
1457 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1458 NewType = M->getPointeeType();
1459 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1460 }
1461
1462 if (!NewType->isFunctionProtoType())
1463 return;
1464
1465 // There's lots of special cases for functions. For function pointers, system
1466 // libraries are hopefully not as broken so that we don't need these
1467 // workarounds.
1468 if (CheckEquivalentExceptionSpec(
1469 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1470 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1471 New->setInvalidDecl();
1472 }
1473}
1474
Chris Lattner199abbc2008-04-08 05:04:30 +00001475/// CheckCXXDefaultArguments - Verify that the default arguments for a
1476/// function declaration are well-formed according to C++
1477/// [dcl.fct.default].
1478void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1479 unsigned NumParams = FD->getNumParams();
1480 unsigned p;
1481
1482 // Find first parameter with a default argument
1483 for (p = 0; p < NumParams; ++p) {
1484 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001485 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001486 break;
1487 }
1488
Benjamin Kramerfe257592015-03-27 13:58:41 +00001489 // C++11 [dcl.fct.default]p4:
1490 // In a given function declaration, each parameter subsequent to a parameter
1491 // with a default argument shall have a default argument supplied in this or
1492 // a previous declaration or shall be a function parameter pack. A default
1493 // argument shall not be redefined by a later declaration (not even to the
1494 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001495 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001496 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001497 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001498 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001499 if (Param->isInvalidDecl())
1500 /* We already complained about this parameter. */;
1501 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001502 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001503 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001504 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001505 else
Mike Stump11289f42009-09-09 15:08:12 +00001506 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001507 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Chris Lattner199abbc2008-04-08 05:04:30 +00001509 LastMissingDefaultArg = p;
1510 }
1511 }
1512
1513 if (LastMissingDefaultArg > 0) {
1514 // Some default arguments were missing. Clear out all of the
1515 // default arguments up to (and including) the last missing
1516 // default argument, so that we leave the function parameters
1517 // in a semantically valid state.
1518 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1519 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001520 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001521 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001522 }
1523 }
1524 }
1525}
Douglas Gregor556877c2008-04-13 21:30:24 +00001526
Richard Smitheb3c10c2011-10-01 02:31:28 +00001527// CheckConstexprParameterTypes - Check whether a function's parameter types
1528// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001529// diagnostic and return false.
1530static bool CheckConstexprParameterTypes(Sema &SemaRef,
1531 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001532 unsigned ArgIndex = 0;
1533 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001534 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1535 e = FT->param_type_end();
1536 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001537 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1538 SourceLocation ParamLoc = PD->getLocation();
1539 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001540 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001541 diag::err_constexpr_non_literal_param,
1542 ArgIndex+1, PD->getSourceRange(),
1543 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001544 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001545 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001546 return true;
1547}
1548
1549/// \brief Get diagnostic %select index for tag kind for
1550/// record diagnostic message.
1551/// WARNING: Indexes apply to particular diagnostics only!
1552///
1553/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001554static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001555 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001556 case TTK_Struct: return 0;
1557 case TTK_Interface: return 1;
1558 case TTK_Class: return 2;
1559 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001560 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001561}
1562
1563// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1564// the requirements of a constexpr function definition or a constexpr
1565// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001566// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001567//
Richard Smith3607ffe2012-02-13 03:54:03 +00001568// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1569bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001570 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1571 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001572 // C++11 [dcl.constexpr]p4:
1573 // The definition of a constexpr constructor shall satisfy the following
1574 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001575 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001576 const CXXRecordDecl *RD = MD->getParent();
1577 if (RD->getNumVBases()) {
1578 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1579 << isa<CXXConstructorDecl>(NewFD)
1580 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001581 for (const auto &I : RD->vbases())
1582 Diag(I.getLocStart(),
1583 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001584 return false;
1585 }
Richard Smith7971b692012-01-13 04:54:00 +00001586 }
1587
1588 if (!isa<CXXConstructorDecl>(NewFD)) {
1589 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001590 // The definition of a constexpr function shall satisfy the following
1591 // constraints:
1592 // - it shall not be virtual;
1593 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1594 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001595 Method = Method->getCanonicalDecl();
1596 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001597
Richard Smith3607ffe2012-02-13 03:54:03 +00001598 // If it's not obvious why this function is virtual, find an overridden
1599 // function which uses the 'virtual' keyword.
1600 const CXXMethodDecl *WrittenVirtual = Method;
1601 while (!WrittenVirtual->isVirtualAsWritten())
1602 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1603 if (WrittenVirtual != Method)
1604 Diag(WrittenVirtual->getLocation(),
1605 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001606 return false;
1607 }
1608
1609 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001610 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001611 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001612 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001613 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001614 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001615 }
1616
Richard Smith7971b692012-01-13 04:54:00 +00001617 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001618 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001619 return false;
1620
Richard Smitheb3c10c2011-10-01 02:31:28 +00001621 return true;
1622}
1623
1624/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001625/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001626///
Richard Smithd9f663b2013-04-22 15:31:51 +00001627/// \return true if the body is OK (maybe only as an extension), false if we
1628/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001629static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001630 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1631 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001632 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1633 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001634 for (const auto *DclIt : DS->decls()) {
1635 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001636 case Decl::StaticAssert:
1637 case Decl::Using:
1638 case Decl::UsingShadow:
1639 case Decl::UsingDirective:
1640 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001641 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001642 // - static_assert-declarations
1643 // - using-declarations,
1644 // - using-directives,
1645 continue;
1646
1647 case Decl::Typedef:
1648 case Decl::TypeAlias: {
1649 // - typedef declarations and alias-declarations that do not define
1650 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001651 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001652 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1653 // Don't allow variably-modified types in constexpr functions.
1654 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1655 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1656 << TL.getSourceRange() << TL.getType()
1657 << isa<CXXConstructorDecl>(Dcl);
1658 return false;
1659 }
1660 continue;
1661 }
1662
1663 case Decl::Enum:
1664 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001665 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001666 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001667 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001668 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001669 ? diag::warn_cxx11_compat_constexpr_type_definition
1670 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001671 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001672 continue;
1673
Richard Smithd9f663b2013-04-22 15:31:51 +00001674 case Decl::EnumConstant:
1675 case Decl::IndirectField:
1676 case Decl::ParmVar:
1677 // These can only appear with other declarations which are banned in
1678 // C++11 and permitted in C++1y, so ignore them.
1679 continue;
1680
Richard Smithdca60b42016-08-12 00:39:32 +00001681 case Decl::Var:
1682 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001683 // C++1y [dcl.constexpr]p3 allows anything except:
1684 // a definition of a variable of non-literal type or of static or
1685 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001686 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001687 if (VD->isThisDeclarationADefinition()) {
1688 if (VD->isStaticLocal()) {
1689 SemaRef.Diag(VD->getLocation(),
1690 diag::err_constexpr_local_var_static)
1691 << isa<CXXConstructorDecl>(Dcl)
1692 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1693 return false;
1694 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001695 if (!VD->getType()->isDependentType() &&
1696 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001697 VD->getLocation(), VD->getType(),
1698 diag::err_constexpr_local_var_non_literal_type,
1699 isa<CXXConstructorDecl>(Dcl)))
1700 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001701 if (!VD->getType()->isDependentType() &&
1702 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001703 SemaRef.Diag(VD->getLocation(),
1704 diag::err_constexpr_local_var_no_init)
1705 << isa<CXXConstructorDecl>(Dcl);
1706 return false;
1707 }
1708 }
1709 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001710 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001711 ? diag::warn_cxx11_compat_constexpr_local_var
1712 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001713 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001714 continue;
1715 }
1716
1717 case Decl::NamespaceAlias:
1718 case Decl::Function:
1719 // These are disallowed in C++11 and permitted in C++1y. Allow them
1720 // everywhere as an extension.
1721 if (!Cxx1yLoc.isValid())
1722 Cxx1yLoc = DS->getLocStart();
1723 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001724
1725 default:
1726 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1727 << isa<CXXConstructorDecl>(Dcl);
1728 return false;
1729 }
1730 }
1731
1732 return true;
1733}
1734
1735/// Check that the given field is initialized within a constexpr constructor.
1736///
1737/// \param Dcl The constexpr constructor being checked.
1738/// \param Field The field being checked. This may be a member of an anonymous
1739/// struct or union nested within the class being checked.
1740/// \param Inits All declarations, including anonymous struct/union members and
1741/// indirect members, for which any initialization was provided.
1742/// \param Diagnosed Set to true if an error is produced.
1743static void CheckConstexprCtorInitializer(Sema &SemaRef,
1744 const FunctionDecl *Dcl,
1745 FieldDecl *Field,
1746 llvm::SmallSet<Decl*, 16> &Inits,
1747 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001748 if (Field->isInvalidDecl())
1749 return;
1750
Douglas Gregor556e5862011-10-10 17:22:13 +00001751 if (Field->isUnnamedBitfield())
1752 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001753
Richard Smithab44d5b2013-12-10 08:25:00 +00001754 // Anonymous unions with no variant members and empty anonymous structs do not
1755 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1756 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001757 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001758 (Field->getType()->isUnionType()
1759 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1760 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001761 return;
1762
Richard Smitheb3c10c2011-10-01 02:31:28 +00001763 if (!Inits.count(Field)) {
1764 if (!Diagnosed) {
1765 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1766 Diagnosed = true;
1767 }
1768 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1769 } else if (Field->isAnonymousStructOrUnion()) {
1770 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001771 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001772 // If an anonymous union contains an anonymous struct of which any member
1773 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001774 if (!RD->isUnion() || Inits.count(I))
1775 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001776 }
1777}
1778
Richard Smithd9f663b2013-04-22 15:31:51 +00001779/// Check the provided statement is allowed in a constexpr function
1780/// definition.
1781static bool
1782CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001783 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001784 SourceLocation &Cxx1yLoc) {
1785 // - its function-body shall be [...] a compound-statement that contains only
1786 switch (S->getStmtClass()) {
1787 case Stmt::NullStmtClass:
1788 // - null statements,
1789 return true;
1790
1791 case Stmt::DeclStmtClass:
1792 // - static_assert-declarations
1793 // - using-declarations,
1794 // - using-directives,
1795 // - typedef declarations and alias-declarations that do not define
1796 // classes or enumerations,
1797 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1798 return false;
1799 return true;
1800
1801 case Stmt::ReturnStmtClass:
1802 // - and exactly one return statement;
1803 if (isa<CXXConstructorDecl>(Dcl)) {
1804 // C++1y allows return statements in constexpr constructors.
1805 if (!Cxx1yLoc.isValid())
1806 Cxx1yLoc = S->getLocStart();
1807 return true;
1808 }
1809
1810 ReturnStmts.push_back(S->getLocStart());
1811 return true;
1812
1813 case Stmt::CompoundStmtClass: {
1814 // C++1y allows compound-statements.
1815 if (!Cxx1yLoc.isValid())
1816 Cxx1yLoc = S->getLocStart();
1817
1818 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001819 for (auto *BodyIt : CompStmt->body()) {
1820 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001821 Cxx1yLoc))
1822 return false;
1823 }
1824 return true;
1825 }
1826
1827 case Stmt::AttributedStmtClass:
1828 if (!Cxx1yLoc.isValid())
1829 Cxx1yLoc = S->getLocStart();
1830 return true;
1831
1832 case Stmt::IfStmtClass: {
1833 // C++1y allows if-statements.
1834 if (!Cxx1yLoc.isValid())
1835 Cxx1yLoc = S->getLocStart();
1836
1837 IfStmt *If = cast<IfStmt>(S);
1838 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1839 Cxx1yLoc))
1840 return false;
1841 if (If->getElse() &&
1842 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1843 Cxx1yLoc))
1844 return false;
1845 return true;
1846 }
1847
1848 case Stmt::WhileStmtClass:
1849 case Stmt::DoStmtClass:
1850 case Stmt::ForStmtClass:
1851 case Stmt::CXXForRangeStmtClass:
1852 case Stmt::ContinueStmtClass:
1853 // C++1y allows all of these. We don't allow them as extensions in C++11,
1854 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001855 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001856 break;
1857 if (!Cxx1yLoc.isValid())
1858 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001859 for (Stmt *SubStmt : S->children())
1860 if (SubStmt &&
1861 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001862 Cxx1yLoc))
1863 return false;
1864 return true;
1865
1866 case Stmt::SwitchStmtClass:
1867 case Stmt::CaseStmtClass:
1868 case Stmt::DefaultStmtClass:
1869 case Stmt::BreakStmtClass:
1870 // C++1y allows switch-statements, and since they don't need variable
1871 // mutation, we can reasonably allow them in C++11 as an extension.
1872 if (!Cxx1yLoc.isValid())
1873 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001874 for (Stmt *SubStmt : S->children())
1875 if (SubStmt &&
1876 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001877 Cxx1yLoc))
1878 return false;
1879 return true;
1880
1881 default:
1882 if (!isa<Expr>(S))
1883 break;
1884
1885 // C++1y allows expression-statements.
1886 if (!Cxx1yLoc.isValid())
1887 Cxx1yLoc = S->getLocStart();
1888 return true;
1889 }
1890
1891 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1892 << isa<CXXConstructorDecl>(Dcl);
1893 return false;
1894}
1895
Richard Smitheb3c10c2011-10-01 02:31:28 +00001896/// Check the body for the given constexpr function declaration only contains
1897/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1898///
1899/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001900bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001901 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001902 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001903 // The definition of a constexpr function shall satisfy the following
1904 // constraints: [...]
1905 // - its function-body shall be = delete, = default, or a
1906 // compound-statement
1907 //
Richard Smith74388b42012-02-04 00:33:54 +00001908 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001909 // In the definition of a constexpr constructor, [...]
1910 // - its function-body shall not be a function-try-block;
1911 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1912 << isa<CXXConstructorDecl>(Dcl);
1913 return false;
1914 }
1915
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001916 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001917
1918 // - its function-body shall be [...] a compound-statement that contains only
1919 // [... list of cases ...]
1920 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1921 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001922 for (auto *BodyIt : CompBody->body()) {
1923 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001924 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001925 }
1926
Richard Smithd9f663b2013-04-22 15:31:51 +00001927 if (Cxx1yLoc.isValid())
1928 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001929 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001930 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1931 : diag::ext_constexpr_body_invalid_stmt)
1932 << isa<CXXConstructorDecl>(Dcl);
1933
Richard Smitheb3c10c2011-10-01 02:31:28 +00001934 if (const CXXConstructorDecl *Constructor
1935 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1936 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001937 // DR1359:
1938 // - every non-variant non-static data member and base class sub-object
1939 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001940 // DR1460:
1941 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001942 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001943 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001944 if (Constructor->getNumCtorInitializers() == 0 &&
1945 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001946 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1947 return false;
1948 }
Richard Smithf368fb42011-10-10 16:38:04 +00001949 } else if (!Constructor->isDependentContext() &&
1950 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001951 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1952
1953 // Skip detailed checking if we have enough initializers, and we would
1954 // allow at most one initializer per member.
1955 bool AnyAnonStructUnionMembers = false;
1956 unsigned Fields = 0;
1957 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1958 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001959 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001960 AnyAnonStructUnionMembers = true;
1961 break;
1962 }
1963 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001964 // DR1460:
1965 // - if the class is a union-like class, but is not a union, for each of
1966 // its anonymous union members having variant members, exactly one of
1967 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001968 if (AnyAnonStructUnionMembers ||
1969 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1970 // Check initialization of non-static data members. Base classes are
1971 // always initialized so do not need to be checked. Dependent bases
1972 // might not have initializers in the member initializer list.
1973 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001974 for (const auto *I: Constructor->inits()) {
1975 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001976 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001977 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001978 Inits.insert(ID->chain_begin(), ID->chain_end());
1979 }
1980
1981 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001982 for (auto *I : RD->fields())
1983 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001984 if (Diagnosed)
1985 return false;
1986 }
1987 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001988 } else {
1989 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001990 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001991 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001992 // otherwise if there's no return statement, the function cannot
1993 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001994 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001995 (Dcl->getReturnType()->isVoidType() ||
1996 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001997 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001998 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1999 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00002000 if (!OK)
2001 return false;
2002 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002003 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002004 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002005 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2006 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002007 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2008 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002009 }
2010 }
2011
Richard Smith74388b42012-02-04 00:33:54 +00002012 // C++11 [dcl.constexpr]p5:
2013 // if no function argument values exist such that the function invocation
2014 // substitution would produce a constant expression, the program is
2015 // ill-formed; no diagnostic required.
2016 // C++11 [dcl.constexpr]p3:
2017 // - every constructor call and implicit conversion used in initializing the
2018 // return value shall be one of those allowed in a constant expression.
2019 // C++11 [dcl.constexpr]p4:
2020 // - every constructor involved in initializing non-static data members and
2021 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002022 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002023 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002024 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002025 << isa<CXXConstructorDecl>(Dcl);
2026 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2027 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002028 // Don't return false here: we allow this for compatibility in
2029 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002030 }
2031
Richard Smitheb3c10c2011-10-01 02:31:28 +00002032 return true;
2033}
2034
Douglas Gregor61956c42008-10-31 09:07:45 +00002035/// isCurrentClassName - Determine whether the identifier II is the
2036/// name of the class type currently being defined. In the case of
2037/// nested classes, this will only return true if II is the name of
2038/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002039bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2040 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002041 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002042
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002043 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002044 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002045 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002046 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2047 } else
2048 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2049
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002050 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002051 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002052 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002053}
2054
Richard Smithfb8b7b92013-10-15 00:00:26 +00002055/// \brief Determine whether the identifier II is a typo for the name of
2056/// the class type currently being defined. If so, update it to the identifier
2057/// that should have been used.
2058bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2059 assert(getLangOpts().CPlusPlus && "No class names in C!");
2060
2061 if (!getLangOpts().SpellChecking)
2062 return false;
2063
2064 CXXRecordDecl *CurDecl;
2065 if (SS && SS->isSet() && !SS->isInvalid()) {
2066 DeclContext *DC = computeDeclContext(*SS, true);
2067 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2068 } else
2069 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2070
2071 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2072 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2073 < II->getLength()) {
2074 II = CurDecl->getIdentifier();
2075 return true;
2076 }
2077
2078 return false;
2079}
2080
Douglas Gregordc974572012-11-10 07:24:09 +00002081/// \brief Determine whether the given class is a base class of the given
2082/// class, including looking at dependent bases.
2083static bool findCircularInheritance(const CXXRecordDecl *Class,
2084 const CXXRecordDecl *Current) {
2085 SmallVector<const CXXRecordDecl*, 8> Queue;
2086
2087 Class = Class->getCanonicalDecl();
2088 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002089 for (const auto &I : Current->bases()) {
2090 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002091 if (!Base)
2092 continue;
2093
2094 Base = Base->getDefinition();
2095 if (!Base)
2096 continue;
2097
2098 if (Base->getCanonicalDecl() == Class)
2099 return true;
2100
2101 Queue.push_back(Base);
2102 }
2103
2104 if (Queue.empty())
2105 return false;
2106
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002107 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002108 }
2109
2110 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002111}
2112
Mike Stump11289f42009-09-09 15:08:12 +00002113/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002114///
2115/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2116/// and returns NULL otherwise.
2117CXXBaseSpecifier *
2118Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2119 SourceRange SpecifierRange,
2120 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002121 TypeSourceInfo *TInfo,
2122 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002123 QualType BaseType = TInfo->getType();
2124
Douglas Gregor463421d2009-03-03 04:44:36 +00002125 // C++ [class.union]p1:
2126 // A union shall not have base classes.
2127 if (Class->isUnion()) {
2128 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2129 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002131 }
2132
Douglas Gregor752a5952011-01-03 22:36:02 +00002133 if (EllipsisLoc.isValid() &&
2134 !TInfo->getType()->containsUnexpandedParameterPack()) {
2135 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2136 << TInfo->getTypeLoc().getSourceRange();
2137 EllipsisLoc = SourceLocation();
2138 }
Douglas Gregor62004702012-11-10 01:18:17 +00002139
2140 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2141
2142 if (BaseType->isDependentType()) {
2143 // Make sure that we don't have circular inheritance among our dependent
2144 // bases. For non-dependent bases, the check for completeness below handles
2145 // this.
2146 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2147 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2148 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002149 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002150 Diag(BaseLoc, diag::err_circular_inheritance)
2151 << BaseType << Context.getTypeDeclType(Class);
2152
2153 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2154 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2155 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002156
2157 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002158 }
2159 }
2160
Mike Stump11289f42009-09-09 15:08:12 +00002161 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002162 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002163 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002164 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002165
2166 // Base specifiers must be record types.
2167 if (!BaseType->isRecordType()) {
2168 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002169 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002170 }
2171
2172 // C++ [class.union]p1:
2173 // A union shall not be used as a base class.
2174 if (BaseType->isUnionType()) {
2175 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002176 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002177 }
2178
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002179 // For the MS ABI, propagate DLL attributes to base class templates.
2180 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2181 if (Attr *ClassAttr = getDLLAttr(Class)) {
2182 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2183 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002184 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2185 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002186 }
2187 }
2188 }
2189
Douglas Gregor463421d2009-03-03 04:44:36 +00002190 // C++ [class.derived]p2:
2191 // The class-name in a base-specifier shall not be an incompletely
2192 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002193 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002194 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002195 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002196 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002197 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002198
Eli Friedmanc96d4962009-08-15 21:55:26 +00002199 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002200 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002201 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002202 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002203 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002204 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002205 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002206
David Majnemer9b1754d2013-11-02 12:00:36 +00002207 // A class which contains a flexible array member is not suitable for use as a
2208 // base class:
2209 // - If the layout determines that a base comes before another base,
2210 // the flexible array member would index into the subsequent base.
2211 // - If the layout determines that base comes before the derived class,
2212 // the flexible array member would index into the derived class.
2213 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2214 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2215 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002216 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002217 }
2218
Anders Carlsson65c76d32011-03-25 14:55:14 +00002219 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002220 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002221 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002222 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002223 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002224 << CXXBaseDecl->getDeclName()
2225 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002226 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2227 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002228 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002229 }
2230
John McCall3696dcb2010-08-17 07:23:57 +00002231 if (BaseDecl->isInvalidDecl())
2232 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002233
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002234 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002235 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002236 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002237 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002238}
2239
Douglas Gregor556877c2008-04-13 21:30:24 +00002240/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2241/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002242/// example:
2243/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002244/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002245BaseResult
John McCall48871652010-08-21 09:40:31 +00002246Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002247 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002248 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002249 ParsedType basetype, SourceLocation BaseLoc,
2250 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002251 if (!classdecl)
2252 return true;
2253
Douglas Gregorc40290e2009-03-09 23:48:35 +00002254 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002255 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002256 if (!Class)
2257 return true;
2258
David Majnemer5ef4fe72014-06-13 06:43:46 +00002259 // We haven't yet attached the base specifiers.
2260 Class->setIsParsingBaseSpecifiers();
2261
Richard Smith4c96e992013-02-19 23:47:15 +00002262 // We do not support any C++11 attributes on base-specifiers yet.
2263 // Diagnose any attributes we see.
2264 if (!Attributes.empty()) {
2265 for (AttributeList *Attr = Attributes.getList(); Attr;
2266 Attr = Attr->getNext()) {
2267 if (Attr->isInvalid() ||
2268 Attr->getKind() == AttributeList::IgnoredAttribute)
2269 continue;
2270 Diag(Attr->getLoc(),
2271 Attr->getKind() == AttributeList::UnknownAttribute
2272 ? diag::warn_unknown_attribute_ignored
2273 : diag::err_base_specifier_attribute)
2274 << Attr->getName();
2275 }
2276 }
2277
Craig Topperc3ec1492014-05-26 06:22:03 +00002278 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002279 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002280
Douglas Gregor752a5952011-01-03 22:36:02 +00002281 if (EllipsisLoc.isInvalid() &&
2282 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002283 UPPC_BaseType))
2284 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002285
Douglas Gregor463421d2009-03-03 04:44:36 +00002286 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002287 Virtual, Access, TInfo,
2288 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002289 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002290 else
2291 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002292
Douglas Gregor463421d2009-03-03 04:44:36 +00002293 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002294}
Douglas Gregor556877c2008-04-13 21:30:24 +00002295
Nathan Sidwell44b21742015-01-19 01:44:02 +00002296/// Use small set to collect indirect bases. As this is only used
2297/// locally, there's no need to abstract the small size parameter.
2298typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2299
2300/// \brief Recursively add the bases of Type. Don't add Type itself.
2301static void
2302NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2303 const QualType &Type)
2304{
2305 // Even though the incoming type is a base, it might not be
2306 // a class -- it could be a template parm, for instance.
2307 if (auto Rec = Type->getAs<RecordType>()) {
2308 auto Decl = Rec->getAsCXXRecordDecl();
2309
2310 // Iterate over its bases.
2311 for (const auto &BaseSpec : Decl->bases()) {
2312 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2313 .getUnqualifiedType();
2314 if (Set.insert(Base).second)
2315 // If we've not already seen it, recurse.
2316 NoteIndirectBases(Context, Set, Base);
2317 }
2318 }
2319}
2320
Douglas Gregor463421d2009-03-03 04:44:36 +00002321/// \brief Performs the actual work of attaching the given base class
2322/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002323bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2324 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2325 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002326 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002327
2328 // Used to keep track of which base types we have already seen, so
2329 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002330 // that the key is always the unqualified canonical type of the base
2331 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002332 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2333
Nathan Sidwell44b21742015-01-19 01:44:02 +00002334 // Used to track indirect bases so we can see if a direct base is
2335 // ambiguous.
2336 IndirectBaseSet IndirectBaseTypes;
2337
Douglas Gregor29a92472008-10-22 17:49:05 +00002338 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002339 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002340 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002341 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002342 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002343 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002344 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002345
2346 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2347 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002348 // C++ [class.mi]p3:
2349 // A class shall not be specified as a direct base class of a
2350 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002351 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002352 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002353 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002354 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002355
2356 // Delete the duplicate base class specifier; we're going to
2357 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002358 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002359
2360 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002361 } else {
2362 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002363 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002364 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002365
2366 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002367 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002368 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2369
John McCalldb632ac2012-09-25 07:32:39 +00002370 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2371 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2372 if (Class->isInterface() &&
2373 (!RD->isInterface() ||
2374 KnownBase->getAccessSpecifier() != AS_public)) {
2375 // The Microsoft extension __interface does not permit bases that
2376 // are not themselves public interfaces.
2377 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2378 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2379 << RD->getSourceRange();
2380 Invalid = true;
2381 }
2382 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002383 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002384 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002385 }
2386 }
2387
2388 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002389 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002390
2391 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2392 // Check whether this direct base is inaccessible due to ambiguity.
2393 QualType BaseType = Bases[idx]->getType();
2394 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2395 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002396
Nathan Sidwell44b21742015-01-19 01:44:02 +00002397 if (IndirectBaseTypes.count(CanonicalBase)) {
2398 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2399 /*DetectVirtual=*/true);
2400 bool found
2401 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2402 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002403 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002404
2405 if (Paths.isAmbiguous(CanonicalBase))
2406 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2407 << BaseType << getAmbiguousPathsDisplayString(Paths)
2408 << Bases[idx]->getSourceRange();
2409 else
2410 assert(Bases[idx]->isVirtual());
2411 }
2412
2413 // Delete the base class specifier, since its data has been copied
2414 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002415 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002416 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002417
2418 return Invalid;
2419}
2420
2421/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2422/// class, after checking whether there are any duplicate base
2423/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002424void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2425 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2426 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002427 return;
2428
2429 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002430 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002431}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002432
Douglas Gregor36d1b142009-10-06 17:59:45 +00002433/// \brief Determine whether the type \p Derived is a C++ class that is
2434/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002435bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002436 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002437 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002438
Douglas Gregor45bb4832013-03-26 23:36:30 +00002439 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002440 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002441 return false;
2442
Douglas Gregor45bb4832013-03-26 23:36:30 +00002443 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002444 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002445 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002446
2447 // If either the base or the derived type is invalid, don't try to
2448 // check whether one is derived from the other.
2449 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2450 return false;
2451
Richard Smithdb0ac552015-12-18 22:40:25 +00002452 // FIXME: In a modules build, do we need the entire path to be visible for us
2453 // to be able to use the inheritance relationship?
2454 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2455 return false;
2456
Richard Smith0f59cb32015-12-18 21:45:41 +00002457 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002458}
2459
2460/// \brief Determine whether the type \p Derived is a C++ class that is
2461/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002462bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2463 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002464 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002465 return false;
2466
Douglas Gregor45bb4832013-03-26 23:36:30 +00002467 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002468 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002469 return false;
2470
Douglas Gregor45bb4832013-03-26 23:36:30 +00002471 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002472 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002473 return false;
2474
Richard Smithdb0ac552015-12-18 22:40:25 +00002475 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2476 return false;
2477
Douglas Gregor36d1b142009-10-06 17:59:45 +00002478 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2479}
2480
Anders Carlssona70cff62010-04-24 19:06:50 +00002481void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002482 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002483 assert(BasePathArray.empty() && "Base path array must be empty!");
2484 assert(Paths.isRecordingPaths() && "Must record paths!");
2485
2486 const CXXBasePath &Path = Paths.front();
2487
2488 // We first go backward and check if we have a virtual base.
2489 // FIXME: It would be better if CXXBasePath had the base specifier for
2490 // the nearest virtual base.
2491 unsigned Start = 0;
2492 for (unsigned I = Path.size(); I != 0; --I) {
2493 if (Path[I - 1].Base->isVirtual()) {
2494 Start = I - 1;
2495 break;
2496 }
2497 }
2498
2499 // Now add all bases.
2500 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002501 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002502}
2503
Douglas Gregor36d1b142009-10-06 17:59:45 +00002504/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2505/// conversion (where Derived and Base are class types) is
2506/// well-formed, meaning that the conversion is unambiguous (and
2507/// that all of the base classes are accessible). Returns true
2508/// and emits a diagnostic if the code is ill-formed, returns false
2509/// otherwise. Loc is the location where this routine should point to
2510/// if there is an error, and Range is the source range to highlight
2511/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002512///
2513/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2514/// diagnostic for the respective type of error will be suppressed, but the
2515/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002516bool
2517Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002518 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002519 unsigned AmbigiousBaseConvID,
2520 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002521 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002522 CXXCastPath *BasePath,
2523 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002524 // First, determine whether the path from Derived to Base is
2525 // ambiguous. This is slightly more expensive than checking whether
2526 // the Derived to Base conversion exists, because here we need to
2527 // explore multiple paths to determine if there is an ambiguity.
2528 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2529 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002530 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002531 assert(DerivationOkay &&
2532 "Can only be used with a derived-to-base conversion");
2533 (void)DerivationOkay;
2534
2535 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002536 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002537 // Check that the base class can be accessed.
2538 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2539 InaccessibleBaseID)) {
2540 case AR_inaccessible:
2541 return true;
2542 case AR_accessible:
2543 case AR_dependent:
2544 case AR_delayed:
2545 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002546 }
John McCall5b0829a2010-02-10 09:31:12 +00002547 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002548
2549 // Build a base path if necessary.
2550 if (BasePath)
2551 BuildBasePathArray(Paths, *BasePath);
2552 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002553 }
2554
David Majnemer626032f2013-06-22 06:43:58 +00002555 if (AmbigiousBaseConvID) {
2556 // We know that the derived-to-base conversion is ambiguous, and
2557 // we're going to produce a diagnostic. Perform the derived-to-base
2558 // search just one more time to compute all of the possible paths so
2559 // that we can print them out. This is more expensive than any of
2560 // the previous derived-to-base checks we've done, but at this point
2561 // performance isn't as much of an issue.
2562 Paths.clear();
2563 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002564 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002565 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2566 (void)StillOkay;
2567
2568 // Build up a textual representation of the ambiguous paths, e.g.,
2569 // D -> B -> A, that will be used to illustrate the ambiguous
2570 // conversions in the diagnostic. We only print one of the paths
2571 // to each base class subobject.
2572 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2573
2574 Diag(Loc, AmbigiousBaseConvID)
2575 << Derived << Base << PathDisplayStr << Range << Name;
2576 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002577 return true;
2578}
2579
2580bool
2581Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002582 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002583 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002584 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002585 return CheckDerivedToBaseConversion(
2586 Derived, Base, diag::err_upcast_to_inaccessible_base,
2587 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2588 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002589}
2590
2591
2592/// @brief Builds a string representing ambiguous paths from a
2593/// specific derived class to different subobjects of the same base
2594/// class.
2595///
2596/// This function builds a string that can be used in error messages
2597/// to show the different paths that one can take through the
2598/// inheritance hierarchy to go from the derived class to different
2599/// subobjects of a base class. The result looks something like this:
2600/// @code
2601/// struct D -> struct B -> struct A
2602/// struct D -> struct C -> struct A
2603/// @endcode
2604std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2605 std::string PathDisplayStr;
2606 std::set<unsigned> DisplayedPaths;
2607 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2608 Path != Paths.end(); ++Path) {
2609 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2610 // We haven't displayed a path to this particular base
2611 // class subobject yet.
2612 PathDisplayStr += "\n ";
2613 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2614 for (CXXBasePath::const_iterator Element = Path->begin();
2615 Element != Path->end(); ++Element)
2616 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2617 }
2618 }
2619
2620 return PathDisplayStr;
2621}
2622
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002623//===----------------------------------------------------------------------===//
2624// C++ class member Handling
2625//===----------------------------------------------------------------------===//
2626
Abramo Bagnarad7340582010-06-05 05:09:32 +00002627/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002628bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2629 SourceLocation ASLoc,
2630 SourceLocation ColonLoc,
2631 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002632 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002633 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002634 ASLoc, ColonLoc);
2635 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002636 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002637}
2638
Richard Smith18f07db2012-08-06 03:25:17 +00002639/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002640void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002641 if (D->isInvalidDecl())
2642 return;
2643
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002644 // We only care about "override" and "final" declarations.
2645 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2646 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002647
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002648 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002649
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002650 // We can't check dependent instance methods.
2651 if (MD && MD->isInstance() &&
2652 (MD->getParent()->hasAnyDependentBases() ||
2653 MD->getType()->isDependentType()))
2654 return;
2655
2656 if (MD && !MD->isVirtual()) {
2657 // If we have a non-virtual method, check if if hides a virtual method.
2658 // (In that case, it's most likely the method has the wrong type.)
2659 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2660 FindHiddenVirtualMethods(MD, OverloadedMethods);
2661
2662 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002663 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2664 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002665 diag::override_keyword_hides_virtual_member_function)
2666 << "override" << (OverloadedMethods.size() > 1);
2667 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002668 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002669 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002670 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2671 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002672 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002673 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2674 MD->setInvalidDecl();
2675 return;
2676 }
2677 // Fall through into the general case diagnostic.
2678 // FIXME: We might want to attempt typo correction here.
2679 }
2680
2681 if (!MD || !MD->isVirtual()) {
2682 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2683 Diag(OA->getLocation(),
2684 diag::override_keyword_only_allowed_on_virtual_member_functions)
2685 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2686 D->dropAttr<OverrideAttr>();
2687 }
2688 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2689 Diag(FA->getLocation(),
2690 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002691 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2692 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002693 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002694 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002695 return;
2696 }
Richard Smith18f07db2012-08-06 03:25:17 +00002697
Richard Smith18f07db2012-08-06 03:25:17 +00002698 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002699 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002700 // does not override a member function of a base class, the program is
2701 // ill-formed.
2702 bool HasOverriddenMethods =
2703 MD->begin_overridden_methods() != MD->end_overridden_methods();
2704 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2705 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2706 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002707}
2708
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002709void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2710 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2711 return;
2712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2713 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2714 isa<CXXDestructorDecl>(MD))
2715 return;
2716
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002717 SourceLocation Loc = MD->getLocation();
2718 SourceLocation SpellingLoc = Loc;
2719 if (getSourceManager().isMacroArgExpansion(Loc))
2720 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2721 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2722 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002723 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002724
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002725 if (MD->size_overridden_methods() > 0) {
2726 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2727 << MD->getDeclName();
2728 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2729 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2730 }
2731}
2732
Richard Smith18f07db2012-08-06 03:25:17 +00002733/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002734/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002735/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002736bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2737 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002738 FinalAttr *FA = Old->getAttr<FinalAttr>();
2739 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002740 return false;
2741
2742 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002743 << New->getDeclName()
2744 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002745 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2746 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002747}
2748
Daniel Jasper0baec5492012-06-06 08:32:04 +00002749static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002750 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2751 // FIXME: Destruction of ObjC lifetime types has side-effects.
2752 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2753 return !RD->isCompleteDefinition() ||
2754 !RD->hasTrivialDefaultConstructor() ||
2755 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002756 return false;
2757}
2758
John McCall5e77d762013-04-16 07:28:30 +00002759static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002760 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002761 if (it->isDeclspecPropertyAttribute())
2762 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002763 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002764}
2765
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002766/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2767/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002768/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002769/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2770/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002771NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002772Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002773 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002774 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002775 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002776 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002777 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2778 DeclarationName Name = NameInfo.getName();
2779 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002780
2781 // For anonymous bitfields, the location should point to the type.
2782 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002783 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002784
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002785 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002786
John McCallb1cd7da2010-06-04 08:34:12 +00002787 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002788 assert(!DS.isFriendSpecified());
2789
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002790 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002791
John McCalldb632ac2012-09-25 07:32:39 +00002792 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2793 // The Microsoft extension __interface only permits public member functions
2794 // and prohibits constructors, destructors, operators, non-public member
2795 // functions, static methods and data members.
2796 unsigned InvalidDecl;
2797 bool ShowDeclName = true;
2798 if (!isFunc)
2799 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2800 else if (AS != AS_public)
2801 InvalidDecl = 2;
2802 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2803 InvalidDecl = 3;
2804 else switch (Name.getNameKind()) {
2805 case DeclarationName::CXXConstructorName:
2806 InvalidDecl = 4;
2807 ShowDeclName = false;
2808 break;
2809
2810 case DeclarationName::CXXDestructorName:
2811 InvalidDecl = 5;
2812 ShowDeclName = false;
2813 break;
2814
2815 case DeclarationName::CXXOperatorName:
2816 case DeclarationName::CXXConversionFunctionName:
2817 InvalidDecl = 6;
2818 break;
2819
2820 default:
2821 InvalidDecl = 0;
2822 break;
2823 }
2824
2825 if (InvalidDecl) {
2826 if (ShowDeclName)
2827 Diag(Loc, diag::err_invalid_member_in_interface)
2828 << (InvalidDecl-1) << Name;
2829 else
2830 Diag(Loc, diag::err_invalid_member_in_interface)
2831 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002832 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002833 }
2834 }
2835
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002836 // C++ 9.2p6: A member shall not be declared to have automatic storage
2837 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002838 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2839 // data members and cannot be applied to names declared const or static,
2840 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002841 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002842 case DeclSpec::SCS_unspecified:
2843 case DeclSpec::SCS_typedef:
2844 case DeclSpec::SCS_static:
2845 break;
2846 case DeclSpec::SCS_mutable:
2847 if (isFunc) {
2848 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002849
Richard Smithb4a9e862013-04-12 22:46:28 +00002850 // FIXME: It would be nicer if the keyword was ignored only for this
2851 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002852 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002853 }
2854 break;
2855 default:
2856 Diag(DS.getStorageClassSpecLoc(),
2857 diag::err_storageclass_invalid_for_member);
2858 D.getMutableDeclSpec().ClearStorageClassSpecs();
2859 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002860 }
2861
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002862 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2863 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002864 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002865
David Blaikie35506f82013-01-30 01:22:18 +00002866 if (DS.isConstexprSpecified() && isInstField) {
2867 SemaDiagnosticBuilder B =
2868 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2869 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2870 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002871 B << 0 << 0;
2872 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2873 B << FixItHint::CreateRemoval(ConstexprLoc);
2874 else {
2875 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2876 D.getMutableDeclSpec().ClearConstexprSpec();
2877 const char *PrevSpec;
2878 unsigned DiagID;
2879 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2880 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2881 (void)Failed;
2882 assert(!Failed && "Making a constexpr member const shouldn't fail");
2883 }
David Blaikie35506f82013-01-30 01:22:18 +00002884 } else {
2885 B << 1;
2886 const char *PrevSpec;
2887 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002888 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002889 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2890 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002891 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002892 "This is the only DeclSpec that should fail to be applied");
2893 B << 1;
2894 } else {
2895 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2896 isInstField = false;
2897 }
2898 }
2899 }
2900
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002901 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002902 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002903 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002904
2905 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002906 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002907 Diag(Loc, diag::err_bad_variable_name)
2908 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002909 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002910 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002911
Benjamin Kramer365082d2012-05-19 16:34:46 +00002912 IdentifierInfo *II = Name.getAsIdentifierInfo();
2913
Douglas Gregor7c26c042011-09-21 14:40:46 +00002914 // Member field could not be with "template" keyword.
2915 // So TemplateParameterLists should be empty in this case.
2916 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002917 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002918 if (TemplateParams->size()) {
2919 // There is no such thing as a member field template.
2920 Diag(D.getIdentifierLoc(), diag::err_template_member)
2921 << II
2922 << SourceRange(TemplateParams->getTemplateLoc(),
2923 TemplateParams->getRAngleLoc());
2924 } else {
2925 // There is an extraneous 'template<>' for this member.
2926 Diag(TemplateParams->getTemplateLoc(),
2927 diag::err_template_member_noparams)
2928 << II
2929 << SourceRange(TemplateParams->getTemplateLoc(),
2930 TemplateParams->getRAngleLoc());
2931 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002932 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002933 }
2934
Douglas Gregora007d362010-10-13 22:19:53 +00002935 if (SS.isSet() && !SS.isInvalid()) {
2936 // The user provided a superfluous scope specifier inside a class
2937 // definition:
2938 //
2939 // class X {
2940 // int X::member;
2941 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002942 if (DeclContext *DC = computeDeclContext(SS, false))
2943 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002944 else
2945 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2946 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002947
Douglas Gregora007d362010-10-13 22:19:53 +00002948 SS.clear();
2949 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002950
John McCall5e77d762013-04-16 07:28:30 +00002951 AttributeList *MSPropertyAttr =
2952 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002953 if (MSPropertyAttr) {
2954 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2955 BitWidth, InitStyle, AS, MSPropertyAttr);
2956 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002957 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002958 isInstField = false;
2959 } else {
2960 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2961 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00002962 if (!Member)
2963 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002964 }
2965 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002966 Member = HandleDeclarator(S, D, TemplateParameterLists);
2967 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002968 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002969
2970 // Non-instance-fields can't have a bitfield.
2971 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002972 if (Member->isInvalidDecl()) {
2973 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002974 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002975 // C++ 9.6p3: A bit-field shall not be a static member.
2976 // "static member 'A' cannot be a bit-field"
2977 Diag(Loc, diag::err_static_not_bitfield)
2978 << Name << BitWidth->getSourceRange();
2979 } else if (isa<TypedefDecl>(Member)) {
2980 // "typedef member 'x' cannot be a bit-field"
2981 Diag(Loc, diag::err_typedef_not_bitfield)
2982 << Name << BitWidth->getSourceRange();
2983 } else {
2984 // A function typedef ("typedef int f(); f a;").
2985 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2986 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002987 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002988 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002989 }
Mike Stump11289f42009-09-09 15:08:12 +00002990
Craig Topperc3ec1492014-05-26 06:22:03 +00002991 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002992 Member->setInvalidDecl();
2993 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002994
2995 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002996
Larisse Voufo39a1e502013-08-06 01:03:05 +00002997 // If we have declared a member function template or static data member
2998 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002999 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3000 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003001 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3002 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003003 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003004
Richard Smith18f07db2012-08-06 03:25:17 +00003005 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003006 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003007 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003008 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3009 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003010
Douglas Gregorf2f08062011-03-08 17:10:18 +00003011 if (VS.getLastLocation().isValid()) {
3012 // Update the end location of a method that has a virt-specifiers.
3013 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3014 MD->setRangeEnd(VS.getLastLocation());
3015 }
Richard Smith18f07db2012-08-06 03:25:17 +00003016
Anders Carlssonc87f8612011-01-20 06:29:02 +00003017 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003018
Douglas Gregor92751d42008-11-17 22:58:34 +00003019 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003020
Daniel Jasper0baec5492012-06-06 08:32:04 +00003021 if (isInstField) {
3022 FieldDecl *FD = cast<FieldDecl>(Member);
3023 FieldCollector->Add(FD);
3024
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003025 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003026 // Remember all explicit private FieldDecls that have a name, no side
3027 // effects and are not part of a dependent type declaration.
3028 if (!FD->isImplicit() && FD->getDeclName() &&
3029 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003030 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003031 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003032 !InitializationHasSideEffects(*FD))
3033 UnusedPrivateFields.insert(FD);
3034 }
3035 }
3036
John McCall48871652010-08-21 09:40:31 +00003037 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003038}
3039
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003040namespace {
3041 class UninitializedFieldVisitor
3042 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3043 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003044 // List of Decls to generate a warning on. Also remove Decls that become
3045 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003046 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003047 // List of base classes of the record. Classes are removed after their
3048 // initializers.
3049 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003050 // Vector of decls to be removed from the Decl set prior to visiting the
3051 // nodes. These Decls may have been initialized in the prior initializer.
3052 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003053 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003054 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003055 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003056 // InitList is true, special case initialization of FieldDecls matching
3057 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003058 bool InitList;
3059 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003060 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3061
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003062 public:
3063 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003064 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003065 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3066 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3067 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3068 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003069
Richard Trieufa1d0a72014-10-17 20:56:10 +00003070 // Returns true if the use of ME is not an uninitialized use.
3071 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3072 bool CheckReferenceOnly) {
3073 llvm::SmallVector<FieldDecl*, 4> Fields;
3074 bool ReferenceField = false;
3075 while (ME) {
3076 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3077 if (!FD)
3078 return false;
3079 Fields.push_back(FD);
3080 if (FD->getType()->isReferenceType())
3081 ReferenceField = true;
3082 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3083 }
3084
3085 // Binding a reference to an unintialized field is not an
3086 // uninitialized use.
3087 if (CheckReferenceOnly && !ReferenceField)
3088 return true;
3089
3090 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3091 // Discard the first field since it is the field decl that is being
3092 // initialized.
3093 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3094 UsedFieldIndex.push_back((*I)->getFieldIndex());
3095 }
3096
3097 for (auto UsedIter = UsedFieldIndex.begin(),
3098 UsedEnd = UsedFieldIndex.end(),
3099 OrigIter = InitFieldIndex.begin(),
3100 OrigEnd = InitFieldIndex.end();
3101 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3102 if (*UsedIter < *OrigIter)
3103 return true;
3104 if (*UsedIter > *OrigIter)
3105 break;
3106 }
3107
3108 return false;
3109 }
3110
Richard Trieu2d779b92014-10-01 03:44:58 +00003111 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3112 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003113 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3114 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003115
Richard Trieu1bc22c12013-09-13 03:20:53 +00003116 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3117 // or union.
3118 MemberExpr *FieldME = ME;
3119
Richard Trieu2d779b92014-10-01 03:44:58 +00003120 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3121
Richard Trieu1bc22c12013-09-13 03:20:53 +00003122 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003123 while (MemberExpr *SubME =
3124 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003125
Richard Trieufa1d0a72014-10-17 20:56:10 +00003126 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003127 return;
3128
Richard Trieufa1d0a72014-10-17 20:56:10 +00003129 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003130 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003131 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003132
Richard Trieu2d779b92014-10-01 03:44:58 +00003133 if (!FieldME->getType().isPODType(S.Context))
3134 AllPODFields = false;
3135
Richard Trieu3630c392014-11-21 03:10:30 +00003136 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003137 }
3138
Richard Trieu3630c392014-11-21 03:10:30 +00003139 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003140 return;
3141
Richard Trieu2d779b92014-10-01 03:44:58 +00003142 if (AddressOf && AllPODFields)
3143 return;
3144
Richard Trieu406e65c2013-09-20 03:03:06 +00003145 ValueDecl* FoundVD = FieldME->getMemberDecl();
3146
Richard Trieu3630c392014-11-21 03:10:30 +00003147 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3148 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3149 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3150 }
3151
3152 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3153 QualType T = BaseCast->getType();
3154 if (T->isPointerType() &&
3155 BaseClasses.count(T->getPointeeType())) {
3156 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3157 << T->getPointeeType() << FoundVD;
3158 }
3159 }
3160 }
3161
Richard Trieuef64e942013-10-25 00:56:00 +00003162 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003163 return;
3164
Richard Trieuef64e942013-10-25 00:56:00 +00003165 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003166
Richard Trieufa1d0a72014-10-17 20:56:10 +00003167 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3168 // Special checking for initializer lists.
3169 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3170 return;
3171 }
3172 } else {
3173 // Prevent double warnings on use of unbounded references.
3174 if (CheckReferenceOnly && !IsReference)
3175 return;
3176 }
Richard Trieuef64e942013-10-25 00:56:00 +00003177
3178 unsigned diag = IsReference
3179 ? diag::warn_reference_field_is_uninit
3180 : diag::warn_field_is_uninit;
3181 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3182 if (Constructor)
3183 S.Diag(Constructor->getLocation(),
3184 diag::note_uninit_in_this_constructor)
3185 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3186
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003187 }
3188
Richard Trieu2d779b92014-10-01 03:44:58 +00003189 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003190 E = E->IgnoreParens();
3191
3192 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003193 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3194 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003195 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003196 }
3197
3198 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003199 Visit(CO->getCond());
3200 HandleValue(CO->getTrueExpr(), AddressOf);
3201 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003202 return;
3203 }
3204
3205 if (BinaryConditionalOperator *BCO =
3206 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003207 Visit(BCO->getCond());
3208 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003209 return;
3210 }
3211
Richard Trieuabf6ec42014-08-27 22:15:10 +00003212 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003213 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003214 return;
3215 }
3216
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3218 switch (BO->getOpcode()) {
3219 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003220 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003221 case(BO_PtrMemD):
3222 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003223 HandleValue(BO->getLHS(), AddressOf);
3224 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003225 return;
3226 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003227 Visit(BO->getLHS());
3228 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003229 return;
3230 }
3231 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003232
3233 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003234 }
3235
Richard Trieufa1d0a72014-10-17 20:56:10 +00003236 void CheckInitListExpr(InitListExpr *ILE) {
3237 InitFieldIndex.push_back(0);
3238 for (auto Child : ILE->children()) {
3239 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3240 CheckInitListExpr(SubList);
3241 } else {
3242 Visit(Child);
3243 }
3244 ++InitFieldIndex.back();
3245 }
3246 InitFieldIndex.pop_back();
3247 }
3248
Richard Trieu8d08a272014-08-28 03:23:47 +00003249 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003250 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003251 // Remove Decls that may have been initialized in the previous
3252 // initializer.
3253 for (ValueDecl* VD : DeclsToRemove)
3254 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003255 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003256
Richard Trieu8d08a272014-08-28 03:23:47 +00003257 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003258 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3259
3260 if (ILE && Field) {
3261 InitList = true;
3262 InitListFieldDecl = Field;
3263 InitFieldIndex.clear();
3264 CheckInitListExpr(ILE);
3265 } else {
3266 InitList = false;
3267 Visit(E);
3268 }
3269
Richard Trieu8d08a272014-08-28 03:23:47 +00003270 if (Field)
3271 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003272 if (BaseClass)
3273 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003274 }
3275
Richard Trieu1bc22c12013-09-13 03:20:53 +00003276 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003277 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003278 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003279 }
3280
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003281 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003282 if (E->getCastKind() == CK_LValueToRValue) {
3283 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3284 return;
3285 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003286
3287 Inherited::VisitImplicitCastExpr(E);
3288 }
3289
Richard Trieu1bc22c12013-09-13 03:20:53 +00003290 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003291 if (E->getConstructor()->isCopyConstructor()) {
3292 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003293 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3294 if (ILE->getNumInits() == 1)
3295 ArgExpr = ILE->getInit(0);
3296 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3297 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003298 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003299 HandleValue(ArgExpr, false /*AddressOf*/);
3300 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003301 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003302 Inherited::VisitCXXConstructExpr(E);
3303 }
3304
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003305 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3306 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003307 if (isa<MemberExpr>(Callee)) {
3308 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003309 for (auto Arg : E->arguments())
3310 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003311 return;
3312 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003313
3314 Inherited::VisitCXXMemberCallExpr(E);
3315 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003316
Richard Trieu11fd0792014-08-26 04:30:55 +00003317 void VisitCallExpr(CallExpr *E) {
3318 // Treat std::move as a use.
3319 if (E->getNumArgs() == 1) {
3320 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003321 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3322 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003323 HandleValue(E->getArg(0), false /*AddressOf*/);
3324 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003325 }
3326 }
3327 }
3328
3329 Inherited::VisitCallExpr(E);
3330 }
3331
Richard Trieud4a01362014-10-31 21:10:22 +00003332 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3333 Expr *Callee = E->getCallee();
3334
3335 if (isa<UnresolvedLookupExpr>(Callee))
3336 return Inherited::VisitCXXOperatorCallExpr(E);
3337
3338 Visit(Callee);
3339 for (auto Arg : E->arguments())
3340 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3341 }
3342
Richard Trieu406e65c2013-09-20 03:03:06 +00003343 void VisitBinaryOperator(BinaryOperator *E) {
3344 // If a field assignment is detected, remove the field from the
3345 // uninitiailized field set.
3346 if (E->getOpcode() == BO_Assign)
3347 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3348 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003349 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003350 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003351
Richard Trieu52b8b602014-09-25 01:15:40 +00003352 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003353 HandleValue(E->getLHS(), false /*AddressOf*/);
3354 Visit(E->getRHS());
3355 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003356 }
3357
Richard Trieu406e65c2013-09-20 03:03:06 +00003358 Inherited::VisitBinaryOperator(E);
3359 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003360
3361 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003362 if (E->isIncrementDecrementOp()) {
3363 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3364 return;
3365 }
3366 if (E->getOpcode() == UO_AddrOf) {
3367 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3368 HandleValue(ME->getBase(), true /*AddressOf*/);
3369 return;
3370 }
3371 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003372
3373 Inherited::VisitUnaryOperator(E);
3374 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003375 };
Richard Trieuef64e942013-10-25 00:56:00 +00003376
3377 // Diagnose value-uses of fields to initialize themselves, e.g.
3378 // foo(foo)
3379 // where foo is not also a parameter to the constructor.
3380 // Also diagnose across field uninitialized use such as
3381 // x(y), y(x)
3382 // TODO: implement -Wuninitialized and fold this into that framework.
3383 static void DiagnoseUninitializedFields(
3384 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3385
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003386 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3387 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003388 return;
3389 }
3390
3391 if (Constructor->isInvalidDecl())
3392 return;
3393
3394 const CXXRecordDecl *RD = Constructor->getParent();
3395
Richard Trieu353a4b42014-10-22 05:21:59 +00003396 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003397 return;
3398
Richard Trieuef64e942013-10-25 00:56:00 +00003399 // Holds fields that are uninitialized.
3400 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3401
3402 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003403 for (auto *I : RD->decls()) {
3404 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003405 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003406 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003407 UninitializedFields.insert(IFD->getAnonField());
3408 }
3409 }
3410
Richard Trieu3630c392014-11-21 03:10:30 +00003411 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3412 for (auto I : RD->bases())
3413 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3414
3415 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003416 return;
3417
3418 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003419 UninitializedFields,
3420 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003421
Aaron Ballman0ad78302014-03-13 17:34:31 +00003422 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003423 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003424 break;
3425
Aaron Ballman0ad78302014-03-13 17:34:31 +00003426 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003427 if (!InitExpr)
3428 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003429
Richard Trieu8d08a272014-08-28 03:23:47 +00003430 if (CXXDefaultInitExpr *Default =
3431 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3432 InitExpr = Default->getExpr();
3433 if (!InitExpr)
3434 continue;
3435 // In class initializers will point to the constructor.
3436 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003437 FieldInit->getAnyMember(),
3438 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003439 } else {
3440 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003441 FieldInit->getAnyMember(),
3442 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003443 }
Richard Trieuef64e942013-10-25 00:56:00 +00003444 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003445 }
3446} // namespace
3447
Richard Smith74108172014-01-17 03:11:34 +00003448/// \brief Enter a new C++ default initializer scope. After calling this, the
3449/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3450/// parsing or instantiating the initializer failed.
3451void Sema::ActOnStartCXXInClassMemberInitializer() {
3452 // Create a synthetic function scope to represent the call to the constructor
3453 // that notionally surrounds a use of this initializer.
3454 PushFunctionScope();
3455}
3456
3457/// \brief This is invoked after parsing an in-class initializer for a
3458/// non-static C++ class member, and after instantiating an in-class initializer
3459/// in a class template. Such actions are deferred until the class is complete.
3460void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3461 SourceLocation InitLoc,
3462 Expr *InitExpr) {
3463 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003464 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003465
David Majnemer87ff66c2014-12-13 11:34:16 +00003466 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3467 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003468 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003469
3470 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003471 D->setInvalidDecl();
3472 if (FD)
3473 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003474 return;
3475 }
3476
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003477 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3478 FD->setInvalidDecl();
3479 FD->removeInClassInitializer();
3480 return;
3481 }
3482
Richard Smith938f40b2011-06-11 17:19:42 +00003483 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003484 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003485 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003486 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003487 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003488 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003489 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3490 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003491 if (Init.isInvalid()) {
3492 FD->setInvalidDecl();
3493 return;
3494 }
Richard Smith938f40b2011-06-11 17:19:42 +00003495 }
3496
Richard Smith945f8d32013-01-14 22:39:08 +00003497 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003498 // The initialization of each base and member constitutes a
3499 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003500 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003501 if (Init.isInvalid()) {
3502 FD->setInvalidDecl();
3503 return;
3504 }
3505
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003506 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003507
3508 FD->setInClassInitializer(InitExpr);
3509}
3510
Douglas Gregor15e77a22009-12-31 09:10:24 +00003511/// \brief Find the direct and/or virtual base specifiers that
3512/// correspond to the given base type, for use in base initialization
3513/// within a constructor.
3514static bool FindBaseInitializer(Sema &SemaRef,
3515 CXXRecordDecl *ClassDecl,
3516 QualType BaseType,
3517 const CXXBaseSpecifier *&DirectBaseSpec,
3518 const CXXBaseSpecifier *&VirtualBaseSpec) {
3519 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003520 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003521 for (const auto &Base : ClassDecl->bases()) {
3522 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003523 // We found a direct base of this type. That's what we're
3524 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003525 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003526 break;
3527 }
3528 }
3529
3530 // Check for a virtual base class.
3531 // FIXME: We might be able to short-circuit this if we know in advance that
3532 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003533 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003534 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3535 // We haven't found a base yet; search the class hierarchy for a
3536 // virtual base class.
3537 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3538 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003539 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3540 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003541 BaseType, Paths)) {
3542 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3543 Path != Paths.end(); ++Path) {
3544 if (Path->back().Base->isVirtual()) {
3545 VirtualBaseSpec = Path->back().Base;
3546 break;
3547 }
3548 }
3549 }
3550 }
3551
3552 return DirectBaseSpec || VirtualBaseSpec;
3553}
3554
Sebastian Redla74948d2011-09-24 17:48:25 +00003555/// \brief Handle a C++ member initializer using braced-init-list syntax.
3556MemInitResult
3557Sema::ActOnMemInitializer(Decl *ConstructorD,
3558 Scope *S,
3559 CXXScopeSpec &SS,
3560 IdentifierInfo *MemberOrBase,
3561 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003562 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003563 SourceLocation IdLoc,
3564 Expr *InitList,
3565 SourceLocation EllipsisLoc) {
3566 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003567 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003568 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003569}
3570
3571/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003572MemInitResult
John McCall48871652010-08-21 09:40:31 +00003573Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003574 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003575 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003576 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003577 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003578 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003579 SourceLocation IdLoc,
3580 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003581 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003582 SourceLocation RParenLoc,
3583 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003584 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003585 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003586 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003587 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003588}
3589
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003590namespace {
3591
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003592// Callback to only accept typo corrections that can be a valid C++ member
3593// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003594class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003595public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003596 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3597 : ClassDecl(ClassDecl) {}
3598
Craig Toppera798a9d2014-03-02 09:32:10 +00003599 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003600 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3601 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3602 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003603 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003604 }
3605 return false;
3606 }
3607
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003608private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003609 CXXRecordDecl *ClassDecl;
3610};
3611
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003612}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003613
Sebastian Redla74948d2011-09-24 17:48:25 +00003614/// \brief Handle a C++ member initializer.
3615MemInitResult
3616Sema::BuildMemInitializer(Decl *ConstructorD,
3617 Scope *S,
3618 CXXScopeSpec &SS,
3619 IdentifierInfo *MemberOrBase,
3620 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003621 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003622 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003623 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003624 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003625 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3626 if (!Res.isUsable())
3627 return true;
3628 Init = Res.get();
3629
Douglas Gregor71a57182009-06-22 23:20:33 +00003630 if (!ConstructorD)
3631 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003633 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003634
3635 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003636 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003637 if (!Constructor) {
3638 // The user wrote a constructor initializer on a function that is
3639 // not a C++ constructor. Ignore the error for now, because we may
3640 // have more member initializers coming; we'll diagnose it just
3641 // once in ActOnMemInitializers.
3642 return true;
3643 }
3644
3645 CXXRecordDecl *ClassDecl = Constructor->getParent();
3646
3647 // C++ [class.base.init]p2:
3648 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003649 // constructor's class and, if not found in that scope, are looked
3650 // up in the scope containing the constructor's definition.
3651 // [Note: if the constructor's class contains a member with the
3652 // same name as a direct or virtual base class of the class, a
3653 // mem-initializer-id naming the member or base class and composed
3654 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003655 // mem-initializer-id for the hidden base class may be specified
3656 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003657 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003658 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003659 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003660 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003661 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003662 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3663 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003664 if (EllipsisLoc.isValid())
3665 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003666 << MemberOrBase
3667 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003668
Sebastian Redla9351792012-02-11 23:51:47 +00003669 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003670 }
Francois Pichetd583da02010-12-04 09:14:42 +00003671 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003672 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003673 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003674 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003675 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003676
3677 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003678 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003679 } else if (DS.getTypeSpecType() == TST_decltype) {
3680 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00003681 } else {
3682 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3683 LookupParsedName(R, S, &SS);
3684
3685 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3686 if (!TyD) {
3687 if (R.isAmbiguous()) return true;
3688
John McCallda6841b2010-04-09 19:01:14 +00003689 // We don't want access-control diagnostics here.
3690 R.suppressDiagnostics();
3691
Douglas Gregora3b624a2010-01-19 06:46:48 +00003692 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3693 bool NotUnknownSpecialization = false;
3694 DeclContext *DC = computeDeclContext(SS, false);
3695 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3696 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3697
3698 if (!NotUnknownSpecialization) {
3699 // When the scope specifier can refer to a member of an unknown
3700 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003701 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3702 SS.getWithLocInContext(Context),
3703 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003704 if (BaseType.isNull())
3705 return true;
3706
Douglas Gregora3b624a2010-01-19 06:46:48 +00003707 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003708 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003709 }
3710 }
3711
Douglas Gregor15e77a22009-12-31 09:10:24 +00003712 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003713 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003714 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003715 (Corr = CorrectTypo(
3716 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3717 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3718 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003719 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003720 // We have found a non-static data member with a similar
3721 // name to what was typed; complain and initialize that
3722 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003723 diagnoseTypo(Corr,
3724 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3725 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003726 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003727 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003728 const CXXBaseSpecifier *DirectBaseSpec;
3729 const CXXBaseSpecifier *VirtualBaseSpec;
3730 if (FindBaseInitializer(*this, ClassDecl,
3731 Context.getTypeDeclType(Type),
3732 DirectBaseSpec, VirtualBaseSpec)) {
3733 // We have found a direct or virtual base class with a
3734 // similar name to what was typed; complain and initialize
3735 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003736 diagnoseTypo(Corr,
3737 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3738 << MemberOrBase << false,
3739 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003740
Richard Smithf9b15102013-08-17 00:46:16 +00003741 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3742 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003743 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003744 diag::note_base_class_specified_here)
3745 << BaseSpec->getType()
3746 << BaseSpec->getSourceRange();
3747
Douglas Gregor15e77a22009-12-31 09:10:24 +00003748 TyD = Type;
3749 }
3750 }
3751 }
3752
Douglas Gregora3b624a2010-01-19 06:46:48 +00003753 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003754 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003755 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003756 return true;
3757 }
John McCallb5a0d312009-12-21 10:41:20 +00003758 }
3759
Douglas Gregora3b624a2010-01-19 06:46:48 +00003760 if (BaseType.isNull()) {
3761 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003762 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003763 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003764 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3765 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003766 TInfo = Context.CreateTypeSourceInfo(BaseType);
3767 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3768 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3769 TL.setElaboratedKeywordLoc(SourceLocation());
3770 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3771 }
John McCallb5a0d312009-12-21 10:41:20 +00003772 }
3773 }
Mike Stump11289f42009-09-09 15:08:12 +00003774
John McCallbcd03502009-12-07 02:54:59 +00003775 if (!TInfo)
3776 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003777
Sebastian Redla9351792012-02-11 23:51:47 +00003778 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003779}
3780
Chandler Carruth599deef2011-09-03 01:14:15 +00003781/// Checks a member initializer expression for cases where reference (or
3782/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003783static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3784 Expr *Init,
3785 SourceLocation IdLoc) {
3786 QualType MemberTy = Member->getType();
3787
3788 // We only handle pointers and references currently.
3789 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3790 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3791 return;
3792
3793 const bool IsPointer = MemberTy->isPointerType();
3794 if (IsPointer) {
3795 if (const UnaryOperator *Op
3796 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3797 // The only case we're worried about with pointers requires taking the
3798 // address.
3799 if (Op->getOpcode() != UO_AddrOf)
3800 return;
3801
3802 Init = Op->getSubExpr();
3803 } else {
3804 // We only handle address-of expression initializers for pointers.
3805 return;
3806 }
3807 }
3808
Richard Smithe3b28bc2013-06-12 21:51:50 +00003809 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003810 // We only warn when referring to a non-reference parameter declaration.
3811 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3812 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003813 return;
3814
3815 S.Diag(Init->getExprLoc(),
3816 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3817 : diag::warn_bind_ref_member_to_parameter)
3818 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003819 } else {
3820 // Other initializers are fine.
3821 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003822 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003823
3824 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3825 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003826}
3827
John McCallfaf5fb42010-08-26 23:41:50 +00003828MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003829Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003830 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003831 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3832 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3833 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003834 "Member must be a FieldDecl or IndirectFieldDecl");
3835
Sebastian Redla9351792012-02-11 23:51:47 +00003836 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003837 return true;
3838
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003839 if (Member->isInvalidDecl())
3840 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003841
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003842 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003843 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003844 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003845 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003846 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003847 } else {
3848 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003849 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003850 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003851
Sebastian Redla9351792012-02-11 23:51:47 +00003852 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003853
Sebastian Redla9351792012-02-11 23:51:47 +00003854 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003855 // Can't check initialization for a member of dependent type or when
3856 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003857 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003858 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003859 bool InitList = false;
3860 if (isa<InitListExpr>(Init)) {
3861 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003862 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003863 }
3864
Chandler Carruthd44c3102010-12-06 09:23:57 +00003865 // Initialize the member.
3866 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003867 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3868 : InitializedEntity::InitializeMember(IndirectMember,
3869 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003870 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003871 InitList ? InitializationKind::CreateDirectList(IdLoc)
3872 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3873 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003874
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003875 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003876 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3877 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003878 if (MemberInit.isInvalid())
3879 return true;
3880
Richard Smith736a9472013-06-12 20:42:33 +00003881 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3882
Richard Smith945f8d32013-01-14 22:39:08 +00003883 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003884 // The initialization of each base and member constitutes a
3885 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003886 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003887 if (MemberInit.isInvalid())
3888 return true;
3889
Richard Smithd59b8322012-12-19 01:39:02 +00003890 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003891 }
3892
Chandler Carruthd44c3102010-12-06 09:23:57 +00003893 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003894 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3895 InitRange.getBegin(), Init,
3896 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003897 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003898 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3899 InitRange.getBegin(), Init,
3900 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003901 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003902}
3903
John McCallfaf5fb42010-08-26 23:41:50 +00003904MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003905Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003906 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003907 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003908 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003909 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003910 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003911 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003912
Sebastian Redl0501c632012-02-12 16:37:36 +00003913 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003914 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003915 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3916 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003917 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003918 }
3919
Sebastian Redla9351792012-02-11 23:51:47 +00003920 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003921 // Initialize the object.
3922 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3923 QualType(ClassDecl->getTypeForDecl(), 0));
3924 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003925 InitList ? InitializationKind::CreateDirectList(NameLoc)
3926 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3927 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003928 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003929 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003931 if (DelegationInit.isInvalid())
3932 return true;
3933
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003934 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3935 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003936
Richard Smith945f8d32013-01-14 22:39:08 +00003937 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003938 // The initialization of each base and member constitutes a
3939 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003940 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3941 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003942 if (DelegationInit.isInvalid())
3943 return true;
3944
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003945 // If we are in a dependent context, template instantiation will
3946 // perform this type-checking again. Just save the arguments that we
3947 // received in a ParenListExpr.
3948 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3949 // of the information that we have about the base
3950 // initializer. However, deconstructing the ASTs is a dicey process,
3951 // and this approach is far more likely to get the corner cases right.
3952 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003953 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003954
Sebastian Redla9351792012-02-11 23:51:47 +00003955 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003956 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003957 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003958}
3959
3960MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003961Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003962 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003963 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003964 SourceLocation BaseLoc
3965 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003966
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003967 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3968 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3969 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3970
3971 // C++ [class.base.init]p2:
3972 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003973 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003974 // of that class, the mem-initializer is ill-formed. A
3975 // mem-initializer-list can initialize a base class using any
3976 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003977 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003978
Sebastian Redla9351792012-02-11 23:51:47 +00003979 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003980 if (EllipsisLoc.isValid()) {
3981 // This is a pack expansion.
3982 if (!BaseType->containsUnexpandedParameterPack()) {
3983 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003984 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003985
Douglas Gregor44e7df62011-01-04 00:32:56 +00003986 EllipsisLoc = SourceLocation();
3987 }
3988 } else {
3989 // Check for any unexpanded parameter packs.
3990 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3991 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003992
Sebastian Redla9351792012-02-11 23:51:47 +00003993 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003994 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003995 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003996
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003997 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003998 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3999 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004000 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004001 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4002 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004003 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004004
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004005 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4006 VirtualBaseSpec);
4007
4008 // C++ [base.class.init]p2:
4009 // Unless the mem-initializer-id names a nonstatic data member of the
4010 // constructor's class or a direct or virtual base of that class, the
4011 // mem-initializer is ill-formed.
4012 if (!DirectBaseSpec && !VirtualBaseSpec) {
4013 // If the class has any dependent bases, then it's possible that
4014 // one of those types will resolve to the same type as
4015 // BaseType. Therefore, just treat this as a dependent base
4016 // class initialization. FIXME: Should we try to check the
4017 // initialization anyway? It seems odd.
4018 if (ClassDecl->hasAnyDependentBases())
4019 Dependent = true;
4020 else
4021 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4022 << BaseType << Context.getTypeDeclType(ClassDecl)
4023 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4024 }
4025 }
4026
4027 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004028 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004029
Sebastian Redla74948d2011-09-24 17:48:25 +00004030 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4031 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004032 InitRange.getBegin(), Init,
4033 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004034 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004035
4036 // C++ [base.class.init]p2:
4037 // If a mem-initializer-id is ambiguous because it designates both
4038 // a direct non-virtual base class and an inherited virtual base
4039 // class, the mem-initializer is ill-formed.
4040 if (DirectBaseSpec && VirtualBaseSpec)
4041 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004042 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004043
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004044 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004045 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004046 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004047
4048 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004049 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004050 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004051 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004052 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004053 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004054 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004055
4056 InitializedEntity BaseEntity =
4057 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4058 InitializationKind Kind =
4059 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4060 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4061 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004062 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004063 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004064 if (BaseInit.isInvalid())
4065 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004066
Richard Smith945f8d32013-01-14 22:39:08 +00004067 // C++11 [class.base.init]p7:
4068 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004069 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004070 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004071 if (BaseInit.isInvalid())
4072 return true;
4073
4074 // If we are in a dependent context, template instantiation will
4075 // perform this type-checking again. Just save the arguments that we
4076 // received in a ParenListExpr.
4077 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4078 // of the information that we have about the base
4079 // initializer. However, deconstructing the ASTs is a dicey process,
4080 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004081 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004082 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004083
Alexis Hunt1d792652011-01-08 20:30:50 +00004084 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004085 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004086 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004087 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004088 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004089}
4090
Sebastian Redl22653ba2011-08-30 19:58:05 +00004091// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004092static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4093 if (T.isNull()) T = E->getType();
4094 QualType TargetType = SemaRef.BuildReferenceType(
4095 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004096 SourceLocation ExprLoc = E->getLocStart();
4097 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4098 TargetType, ExprLoc);
4099
4100 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4101 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004102 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004103}
4104
Anders Carlsson1b00e242010-04-23 03:10:23 +00004105/// ImplicitInitializerKind - How an implicit base or member initializer should
4106/// initialize its base or member.
4107enum ImplicitInitializerKind {
4108 IIK_Default,
4109 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004110 IIK_Move,
4111 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004112};
4113
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004114static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004115BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004116 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004117 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004118 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004119 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004120 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004121 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4122 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004123
John McCalldadc5752010-08-24 06:29:42 +00004124 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004125
4126 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004127 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004128 case IIK_Default: {
4129 InitializationKind InitKind
4130 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004131 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4132 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004133 break;
4134 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004135
Sebastian Redl22653ba2011-08-30 19:58:05 +00004136 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004137 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004138 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004139 ParmVarDecl *Param = Constructor->getParamDecl(0);
4140 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004141
Anders Carlsson1b00e242010-04-23 03:10:23 +00004142 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004143 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004144 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004145 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004146 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004147
Eli Friedmanfa0df832012-02-02 03:46:19 +00004148 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4149
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004150 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004151 QualType ArgTy =
4152 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4153 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004154
Sebastian Redl22653ba2011-08-30 19:58:05 +00004155 if (Moving) {
4156 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4157 }
4158
John McCallcf142162010-08-07 06:22:56 +00004159 CXXCastPath BasePath;
4160 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004161 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4162 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004163 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004164 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004165
Anders Carlsson1b00e242010-04-23 03:10:23 +00004166 InitializationKind InitKind
4167 = InitializationKind::CreateDirect(Constructor->getLocation(),
4168 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004169 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4170 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004171 break;
4172 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004173 }
John McCallb268a282010-08-23 23:25:46 +00004174
Douglas Gregora40433a2010-12-07 00:41:46 +00004175 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004176 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004177 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004178
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004179 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004180 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004181 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4182 SourceLocation()),
4183 BaseSpec->isVirtual(),
4184 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004185 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004186 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004187 SourceLocation());
4188
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004189 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004190}
4191
Sebastian Redl22653ba2011-08-30 19:58:05 +00004192static bool RefersToRValueRef(Expr *MemRef) {
4193 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4194 return Referenced->getType()->isRValueReferenceType();
4195}
4196
Anders Carlsson3c1db572010-04-23 02:15:47 +00004197static bool
4198BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004199 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004200 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004201 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004202 if (Field->isInvalidDecl())
4203 return true;
4204
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004205 SourceLocation Loc = Constructor->getLocation();
4206
Sebastian Redl22653ba2011-08-30 19:58:05 +00004207 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4208 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004209 ParmVarDecl *Param = Constructor->getParamDecl(0);
4210 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004211
4212 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004213 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4214 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004215
Anders Carlsson423f5d82010-04-23 16:04:08 +00004216 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004217 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004218 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004219 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004220
Eli Friedmanfa0df832012-02-02 03:46:19 +00004221 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4222
Sebastian Redl22653ba2011-08-30 19:58:05 +00004223 if (Moving) {
4224 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4225 }
4226
Douglas Gregor94f9a482010-05-05 05:51:00 +00004227 // Build a reference to this field within the parameter.
4228 CXXScopeSpec SS;
4229 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4230 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004231 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4232 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004233 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004234 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004235 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004236 ParamType, Loc,
4237 /*IsArrow=*/false,
4238 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004239 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004240 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004241 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004242 /*TemplateArgs=*/nullptr,
4243 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004244 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004245 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004246
4247 // C++11 [class.copy]p15:
4248 // - if a member m has rvalue reference type T&&, it is direct-initialized
4249 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004250 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004251 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004252 }
4253
Douglas Gregor94f9a482010-05-05 05:51:00 +00004254 // When the field we are copying is an array, create index variables for
4255 // each dimension of the array. We use these index variables to subscript
4256 // the source array, and other clients (e.g., CodeGen) will perform the
4257 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004258 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004259 QualType BaseType = Field->getType();
4260 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004261 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004262 while (const ConstantArrayType *Array
4263 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004264 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004265 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00004266 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004267 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004268 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004269 llvm::raw_svector_ostream OS(Str);
4270 OS << "__i" << IndexVariables.size();
4271 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4272 }
4273 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00004274 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004275 IterationVarName, SizeType,
4276 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004277 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004278 IndexVariables.push_back(IterationVar);
4279
4280 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00004281 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00004282 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004283 assert(!IterationVarRef.isInvalid() &&
4284 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004285 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00004286 assert(!IterationVarRef.isInvalid() &&
4287 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00004288
Douglas Gregor94f9a482010-05-05 05:51:00 +00004289 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004290 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4291 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00004292 Loc);
4293 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00004294 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004295
Douglas Gregor94f9a482010-05-05 05:51:00 +00004296 BaseType = Array->getElementType();
4297 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004298
4299 // The array subscript expression is an lvalue, which is wrong for moving.
4300 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004301 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004302
Douglas Gregor94f9a482010-05-05 05:51:00 +00004303 // Construct the entity that we will be initializing. For an array, this
4304 // will be first element in the array, which may require several levels
4305 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004306 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004307 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00004308 if (Indirect)
4309 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4310 else
4311 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00004312 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4313 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4314 0,
4315 Entities.back()));
4316
4317 // Direct-initialize to use the copy constructor.
4318 InitializationKind InitKind =
4319 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4320
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004321 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00004322 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4323 CtorArgE);
4324
John McCalldadc5752010-08-24 06:29:42 +00004325 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00004326 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004327 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004328 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004329 if (MemberInit.isInvalid())
4330 return true;
4331
Douglas Gregor493627b2011-08-10 15:22:55 +00004332 if (Indirect) {
4333 assert(IndexVariables.size() == 0 &&
4334 "Indirect field improperly initialized");
4335 CXXMemberInit
4336 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4337 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004338 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004339 Loc);
4340 } else
4341 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004342 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004343 Loc,
4344 IndexVariables.data(),
4345 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00004346 return false;
4347 }
4348
Richard Smithc2bc61b2013-03-18 21:12:30 +00004349 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4350 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004351
Anders Carlsson3c1db572010-04-23 02:15:47 +00004352 QualType FieldBaseElementType =
4353 SemaRef.Context.getBaseElementType(Field->getType());
4354
Anders Carlsson3c1db572010-04-23 02:15:47 +00004355 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004356 InitializedEntity InitEntity
4357 = Indirect? InitializedEntity::InitializeMember(Indirect)
4358 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004359 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004360 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004361
4362 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4363 ExprResult MemberInit =
4364 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004365
Douglas Gregora40433a2010-12-07 00:41:46 +00004366 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004367 if (MemberInit.isInvalid())
4368 return true;
4369
Douglas Gregor493627b2011-08-10 15:22:55 +00004370 if (Indirect)
4371 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4372 Indirect, Loc,
4373 Loc,
4374 MemberInit.get(),
4375 Loc);
4376 else
4377 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4378 Field, Loc, Loc,
4379 MemberInit.get(),
4380 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004381 return false;
4382 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004383
Alexis Hunt8b455182011-05-17 00:19:05 +00004384 if (!Field->getParent()->isUnion()) {
4385 if (FieldBaseElementType->isReferenceType()) {
4386 SemaRef.Diag(Constructor->getLocation(),
4387 diag::err_uninitialized_member_in_ctor)
4388 << (int)Constructor->isImplicit()
4389 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4390 << 0 << Field->getDeclName();
4391 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4392 return true;
4393 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004394
Alexis Hunt8b455182011-05-17 00:19:05 +00004395 if (FieldBaseElementType.isConstQualified()) {
4396 SemaRef.Diag(Constructor->getLocation(),
4397 diag::err_uninitialized_member_in_ctor)
4398 << (int)Constructor->isImplicit()
4399 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4400 << 1 << Field->getDeclName();
4401 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4402 return true;
4403 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004404 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004405
David Blaikiebbafb8a2012-03-11 07:00:24 +00004406 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004407 FieldBaseElementType->isObjCRetainableType() &&
4408 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4409 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004410 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004411 // Default-initialize Objective-C pointers to NULL.
4412 CXXMemberInit
4413 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4414 Loc, Loc,
4415 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4416 Loc);
4417 return false;
4418 }
4419
Anders Carlsson3c1db572010-04-23 02:15:47 +00004420 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004421 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004422 return false;
4423}
John McCallbc83b3f2010-05-20 23:23:51 +00004424
4425namespace {
4426struct BaseAndFieldInfo {
4427 Sema &S;
4428 CXXConstructorDecl *Ctor;
4429 bool AnyErrorsInInits;
4430 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004431 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004432 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004433 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004434
4435 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4436 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004437 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004438 if (Ctor->getInheritedConstructor())
4439 IIK = IIK_Inherit;
4440 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004441 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004442 else if (Generated && Ctor->isMoveConstructor())
4443 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004444 else
4445 IIK = IIK_Default;
4446 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004447
4448 bool isImplicitCopyOrMove() const {
4449 switch (IIK) {
4450 case IIK_Copy:
4451 case IIK_Move:
4452 return true;
4453
4454 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004455 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004456 return false;
4457 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004458
4459 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004460 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004461
4462 bool addFieldInitializer(CXXCtorInitializer *Init) {
4463 AllToInit.push_back(Init);
4464
4465 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004466 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004467 S.UnusedPrivateFields.remove(Init->getAnyMember());
4468
4469 return false;
4470 }
John McCallbc83b3f2010-05-20 23:23:51 +00004471
Richard Smithab44d5b2013-12-10 08:25:00 +00004472 bool isInactiveUnionMember(FieldDecl *Field) {
4473 RecordDecl *Record = Field->getParent();
4474 if (!Record->isUnion())
4475 return false;
4476
Richard Smith8d183852013-12-10 20:56:03 +00004477 if (FieldDecl *Active =
4478 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004479 return Active != Field->getCanonicalDecl();
4480
4481 // In an implicit copy or move constructor, ignore any in-class initializer.
4482 if (isImplicitCopyOrMove())
4483 return true;
4484
4485 // If there's no explicit initialization, the field is active only if it
4486 // has an in-class initializer...
4487 if (Field->hasInClassInitializer())
4488 return false;
4489 // ... or it's an anonymous struct or union whose class has an in-class
4490 // initializer.
4491 if (!Field->isAnonymousStructOrUnion())
4492 return true;
4493 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4494 return !FieldRD->hasInClassInitializer();
4495 }
4496
4497 /// \brief Determine whether the given field is, or is within, a union member
4498 /// that is inactive (because there was an initializer given for a different
4499 /// member of the union, or because the union was not initialized at all).
4500 bool isWithinInactiveUnionMember(FieldDecl *Field,
4501 IndirectFieldDecl *Indirect) {
4502 if (!Indirect)
4503 return isInactiveUnionMember(Field);
4504
Aaron Ballman29c94602014-03-07 18:36:15 +00004505 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004506 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004507 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004508 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004509 }
4510 return false;
4511 }
4512};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004513}
Richard Smithc94ec842011-09-19 13:34:43 +00004514
Douglas Gregor10f939c2011-11-02 23:04:16 +00004515/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4516/// array type.
4517static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4518 if (T->isIncompleteArrayType())
4519 return true;
4520
4521 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4522 if (!ArrayT->getSize())
4523 return true;
4524
4525 T = ArrayT->getElementType();
4526 }
4527
4528 return false;
4529}
4530
Richard Smith938f40b2011-06-11 17:19:42 +00004531static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004532 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004534 if (Field->isInvalidDecl())
4535 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004536
Chandler Carruth139e9622010-06-30 02:59:29 +00004537 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004538 if (CXXCtorInitializer *Init =
4539 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004540 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004541
Richard Smithab44d5b2013-12-10 08:25:00 +00004542 // C++11 [class.base.init]p8:
4543 // if the entity is a non-static data member that has a
4544 // brace-or-equal-initializer and either
4545 // -- the constructor's class is a union and no other variant member of that
4546 // union is designated by a mem-initializer-id or
4547 // -- the constructor's class is not a union, and, if the entity is a member
4548 // of an anonymous union, no other member of that union is designated by
4549 // a mem-initializer-id,
4550 // the entity is initialized as specified in [dcl.init].
4551 //
4552 // We also apply the same rules to handle anonymous structs within anonymous
4553 // unions.
4554 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4555 return false;
4556
Douglas Gregor7db3e952011-11-28 20:03:15 +00004557 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004558 ExprResult DIE =
4559 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4560 if (DIE.isInvalid())
4561 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004562 CXXCtorInitializer *Init;
4563 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004564 Init = new (SemaRef.Context)
4565 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4566 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004567 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004568 Init = new (SemaRef.Context)
4569 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4570 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004571 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004572 }
4573
Douglas Gregor10f939c2011-11-02 23:04:16 +00004574 // Don't initialize incomplete or zero-length arrays.
4575 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4576 return false;
4577
John McCallbc83b3f2010-05-20 23:23:51 +00004578 // Don't try to build an implicit initializer if there were semantic
4579 // errors in any of the initializers (and therefore we might be
4580 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004581 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004582 return false;
4583
Craig Topperc3ec1492014-05-26 06:22:03 +00004584 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004585 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4586 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004587 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004588
Richard Smith0a8cfc72012-08-07 21:30:42 +00004589 if (!Init)
4590 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004591
Richard Smith0a8cfc72012-08-07 21:30:42 +00004592 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004593}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004594
4595bool
4596Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4597 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004598 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004599 Constructor->setNumCtorInitializers(1);
4600 CXXCtorInitializer **initializer =
4601 new (Context) CXXCtorInitializer*[1];
4602 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4603 Constructor->setCtorInitializers(initializer);
4604
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004605 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004606 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004607 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4608 }
4609
Alexis Hunte2622992011-05-05 00:05:47 +00004610 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004611
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004612 DiagnoseUninitializedFields(*this, Constructor);
4613
Alexis Hunt61bc1732011-05-01 07:04:31 +00004614 return false;
4615}
Douglas Gregor493627b2011-08-10 15:22:55 +00004616
David Blaikie3fc2f912013-01-17 05:26:25 +00004617bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4618 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004619 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004620 // Just store the initializers as written, they will be checked during
4621 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004622 if (!Initializers.empty()) {
4623 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004624 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004625 new (Context) CXXCtorInitializer*[Initializers.size()];
4626 memcpy(baseOrMemberInitializers, Initializers.data(),
4627 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004628 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004629 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004630
4631 // Let template instantiation know whether we had errors.
4632 if (AnyErrors)
4633 Constructor->setInvalidDecl();
4634
Anders Carlssondb0a9652010-04-02 06:26:44 +00004635 return false;
4636 }
4637
John McCallbc83b3f2010-05-20 23:23:51 +00004638 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004639
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004640 // We need to build the initializer AST according to order of construction
4641 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004642 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004643 if (!ClassDecl)
4644 return true;
4645
Eli Friedman9cf6b592009-11-09 19:20:36 +00004646 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004647
David Blaikie3fc2f912013-01-17 05:26:25 +00004648 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004649 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004650
Anders Carlssondb0a9652010-04-02 06:26:44 +00004651 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004652 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004653 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004654 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004655
4656 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004657 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004658 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004659 if (FD && FD->getParent()->isUnion())
4660 Info.ActiveUnionMember.insert(std::make_pair(
4661 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4662 }
4663 } else if (FieldDecl *FD = Member->getMember()) {
4664 if (FD->getParent()->isUnion())
4665 Info.ActiveUnionMember.insert(std::make_pair(
4666 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4667 }
4668 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004669 }
4670
Anders Carlsson43c64af2010-04-21 19:52:01 +00004671 // Keep track of the direct virtual bases.
4672 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004673 for (auto &I : ClassDecl->bases()) {
4674 if (I.isVirtual())
4675 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004676 }
4677
Anders Carlssondb0a9652010-04-02 06:26:44 +00004678 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004679 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004680 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004681 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004682 // [class.base.init]p7, per DR257:
4683 // A mem-initializer where the mem-initializer-id names a virtual base
4684 // class is ignored during execution of a constructor of any class that
4685 // is not the most derived class.
4686 if (ClassDecl->isAbstract()) {
4687 // FIXME: Provide a fixit to remove the base specifier. This requires
4688 // tracking the location of the associated comma for a base specifier.
4689 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004690 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004691 DiagnoseAbstractType(ClassDecl);
4692 }
4693
John McCallbc83b3f2010-05-20 23:23:51 +00004694 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004695 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4696 // [class.base.init]p8, per DR257:
4697 // If a given [...] base class is not named by a mem-initializer-id
4698 // [...] and the entity is not a virtual base class of an abstract
4699 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004700 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004701 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004702 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004703 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004704 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004705 HadError = true;
4706 continue;
4707 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004708
John McCallbc83b3f2010-05-20 23:23:51 +00004709 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004710 }
4711 }
Mike Stump11289f42009-09-09 15:08:12 +00004712
John McCallbc83b3f2010-05-20 23:23:51 +00004713 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004714 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004715 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004716 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004717 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004718
Alexis Hunt1d792652011-01-08 20:30:50 +00004719 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004720 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004721 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004722 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004723 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004724 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004725 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004726 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004727 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004728 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004729 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004730
John McCallbc83b3f2010-05-20 23:23:51 +00004731 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004732 }
4733 }
Mike Stump11289f42009-09-09 15:08:12 +00004734
John McCallbc83b3f2010-05-20 23:23:51 +00004735 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004736 for (auto *Mem : ClassDecl->decls()) {
4737 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004738 // C++ [class.bit]p2:
4739 // A declaration for a bit-field that omits the identifier declares an
4740 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4741 // initialized.
4742 if (F->isUnnamedBitfield())
4743 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004744
Sebastian Redl22653ba2011-08-30 19:58:05 +00004745 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004746 // handle anonymous struct/union fields based on their individual
4747 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004748 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004749 continue;
4750
4751 if (CollectFieldInitializer(*this, Info, F))
4752 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004753 continue;
4754 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004755
4756 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004757 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004758 continue;
4759
Aaron Ballman629afae2014-03-07 19:56:05 +00004760 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004761 if (F->getType()->isIncompleteArrayType()) {
4762 assert(ClassDecl->hasFlexibleArrayMember() &&
4763 "Incomplete array type is not valid");
4764 continue;
4765 }
4766
Douglas Gregor493627b2011-08-10 15:22:55 +00004767 // Initialize each field of an anonymous struct individually.
4768 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4769 HadError = true;
4770
4771 continue;
4772 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004773 }
Mike Stump11289f42009-09-09 15:08:12 +00004774
David Blaikie3fc2f912013-01-17 05:26:25 +00004775 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004776 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004777 Constructor->setNumCtorInitializers(NumInitializers);
4778 CXXCtorInitializer **baseOrMemberInitializers =
4779 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004780 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004781 NumInitializers * sizeof(CXXCtorInitializer*));
4782 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004783
John McCalla6309952010-03-16 21:39:52 +00004784 // Constructors implicitly reference the base and member
4785 // destructors.
4786 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4787 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004788 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004789
4790 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004791}
4792
David Blaikieb61b8152013-01-17 08:49:22 +00004793static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004794 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004795 const RecordDecl *RD = RT->getDecl();
4796 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004797 for (auto *Field : RD->fields())
4798 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004799 return;
4800 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004801 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004802 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004803}
4804
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004805static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4806 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004807}
4808
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004809static const void *GetKeyForMember(ASTContext &Context,
4810 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004811 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004812 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004813
Richard Smithcd45dbc2014-04-19 03:48:30 +00004814 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004815}
4816
David Blaikie3fc2f912013-01-17 05:26:25 +00004817static void DiagnoseBaseOrMemInitializerOrder(
4818 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4819 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004820 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004821 return;
Mike Stump11289f42009-09-09 15:08:12 +00004822
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004823 // Don't check initializers order unless the warning is enabled at the
4824 // location of at least one initializer.
4825 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004826 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004827 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004828 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4829 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004830 ShouldCheckOrder = true;
4831 break;
4832 }
4833 }
4834 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004835 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004836
John McCallbb7b6582010-04-10 07:37:23 +00004837 // Build the list of bases and members in the order that they'll
4838 // actually be initialized. The explicit initializers should be in
4839 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004840 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004841
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004842 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4843
John McCallbb7b6582010-04-10 07:37:23 +00004844 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004845 for (const auto &VBase : ClassDecl->vbases())
4846 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004847
John McCallbb7b6582010-04-10 07:37:23 +00004848 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004849 for (const auto &Base : ClassDecl->bases()) {
4850 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004851 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004852 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004853 }
Mike Stump11289f42009-09-09 15:08:12 +00004854
John McCallbb7b6582010-04-10 07:37:23 +00004855 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004856 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004857 if (Field->isUnnamedBitfield())
4858 continue;
4859
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004860 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004861 }
4862
John McCallbb7b6582010-04-10 07:37:23 +00004863 unsigned NumIdealInits = IdealInitKeys.size();
4864 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004865
Craig Topperc3ec1492014-05-26 06:22:03 +00004866 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004867 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004868 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004869 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004870
4871 // Scan forward to try to find this initializer in the idealized
4872 // initializers list.
4873 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4874 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004875 break;
John McCallbb7b6582010-04-10 07:37:23 +00004876
4877 // If we didn't find this initializer, it must be because we
4878 // scanned past it on a previous iteration. That can only
4879 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004880 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004881 Sema::SemaDiagnosticBuilder D =
4882 SemaRef.Diag(PrevInit->getSourceLocation(),
4883 diag::warn_initializer_out_of_order);
4884
Francois Pichetd583da02010-12-04 09:14:42 +00004885 if (PrevInit->isAnyMemberInitializer())
4886 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004887 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004888 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004889
Francois Pichetd583da02010-12-04 09:14:42 +00004890 if (Init->isAnyMemberInitializer())
4891 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004892 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004893 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004894
4895 // Move back to the initializer's location in the ideal list.
4896 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4897 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004898 break;
John McCallbb7b6582010-04-10 07:37:23 +00004899
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004900 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004901 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004902 }
John McCallbb7b6582010-04-10 07:37:23 +00004903
4904 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004905 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004906}
4907
John McCall23eebd92010-04-10 09:28:51 +00004908namespace {
4909bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004910 CXXCtorInitializer *Init,
4911 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004912 if (!PrevInit) {
4913 PrevInit = Init;
4914 return false;
4915 }
4916
Douglas Gregorea306a12013-03-25 23:28:23 +00004917 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004918 S.Diag(Init->getSourceLocation(),
4919 diag::err_multiple_mem_initialization)
4920 << Field->getDeclName()
4921 << Init->getSourceRange();
4922 else {
John McCall424cec92011-01-19 06:33:43 +00004923 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004924 assert(BaseClass && "neither field nor base");
4925 S.Diag(Init->getSourceLocation(),
4926 diag::err_multiple_base_initialization)
4927 << QualType(BaseClass, 0)
4928 << Init->getSourceRange();
4929 }
4930 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4931 << 0 << PrevInit->getSourceRange();
4932
4933 return true;
4934}
4935
Alexis Hunt1d792652011-01-08 20:30:50 +00004936typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004937typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4938
4939bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004940 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004941 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004942 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004943 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004944 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004945
4946 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004947 if (Parent->isUnion()) {
4948 UnionEntry &En = Unions[Parent];
4949 if (En.first && En.first != Child) {
4950 S.Diag(Init->getSourceLocation(),
4951 diag::err_multiple_mem_union_initialization)
4952 << Field->getDeclName()
4953 << Init->getSourceRange();
4954 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4955 << 0 << En.second->getSourceRange();
4956 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004957 }
4958 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004959 En.first = Child;
4960 En.second = Init;
4961 }
David Blaikie0f65d592011-11-17 06:01:57 +00004962 if (!Parent->isAnonymousStructOrUnion())
4963 return false;
John McCall23eebd92010-04-10 09:28:51 +00004964 }
4965
4966 Child = Parent;
4967 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004968 }
John McCall23eebd92010-04-10 09:28:51 +00004969
4970 return false;
4971}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004972}
John McCall23eebd92010-04-10 09:28:51 +00004973
Anders Carlssone857b292010-04-02 03:37:03 +00004974/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004975void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004976 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004977 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004978 bool AnyErrors) {
4979 if (!ConstructorDecl)
4980 return;
4981
4982 AdjustDeclIfTemplate(ConstructorDecl);
4983
4984 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004985 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004986
4987 if (!Constructor) {
4988 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4989 return;
4990 }
4991
John McCall23eebd92010-04-10 09:28:51 +00004992 // Mapping for the duplicate initializers check.
4993 // For member initializers, this is keyed with a FieldDecl*.
4994 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004995 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004996
4997 // Mapping for the inconsistent anonymous-union initializers check.
4998 RedundantUnionMap MemberUnions;
4999
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005000 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00005001 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00005002 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00005003
Abramo Bagnara341d7832010-05-26 18:09:23 +00005004 // Set the source order index.
5005 Init->setSourceOrder(i);
5006
Francois Pichetd583da02010-12-04 09:14:42 +00005007 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005008 const void *Key = GetKeyForMember(Context, Init);
5009 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005010 CheckRedundantUnionInit(*this, Init, MemberUnions))
5011 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005012 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005013 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005014 if (CheckRedundantInit(*this, Init, Members[Key]))
5015 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005016 } else {
5017 assert(Init->isDelegatingInitializer());
5018 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005019 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005020 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005021 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005022 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005023 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005024 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005025 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005026 // Return immediately as the initializer is set.
5027 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005028 }
Anders Carlssone857b292010-04-02 03:37:03 +00005029 }
5030
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005031 if (HadError)
5032 return;
5033
David Blaikie3fc2f912013-01-17 05:26:25 +00005034 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005035
David Blaikie3fc2f912013-01-17 05:26:25 +00005036 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005037
Richard Trieuef64e942013-10-25 00:56:00 +00005038 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005039}
5040
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005041void
John McCalla6309952010-03-16 21:39:52 +00005042Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5043 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005044 // Ignore dependent contexts. Also ignore unions, since their members never
5045 // have destructors implicitly called.
5046 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005047 return;
John McCall1064d7e2010-03-16 05:22:47 +00005048
5049 // FIXME: all the access-control diagnostics are positioned on the
5050 // field/base declaration. That's probably good; that said, the
5051 // user might reasonably want to know why the destructor is being
5052 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005053
Anders Carlssondee9a302009-11-17 04:44:12 +00005054 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005055 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005056 if (Field->isInvalidDecl())
5057 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005058
5059 // Don't destroy incomplete or zero-length arrays.
5060 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5061 continue;
5062
Anders Carlssondee9a302009-11-17 04:44:12 +00005063 QualType FieldType = Context.getBaseElementType(Field->getType());
5064
5065 const RecordType* RT = FieldType->getAs<RecordType>();
5066 if (!RT)
5067 continue;
5068
5069 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005070 if (FieldClassDecl->isInvalidDecl())
5071 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005072 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005073 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005074 // The destructor for an implicit anonymous union member is never invoked.
5075 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5076 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005077
Douglas Gregore71edda2010-07-01 22:47:18 +00005078 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005079 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005080 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005081 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005082 << Field->getDeclName()
5083 << FieldType);
5084
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005085 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005086 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005087 }
5088
John McCall1064d7e2010-03-16 05:22:47 +00005089 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5090
Anders Carlssondee9a302009-11-17 04:44:12 +00005091 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005092 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005093 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005094 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005095
5096 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005097 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00005098 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00005099
John McCall1064d7e2010-03-16 05:22:47 +00005100 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005101 // If our base class is invalid, we probably can't get its dtor anyway.
5102 if (BaseClassDecl->isInvalidDecl())
5103 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005104 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005105 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005106
Douglas Gregore71edda2010-07-01 22:47:18 +00005107 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005108 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005109
5110 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005111 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005112 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005113 << Base.getType()
5114 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005115 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005116
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005117 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005118 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005119 }
5120
5121 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005122 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005123 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005124 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005125
5126 // Ignore direct virtual bases.
5127 if (DirectVirtualBases.count(RT))
5128 continue;
5129
John McCall1064d7e2010-03-16 05:22:47 +00005130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005131 // If our base class is invalid, we probably can't get its dtor anyway.
5132 if (BaseClassDecl->isInvalidDecl())
5133 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005134 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005135 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005136
Douglas Gregore71edda2010-07-01 22:47:18 +00005137 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005138 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005139 if (CheckDestructorAccess(
5140 ClassDecl->getLocation(), Dtor,
5141 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005142 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005143 Context.getTypeDeclType(ClassDecl)) ==
5144 AR_accessible) {
5145 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005146 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005147 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005148 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005149 }
John McCall1064d7e2010-03-16 05:22:47 +00005150
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005151 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005152 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005153 }
5154}
5155
John McCall48871652010-08-21 09:40:31 +00005156void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005157 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005158 return;
Mike Stump11289f42009-09-09 15:08:12 +00005159
Mike Stump11289f42009-09-09 15:08:12 +00005160 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005161 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005162 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005163 DiagnoseUninitializedFields(*this, Constructor);
5164 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005165}
5166
Richard Smithdb0ac552015-12-18 22:40:25 +00005167bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005168 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005169 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005170
Richard Smithdb0ac552015-12-18 22:40:25 +00005171 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5172 if (!RD)
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 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5176 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005177
John McCall02db245d2010-08-18 09:41:07 +00005178 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005179 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005180 // over all the declarations when we have a full definition.
5181 const CXXRecordDecl *Def = RD->getDefinition();
5182 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005183 return false;
5184
Richard Smithdb0ac552015-12-18 22:40:25 +00005185 return RD->isAbstract();
5186}
5187
5188bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5189 TypeDiagnoser &Diagnoser) {
5190 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005192
Richard Smithdb0ac552015-12-18 22:40:25 +00005193 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005194 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005195 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005196 return true;
5197}
5198
5199void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5200 // Check if we've already emitted the list of pure virtual functions
5201 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005202 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005203 return;
Mike Stump11289f42009-09-09 15:08:12 +00005204
Richard Smithbc46e432013-07-22 02:56:56 +00005205 // If the diagnostic is suppressed, don't emit the notes. We're only
5206 // going to emit them once, so try to attach them to a diagnostic we're
5207 // actually going to show.
5208 if (Diags.isLastDiagnosticIgnored())
5209 return;
5210
Douglas Gregor4165bd62010-03-23 23:47:56 +00005211 CXXFinalOverriderMap FinalOverriders;
5212 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005213
Anders Carlssona2f74f32010-06-03 01:00:02 +00005214 // Keep a set of seen pure methods so we won't diagnose the same method
5215 // more than once.
5216 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5217
Douglas Gregor4165bd62010-03-23 23:47:56 +00005218 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5219 MEnd = FinalOverriders.end();
5220 M != MEnd;
5221 ++M) {
5222 for (OverridingMethods::iterator SO = M->second.begin(),
5223 SOEnd = M->second.end();
5224 SO != SOEnd; ++SO) {
5225 // C++ [class.abstract]p4:
5226 // A class is abstract if it contains or inherits at least one
5227 // pure virtual function for which the final overrider is pure
5228 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005229
Douglas Gregor4165bd62010-03-23 23:47:56 +00005230 //
5231 if (SO->second.size() != 1)
5232 continue;
5233
5234 if (!SO->second.front().Method->isPure())
5235 continue;
5236
David Blaikie82e95a32014-11-19 07:49:47 +00005237 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005238 continue;
5239
Douglas Gregor4165bd62010-03-23 23:47:56 +00005240 Diag(SO->second.front().Method->getLocation(),
5241 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005242 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005243 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005244 }
5245
5246 if (!PureVirtualClassDiagSet)
5247 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5248 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005249}
5250
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005251namespace {
John McCall02db245d2010-08-18 09:41:07 +00005252struct AbstractUsageInfo {
5253 Sema &S;
5254 CXXRecordDecl *Record;
5255 CanQualType AbstractType;
5256 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005257
John McCall02db245d2010-08-18 09:41:07 +00005258 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5259 : S(S), Record(Record),
5260 AbstractType(S.Context.getCanonicalType(
5261 S.Context.getTypeDeclType(Record))),
5262 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005263
John McCall02db245d2010-08-18 09:41:07 +00005264 void DiagnoseAbstractType() {
5265 if (Invalid) return;
5266 S.DiagnoseAbstractType(Record);
5267 Invalid = true;
5268 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005269
John McCall02db245d2010-08-18 09:41:07 +00005270 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5271};
5272
5273struct CheckAbstractUsage {
5274 AbstractUsageInfo &Info;
5275 const NamedDecl *Ctx;
5276
5277 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5278 : Info(Info), Ctx(Ctx) {}
5279
5280 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5281 switch (TL.getTypeLocClass()) {
5282#define ABSTRACT_TYPELOC(CLASS, PARENT)
5283#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005284 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005285#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005286 }
John McCall02db245d2010-08-18 09:41:07 +00005287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
John McCall02db245d2010-08-18 09:41:07 +00005289 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005290 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005291 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5292 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005293 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005294
5295 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005296 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005297 }
John McCall02db245d2010-08-18 09:41:07 +00005298 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005299
John McCall02db245d2010-08-18 09:41:07 +00005300 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5301 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5302 }
Mike Stump11289f42009-09-09 15:08:12 +00005303
John McCall02db245d2010-08-18 09:41:07 +00005304 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5305 // Visit the type parameters from a permissive context.
5306 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5307 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5308 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5309 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5310 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5311 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005312 }
John McCall02db245d2010-08-18 09:41:07 +00005313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
John McCall02db245d2010-08-18 09:41:07 +00005315 // Visit pointee types from a permissive context.
5316#define CheckPolymorphic(Type) \
5317 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5318 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5319 }
5320 CheckPolymorphic(PointerTypeLoc)
5321 CheckPolymorphic(ReferenceTypeLoc)
5322 CheckPolymorphic(MemberPointerTypeLoc)
5323 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005324 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005325
John McCall02db245d2010-08-18 09:41:07 +00005326 /// Handle all the types we haven't given a more specific
5327 /// implementation for above.
5328 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5329 // Every other kind of type that we haven't called out already
5330 // that has an inner type is either (1) sugar or (2) contains that
5331 // inner type in some way as a subobject.
5332 if (TypeLoc Next = TL.getNextTypeLoc())
5333 return Visit(Next, Sel);
5334
5335 // If there's no inner type and we're in a permissive context,
5336 // don't diagnose.
5337 if (Sel == Sema::AbstractNone) return;
5338
5339 // Check whether the type matches the abstract type.
5340 QualType T = TL.getType();
5341 if (T->isArrayType()) {
5342 Sel = Sema::AbstractArrayType;
5343 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005344 }
John McCall02db245d2010-08-18 09:41:07 +00005345 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5346 if (CT != Info.AbstractType) return;
5347
5348 // It matched; do some magic.
5349 if (Sel == Sema::AbstractArrayType) {
5350 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5351 << T << TL.getSourceRange();
5352 } else {
5353 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5354 << Sel << T << TL.getSourceRange();
5355 }
5356 Info.DiagnoseAbstractType();
5357 }
5358};
5359
5360void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5361 Sema::AbstractDiagSelID Sel) {
5362 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5363}
5364
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005365}
John McCall02db245d2010-08-18 09:41:07 +00005366
5367/// Check for invalid uses of an abstract type in a method declaration.
5368static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5369 CXXMethodDecl *MD) {
5370 // No need to do the check on definitions, which require that
5371 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005372 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005373 return;
5374
5375 // For safety's sake, just ignore it if we don't have type source
5376 // information. This should never happen for non-implicit methods,
5377 // but...
5378 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5379 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5380}
5381
5382/// Check for invalid uses of an abstract type within a class definition.
5383static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5384 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005385 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005386 if (D->isImplicit()) continue;
5387
5388 // Methods and method templates.
5389 if (isa<CXXMethodDecl>(D)) {
5390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5391 } else if (isa<FunctionTemplateDecl>(D)) {
5392 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5393 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5394
5395 // Fields and static variables.
5396 } else if (isa<FieldDecl>(D)) {
5397 FieldDecl *FD = cast<FieldDecl>(D);
5398 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5399 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5400 } else if (isa<VarDecl>(D)) {
5401 VarDecl *VD = cast<VarDecl>(D);
5402 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5403 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5404
5405 // Nested classes and class templates.
5406 } else if (isa<CXXRecordDecl>(D)) {
5407 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5408 } else if (isa<ClassTemplateDecl>(D)) {
5409 CheckAbstractClassUsage(Info,
5410 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5411 }
5412 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005413}
5414
Hans Wennborg99000c22015-08-15 01:18:16 +00005415static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5416 Attr *ClassAttr = getDLLAttr(Class);
5417 if (!ClassAttr)
5418 return;
5419
5420 assert(ClassAttr->getKind() == attr::DLLExport);
5421
5422 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5423
5424 if (TSK == TSK_ExplicitInstantiationDeclaration)
5425 // Don't go any further if this is just an explicit instantiation
5426 // declaration.
5427 return;
5428
5429 for (Decl *Member : Class->decls()) {
5430 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5431 if (!MD)
5432 continue;
5433
5434 if (Member->getAttr<DLLExportAttr>()) {
5435 if (MD->isUserProvided()) {
5436 // Instantiate non-default class member functions ...
5437
5438 // .. except for certain kinds of template specializations.
5439 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5440 continue;
5441
5442 S.MarkFunctionReferenced(Class->getLocation(), MD);
5443
5444 // The function will be passed to the consumer when its definition is
5445 // encountered.
5446 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5447 MD->isCopyAssignmentOperator() ||
5448 MD->isMoveAssignmentOperator()) {
5449 // Synthesize and instantiate non-trivial implicit methods, explicitly
5450 // defaulted methods, and the copy and move assignment operators. The
5451 // latter are exported even if they are trivial, because the address of
5452 // an operator can be taken and should compare equal accross libraries.
5453 DiagnosticErrorTrap Trap(S.Diags);
5454 S.MarkFunctionReferenced(Class->getLocation(), MD);
5455 if (Trap.hasErrorOccurred()) {
5456 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5457 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5458 break;
5459 }
5460
5461 // There is no later point when we will see the definition of this
5462 // function, so pass it to the consumer now.
5463 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5464 }
5465 }
5466 }
5467}
5468
Hans Wennborg853ae942014-05-30 16:59:42 +00005469/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005470void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005471 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005472
5473 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005474 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005475 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5476 if (Attr *TemplateAttr =
5477 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005478 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005479 A->setInherited(true);
5480 ClassAttr = A;
5481 }
5482 }
5483 }
5484
Hans Wennborg853ae942014-05-30 16:59:42 +00005485 if (!ClassAttr)
5486 return;
5487
Hans Wennborg8313c762014-11-03 16:09:16 +00005488 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005489 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005490 << Class << ClassAttr;
5491 return;
5492 }
5493
Hans Wennborg17f9b442015-05-27 00:06:45 +00005494 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005495 !ClassAttr->isInherited()) {
5496 // Diagnose dll attributes on members of class with dll attribute.
5497 for (Decl *Member : Class->decls()) {
5498 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5499 continue;
5500 InheritableAttr *MemberAttr = getDLLAttr(Member);
5501 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5502 continue;
5503
Hans Wennborg17f9b442015-05-27 00:06:45 +00005504 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005505 diag::err_attribute_dll_member_of_dll_class)
5506 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005507 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005508 Member->setInvalidDecl();
5509 }
5510 }
5511
5512 if (Class->getDescribedClassTemplate())
5513 // Don't inherit dll attribute until the template is instantiated.
5514 return;
5515
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005516 // The class is either imported or exported.
5517 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005518
Hans Wennborgfd76d912015-01-15 21:18:30 +00005519 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5520
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005521 // Ignore explicit dllexport on explicit class template instantiation declarations.
5522 if (ClassExported && !ClassAttr->isInherited() &&
5523 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005524 Class->dropAttr<DLLExportAttr>();
5525 return;
5526 }
5527
Hans Wennborg853ae942014-05-30 16:59:42 +00005528 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005529 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005530
5531 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5532 // seem to be true in practice?
5533
Hans Wennborg853ae942014-05-30 16:59:42 +00005534 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005535 VarDecl *VD = dyn_cast<VarDecl>(Member);
5536 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5537
5538 // Only methods and static fields inherit the attributes.
5539 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005540 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005541
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005542 if (MD) {
5543 // Don't process deleted methods.
5544 if (MD->isDeleted())
5545 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005546
David Majnemer30f058a2015-05-11 03:00:22 +00005547 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005548 // MinGW does not import or export inline methods.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005549 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemer30f058a2015-05-11 03:00:22 +00005550 continue;
5551
Dmitry Polukhin41581522016-05-13 09:03:56 +00005552 // MSVC versions before 2015 don't export the move assignment operators
5553 // and move constructor, so don't attempt to import/export them if
5554 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005555 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005556 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005557 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005558 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005559 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005560
5561 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5562 // operator is exported anyway.
5563 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5564 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5565 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005566 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005567 }
5568
Hans Wennborg287231c2015-04-22 04:05:17 +00005569 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5570 continue;
5571
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005572 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005573 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005574 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005575 NewAttr->setInherited(true);
5576 Member->addAttr(NewAttr);
5577 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005578 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005579
5580 if (ClassExported)
5581 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005582}
5583
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005584/// \brief Perform propagation of DLL attributes from a derived class to a
5585/// templated base class for MS compatibility.
5586void Sema::propagateDLLAttrToBaseClassTemplate(
5587 CXXRecordDecl *Class, Attr *ClassAttr,
5588 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5589 if (getDLLAttr(
5590 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5591 // If the base class template has a DLL attribute, don't try to change it.
5592 return;
5593 }
5594
5595 auto TSK = BaseTemplateSpec->getSpecializationKind();
5596 if (!getDLLAttr(BaseTemplateSpec) &&
5597 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5598 TSK == TSK_ImplicitInstantiation)) {
5599 // The template hasn't been instantiated yet (or it has, but only as an
5600 // explicit instantiation declaration or implicit instantiation, which means
5601 // we haven't codegenned any members yet), so propagate the attribute.
5602 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5603 NewAttr->setInherited(true);
5604 BaseTemplateSpec->addAttr(NewAttr);
5605
5606 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5607 // needs to be run again to work see the new attribute. Otherwise this will
5608 // get run whenever the template is instantiated.
5609 if (TSK != TSK_Undeclared)
5610 checkClassLevelDLLAttribute(BaseTemplateSpec);
5611
5612 return;
5613 }
5614
5615 if (getDLLAttr(BaseTemplateSpec)) {
5616 // The template has already been specialized or instantiated with an
5617 // attribute, explicitly or through propagation. We should not try to change
5618 // it.
5619 return;
5620 }
5621
5622 // The template was previously instantiated or explicitly specialized without
5623 // a dll attribute, It's too late for us to add an attribute, so warn that
5624 // this is unsupported.
5625 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5626 << BaseTemplateSpec->isExplicitSpecialization();
5627 Diag(ClassAttr->getLocation(), diag::note_attribute);
5628 if (BaseTemplateSpec->isExplicitSpecialization()) {
5629 Diag(BaseTemplateSpec->getLocation(),
5630 diag::note_template_class_explicit_specialization_was_here)
5631 << BaseTemplateSpec;
5632 } else {
5633 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5634 diag::note_template_class_instantiation_was_here)
5635 << BaseTemplateSpec;
5636 }
5637}
5638
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005639static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5640 SourceLocation DefaultLoc) {
5641 switch (S.getSpecialMember(MD)) {
5642 case Sema::CXXDefaultConstructor:
5643 S.DefineImplicitDefaultConstructor(DefaultLoc,
5644 cast<CXXConstructorDecl>(MD));
5645 break;
5646 case Sema::CXXCopyConstructor:
5647 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5648 break;
5649 case Sema::CXXCopyAssignment:
5650 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5651 break;
5652 case Sema::CXXDestructor:
5653 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5654 break;
5655 case Sema::CXXMoveConstructor:
5656 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5657 break;
5658 case Sema::CXXMoveAssignment:
5659 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5660 break;
5661 case Sema::CXXInvalid:
5662 llvm_unreachable("Invalid special member.");
5663 }
5664}
5665
Douglas Gregorc99f1552009-12-03 18:33:45 +00005666/// \brief Perform semantic checks on a class definition that has been
5667/// completing, introducing implicitly-declared members, checking for
5668/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005669void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005670 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005671 return;
5672
John McCall02db245d2010-08-18 09:41:07 +00005673 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5674 AbstractUsageInfo Info(*this, Record);
5675 CheckAbstractClassUsage(Info, Record);
5676 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005677
5678 // If this is not an aggregate type and has no user-declared constructor,
5679 // complain about any non-static data members of reference or const scalar
5680 // type, since they will never get initializers.
5681 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005682 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5683 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005684 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005685 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005686 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005687 continue;
5688
Douglas Gregor454a5b62010-04-15 00:00:53 +00005689 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005690 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005691 if (!Complained) {
5692 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5693 << Record->getTagKind() << Record;
5694 Complained = true;
5695 }
5696
5697 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5698 << F->getType()->isReferenceType()
5699 << F->getDeclName();
5700 }
5701 }
5702 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005703
Douglas Gregor36c22a22010-10-15 13:21:21 +00005704 if (Record->getIdentifier()) {
5705 // C++ [class.mem]p13:
5706 // If T is the name of a class, then each of the following shall have a
5707 // name different from T:
5708 // - every member of every anonymous union that is a member of class T.
5709 //
5710 // C++ [class.mem]p14:
5711 // In addition, if class T has a user-declared constructor (12.1), every
5712 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005713 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5714 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5715 ++I) {
5716 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005717 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5718 isa<IndirectFieldDecl>(D)) {
5719 Diag(D->getLocation(), diag::err_member_name_of_class)
5720 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005721 break;
5722 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005723 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005724 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005725
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005726 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005727 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005728 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005729 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5730 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005731 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5732 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5733 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005734
David Majnemera5433082013-10-18 00:33:31 +00005735 if (Record->isAbstract()) {
5736 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5737 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5738 << FA->isSpelledAsSealed();
5739 DiagnoseAbstractType(Record);
5740 }
David Blaikie348df502012-09-21 03:21:07 +00005741 }
5742
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005743 bool HasMethodWithOverrideControl = false,
5744 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005745 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005746 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005747 // See if a method overloads virtual methods in a base
5748 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005749 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005750 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005751 if (M->hasAttr<OverrideAttr>())
5752 HasMethodWithOverrideControl = true;
5753 else if (M->size_overridden_methods() > 0)
5754 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005755 // Check whether the explicitly-defaulted special members are valid.
5756 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005757 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005758
5759 // For an explicitly defaulted or deleted special member, we defer
5760 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005761 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005762 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005763 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005764 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005765
5766 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005767 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005768 }
5769 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005770
5771 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5772 M->hasAttr<DLLExportAttr>()) {
5773 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5774 M->isTrivial() &&
5775 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5776 CSM == CXXDestructor))
5777 M->dropAttr<DLLExportAttr>();
5778
5779 if (M->hasAttr<DLLExportAttr>()) {
5780 DefineImplicitSpecialMember(*this, M, M->getLocation());
5781 ActOnFinishInlineFunctionDef(M);
5782 }
5783 }
Richard Smithbd305122012-12-11 01:14:52 +00005784 }
5785 }
5786
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005787 if (HasMethodWithOverrideControl &&
5788 HasOverridingMethodWithoutOverrideControl) {
5789 // At least one method has the 'override' control declared.
5790 // Diagnose all other overridden methods which do not have 'override' specified on them.
5791 for (auto *M : Record->methods())
5792 DiagnoseAbsenceOfOverrideControl(M);
5793 }
Sebastian Redl08905022011-02-05 19:23:19 +00005794
John McCall95833f32014-02-27 20:30:49 +00005795 // ms_struct is a request to use the same ABI rules as MSVC. Check
5796 // whether this class uses any C++ features that are implemented
5797 // completely differently in MSVC, and if so, emit a diagnostic.
5798 // That diagnostic defaults to an error, but we allow projects to
5799 // map it down to a warning (or ignore it). It's a fairly common
5800 // practice among users of the ms_struct pragma to mass-annotate
5801 // headers, sweeping up a bunch of types that the project doesn't
5802 // really rely on MSVC-compatible layout for. We must therefore
5803 // support "ms_struct except for C++ stuff" as a secondary ABI.
5804 if (Record->isMsStruct(Context) &&
5805 (Record->isPolymorphic() || Record->getNumBases())) {
5806 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005807 }
5808
Hans Wennborg17f9b442015-05-27 00:06:45 +00005809 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005810}
5811
Richard Smith41c35d62013-11-27 03:39:20 +00005812/// Look up the special member function that would be called by a special
5813/// member function for a subobject of class type.
5814///
5815/// \param Class The class type of the subobject.
5816/// \param CSM The kind of special member function.
5817/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5818/// \param ConstRHS True if this is a copy operation with a const object
5819/// on its RHS, that is, if the argument to the outer special member
5820/// function is 'const' and this is not a field marked 'mutable'.
5821static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5822 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5823 unsigned FieldQuals, bool ConstRHS) {
5824 unsigned LHSQuals = 0;
5825 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5826 LHSQuals = FieldQuals;
5827
5828 unsigned RHSQuals = FieldQuals;
5829 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5830 RHSQuals = 0;
5831 else if (ConstRHS)
5832 RHSQuals |= Qualifiers::Const;
5833
5834 return S.LookupSpecialMember(Class, CSM,
5835 RHSQuals & Qualifiers::Const,
5836 RHSQuals & Qualifiers::Volatile,
5837 false,
5838 LHSQuals & Qualifiers::Const,
5839 LHSQuals & Qualifiers::Volatile);
5840}
5841
Richard Smith80a47022016-06-29 01:10:27 +00005842class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005843 Sema &S;
5844 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005845
5846 /// A mapping from the base classes through which the constructor was
5847 /// inherited to the using shadow declaration in that base class (or a null
5848 /// pointer if the constructor was declared in that base class).
5849 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5850 InheritedFromBases;
5851
Richard Smith80a47022016-06-29 01:10:27 +00005852public:
Richard Smith5179eb72016-06-28 19:03:57 +00005853 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5854 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005855 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005856 bool DiagnosedMultipleConstructedBases = false;
5857 CXXRecordDecl *ConstructedBase = nullptr;
5858 UsingDecl *ConstructedBaseUsing = nullptr;
5859
5860 // Find the set of such base class subobjects and check that there's a
5861 // unique constructed subobject.
5862 for (auto *D : Shadow->redecls()) {
5863 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5864 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5865 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5866
5867 InheritedFromBases.insert(
5868 std::make_pair(DNominatedBase->getCanonicalDecl(),
5869 DShadow->getNominatedBaseClassShadowDecl()));
5870 if (DShadow->constructsVirtualBase())
5871 InheritedFromBases.insert(
5872 std::make_pair(DConstructedBase->getCanonicalDecl(),
5873 DShadow->getConstructedBaseClassShadowDecl()));
5874 else
5875 assert(DNominatedBase == DConstructedBase);
5876
5877 // [class.inhctor.init]p2:
5878 // If the constructor was inherited from multiple base class subobjects
5879 // of type B, the program is ill-formed.
5880 if (!ConstructedBase) {
5881 ConstructedBase = DConstructedBase;
5882 ConstructedBaseUsing = D->getUsingDecl();
5883 } else if (ConstructedBase != DConstructedBase &&
5884 !Shadow->isInvalidDecl()) {
5885 if (!DiagnosedMultipleConstructedBases) {
5886 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5887 << Shadow->getTargetDecl();
5888 S.Diag(ConstructedBaseUsing->getLocation(),
5889 diag::note_ambiguous_inherited_constructor_using)
5890 << ConstructedBase;
5891 DiagnosedMultipleConstructedBases = true;
5892 }
5893 S.Diag(D->getUsingDecl()->getLocation(),
5894 diag::note_ambiguous_inherited_constructor_using)
5895 << DConstructedBase;
5896 }
5897 }
5898
5899 if (DiagnosedMultipleConstructedBases)
5900 Shadow->setInvalidDecl();
5901 }
5902
5903 /// Find the constructor to use for inherited construction of a base class,
5904 /// and whether that base class constructor inherits the constructor from a
5905 /// virtual base class (in which case it won't actually invoke it).
5906 std::pair<CXXConstructorDecl *, bool>
5907 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5908 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5909 if (It == InheritedFromBases.end())
5910 return std::make_pair(nullptr, false);
5911
5912 // This is an intermediary class.
5913 if (It->second)
5914 return std::make_pair(
5915 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5916 It->second->constructsVirtualBase());
5917
5918 // This is the base class from which the constructor was inherited.
5919 return std::make_pair(Ctor, false);
5920 }
5921};
Richard Smith5179eb72016-06-28 19:03:57 +00005922
Richard Smithb5800092012-06-10 05:43:50 +00005923/// Is the special member function which would be selected to perform the
5924/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005925static bool
5926specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5927 Sema::CXXSpecialMember CSM, unsigned Quals,
5928 bool ConstRHS,
5929 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005930 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005931 // If we're inheriting a constructor, see if we need to call it for this base
5932 // class.
5933 if (InheritedCtor) {
5934 assert(CSM == Sema::CXXDefaultConstructor);
5935 auto BaseCtor =
5936 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5937 if (BaseCtor)
5938 return BaseCtor->isConstexpr();
5939 }
5940
5941 if (CSM == Sema::CXXDefaultConstructor)
5942 return ClassDecl->hasConstexprDefaultConstructor();
5943
Richard Smithb5800092012-06-10 05:43:50 +00005944 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005945 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005946 if (!SMOR || !SMOR->getMethod())
5947 // A constructor we wouldn't select can't be "involved in initializing"
5948 // anything.
5949 return true;
5950 return SMOR->getMethod()->isConstexpr();
5951}
5952
5953/// Determine whether the specified special member function would be constexpr
5954/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005955static bool defaultedSpecialMemberIsConstexpr(
5956 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5957 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005958 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005959 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005960 return false;
5961
5962 // C++11 [dcl.constexpr]p4:
5963 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005964 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005965 switch (CSM) {
5966 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00005967 if (Inherited)
5968 break;
Richard Smith4086a132012-06-10 07:07:24 +00005969 // Since default constructor lookup is essentially trivial (and cannot
5970 // involve, for instance, template instantiation), we compute whether a
5971 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5972 //
5973 // This is important for performance; we need to know whether the default
5974 // constructor is constexpr to determine whether the type is a literal type.
5975 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5976
Richard Smithb5800092012-06-10 05:43:50 +00005977 case Sema::CXXCopyConstructor:
5978 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005979 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005980 break;
5981
5982 case Sema::CXXCopyAssignment:
5983 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005984 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005985 return false;
5986 // In C++1y, we need to perform overload resolution.
5987 Ctor = false;
5988 break;
5989
Richard Smithb5800092012-06-10 05:43:50 +00005990 case Sema::CXXDestructor:
5991 case Sema::CXXInvalid:
5992 return false;
5993 }
5994
5995 // -- if the class is a non-empty union, or for each non-empty anonymous
5996 // union member of a non-union class, exactly one non-static data member
5997 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005998 //
5999 // If we squint, this is guaranteed, since exactly one non-static data member
6000 // will be initialized (if the constructor isn't deleted), we just don't know
6001 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006002 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006003 return CSM == Sema::CXXDefaultConstructor
6004 ? ClassDecl->hasInClassInitializer() ||
6005 !ClassDecl->hasVariantMembers()
6006 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006007
6008 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006009 if (Ctor && ClassDecl->getNumVBases())
6010 return false;
6011
6012 // C++1y [class.copy]p26:
6013 // -- [the class] is a literal type, and
6014 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006015 return false;
6016
6017 // -- every constructor involved in initializing [...] base class
6018 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006019 // -- the assignment operator selected to copy/move each direct base
6020 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006021 for (const auto &B : ClassDecl->bases()) {
6022 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006023 if (!BaseType) continue;
6024
6025 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006026 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6027 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006028 return false;
6029 }
6030
6031 // -- every constructor involved in initializing non-static data members
6032 // [...] shall be a constexpr constructor;
6033 // -- every non-static data member and base class sub-object shall be
6034 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006035 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006036 // thereof), the assignment operator selected to copy/move that member is
6037 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006038 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006039 if (F->isInvalidDecl())
6040 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006041 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6042 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006043 QualType BaseType = S.Context.getBaseElementType(F->getType());
6044 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006045 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006046 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6047 BaseType.getCVRQualifiers(),
6048 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006049 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006050 } else if (CSM == Sema::CXXDefaultConstructor) {
6051 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006052 }
6053 }
6054
6055 // All OK, it's constexpr!
6056 return true;
6057}
6058
Richard Smithd3b5c9082012-07-27 04:22:15 +00006059static Sema::ImplicitExceptionSpecification
6060computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6061 switch (S.getSpecialMember(MD)) {
6062 case Sema::CXXDefaultConstructor:
6063 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6064 case Sema::CXXCopyConstructor:
6065 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6066 case Sema::CXXCopyAssignment:
6067 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6068 case Sema::CXXMoveConstructor:
6069 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6070 case Sema::CXXMoveAssignment:
6071 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6072 case Sema::CXXDestructor:
6073 return S.ComputeDefaultedDtorExceptionSpec(MD);
6074 case Sema::CXXInvalid:
6075 break;
6076 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00006077 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6078 "only special members have implicit exception specs");
Richard Smith5179eb72016-06-28 19:03:57 +00006079 return S.ComputeInheritingCtorExceptionSpec(Loc,
6080 cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00006081}
6082
Reid Kleckner78af0702013-08-27 23:08:25 +00006083static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6084 CXXMethodDecl *MD) {
6085 FunctionProtoType::ExtProtoInfo EPI;
6086
6087 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006088 EPI.ExceptionSpec.Type = EST_Unevaluated;
6089 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006090
6091 // Set the calling convention to the default for C++ instance methods.
6092 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6093 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6094 /*IsCXXMethod=*/true));
6095 return EPI;
6096}
6097
Richard Smithd3b5c9082012-07-27 04:22:15 +00006098void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6099 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6100 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6101 return;
6102
Richard Smith7f782272012-07-30 23:48:14 +00006103 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00006104 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006105
Richard Smith7f782272012-07-30 23:48:14 +00006106 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006107 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006108
6109 // A user-provided destructor can be defined outside the class. When that
6110 // happens, be sure to update the exception specification on both
6111 // declarations.
6112 const FunctionProtoType *CanonicalFPT =
6113 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6114 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006115 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006116}
6117
Richard Smithb9e90b12012-05-15 04:39:51 +00006118void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6119 CXXRecordDecl *RD = MD->getParent();
6120 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006121
Richard Smithb9e90b12012-05-15 04:39:51 +00006122 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6123 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006124
6125 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006126 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006127 bool First = MD == MD->getCanonicalDecl();
6128
6129 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006130
6131 // C++11 [dcl.fct.def.default]p1:
6132 // A function that is explicitly defaulted shall
6133 // -- be a special member function (checked elsewhere),
6134 // -- have the same type (except for ref-qualifiers, and except that a
6135 // copy operation can take a non-const reference) as an implicit
6136 // declaration, and
6137 // -- not have default arguments.
6138 unsigned ExpectedParams = 1;
6139 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6140 ExpectedParams = 0;
6141 if (MD->getNumParams() != ExpectedParams) {
6142 // This also checks for default arguments: a copy or move constructor with a
6143 // default argument is classified as a default constructor, and assignment
6144 // operations and destructors can't have default arguments.
6145 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6146 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006147 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006148 } else if (MD->isVariadic()) {
6149 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6150 << CSM << MD->getSourceRange();
6151 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006152 }
6153
Richard Smithb9e90b12012-05-15 04:39:51 +00006154 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006155
Richard Smithb5800092012-06-10 05:43:50 +00006156 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006157 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006158 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006159 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006160 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006161
Richard Smithb9e90b12012-05-15 04:39:51 +00006162 QualType ReturnType = Context.VoidTy;
6163 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6164 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006165 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006166 QualType ExpectedReturnType =
6167 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6168 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6169 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6170 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6171 HadError = true;
6172 }
6173
6174 // A defaulted special member cannot have cv-qualifiers.
6175 if (Type->getTypeQuals()) {
6176 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006177 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006178 HadError = true;
6179 }
6180 }
6181
6182 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006183 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006184 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006185 if (ExpectedParams && ArgType->isReferenceType()) {
6186 // Argument must be reference to possibly-const T.
6187 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006188 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006189
6190 if (ReferentType.isVolatileQualified()) {
6191 Diag(MD->getLocation(),
6192 diag::err_defaulted_special_member_volatile_param) << CSM;
6193 HadError = true;
6194 }
6195
Richard Smithb5800092012-06-10 05:43:50 +00006196 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006197 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6198 Diag(MD->getLocation(),
6199 diag::err_defaulted_special_member_copy_const_param)
6200 << (CSM == CXXCopyAssignment);
6201 // FIXME: Explain why this special member can't be const.
6202 } else {
6203 Diag(MD->getLocation(),
6204 diag::err_defaulted_special_member_move_const_param)
6205 << (CSM == CXXMoveAssignment);
6206 }
6207 HadError = true;
6208 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006209 } else if (ExpectedParams) {
6210 // A copy assignment operator can take its argument by value, but a
6211 // defaulted one cannot.
6212 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006213 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006214 HadError = true;
6215 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006216
Richard Smithcc36f692011-12-22 02:22:31 +00006217 // C++11 [dcl.fct.def.default]p2:
6218 // An explicitly-defaulted function may be declared constexpr only if it
6219 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006220 // Do not apply this rule to members of class templates, since core issue 1358
6221 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006222 // functions which cannot be constexpr (for non-constructors in C++11 and for
6223 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006224 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6225 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006226 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006227 : isa<CXXConstructorDecl>(MD)) &&
6228 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006229 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6230 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006231 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006232 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006233 }
Richard Smithbd305122012-12-11 01:14:52 +00006234
Richard Smithcc36f692011-12-22 02:22:31 +00006235 // and may have an explicit exception-specification only if it is compatible
6236 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006237 if (Type->hasExceptionSpec()) {
6238 // Delay the check if this is the first declaration of the special member,
6239 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006240 if (First) {
6241 // If the exception specification needs to be instantiated, do so now,
6242 // before we clobber it with an EST_Unevaluated specification below.
6243 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6244 InstantiateExceptionSpec(MD->getLocStart(), MD);
6245 Type = MD->getType()->getAs<FunctionProtoType>();
6246 }
Richard Smithbd305122012-12-11 01:14:52 +00006247 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006248 } else
Richard Smithbd305122012-12-11 01:14:52 +00006249 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6250 }
Richard Smithcc36f692011-12-22 02:22:31 +00006251
6252 // If a function is explicitly defaulted on its first declaration,
6253 if (First) {
6254 // -- it is implicitly considered to be constexpr if the implicit
6255 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006256 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006257
Richard Smithb9e90b12012-05-15 04:39:51 +00006258 // -- it is implicitly considered to have the same exception-specification
6259 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006260 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006261 EPI.ExceptionSpec.Type = EST_Unevaluated;
6262 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006263 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006264 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006265 ExpectedParams),
6266 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006267 }
6268
Richard Smithb9e90b12012-05-15 04:39:51 +00006269 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006270 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006271 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006272 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006273 // C++11 [dcl.fct.def.default]p4:
6274 // [For a] user-provided explicitly-defaulted function [...] if such a
6275 // function is implicitly defined as deleted, the program is ill-formed.
6276 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006277 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006278 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006279 }
6280 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006281
Richard Smithb9e90b12012-05-15 04:39:51 +00006282 if (HadError)
6283 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006284}
6285
Richard Smithbd305122012-12-11 01:14:52 +00006286/// Check whether the exception specification provided for an
6287/// explicitly-defaulted special member matches the exception specification
6288/// that would have been generated for an implicit special member, per
6289/// C++11 [dcl.fct.def.default]p2.
6290void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6291 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006292 // If the exception specification was explicitly specified but hadn't been
6293 // parsed when the method was defaulted, grab it now.
6294 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6295 SpecifiedType =
6296 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6297
Richard Smithbd305122012-12-11 01:14:52 +00006298 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006299 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6300 /*IsCXXMethod=*/true);
6301 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00006302 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6303 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006304 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006305 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006306
6307 // Ensure that it matches.
6308 CheckEquivalentExceptionSpec(
6309 PDiag(diag::err_incorrect_defaulted_exception_spec)
6310 << getSpecialMember(MD), PDiag(),
6311 ImplicitType, SourceLocation(),
6312 SpecifiedType, MD->getLocation());
6313}
6314
Alp Tokerae3a9442013-10-18 05:54:19 +00006315void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006316 decltype(DelayedExceptionSpecChecks) Checks;
6317 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006318
Richard Smith88f45492014-11-22 03:09:05 +00006319 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006320 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6321
6322 // Perform any deferred checking of exception specifications for virtual
6323 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006324 for (auto &Check : Checks)
6325 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006326
6327 // Check that any explicitly-defaulted methods have exception specifications
6328 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006329 for (auto &Spec : Specs)
6330 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006331}
6332
Richard Smithd951a1d2012-02-18 02:02:13 +00006333namespace {
6334struct SpecialMemberDeletionInfo {
6335 Sema &S;
6336 CXXMethodDecl *MD;
6337 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006338 Sema::InheritedConstructorInfo *ICI;
Richard Smith852265f2012-03-30 20:53:28 +00006339 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006340
6341 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00006342 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00006343 SourceLocation Loc;
6344
6345 bool AllFieldsAreConst;
6346
6347 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006348 Sema::CXXSpecialMember CSM,
6349 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6350 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6351 IsConstructor(false), IsAssignment(false), IsMove(false),
6352 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006353 switch (CSM) {
6354 case Sema::CXXDefaultConstructor:
6355 case Sema::CXXCopyConstructor:
6356 IsConstructor = true;
6357 break;
6358 case Sema::CXXMoveConstructor:
6359 IsConstructor = true;
6360 IsMove = true;
6361 break;
6362 case Sema::CXXCopyAssignment:
6363 IsAssignment = true;
6364 break;
6365 case Sema::CXXMoveAssignment:
6366 IsAssignment = true;
6367 IsMove = true;
6368 break;
6369 case Sema::CXXDestructor:
6370 break;
6371 case Sema::CXXInvalid:
6372 llvm_unreachable("invalid special member kind");
6373 }
6374
6375 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00006376 if (const ReferenceType *RT =
6377 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6378 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00006379 }
6380 }
6381
6382 bool inUnion() const { return MD->getParent()->isUnion(); }
6383
Richard Smith80a47022016-06-29 01:10:27 +00006384 Sema::CXXSpecialMember getEffectiveCSM() {
6385 return ICI ? Sema::CXXInvalid : CSM;
6386 }
6387
Richard Smithd951a1d2012-02-18 02:02:13 +00006388 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00006389 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00006390 unsigned Quals, bool IsMutable) {
6391 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6392 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00006393 }
6394
Richard Smith852265f2012-03-30 20:53:28 +00006395 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00006396
Richard Smith852265f2012-03-30 20:53:28 +00006397 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006398 bool shouldDeleteForField(FieldDecl *FD);
6399 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006400
Richard Smithaf136f82012-07-18 03:51:16 +00006401 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6402 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006403 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6404 Sema::SpecialMemberOverloadResult *SMOR,
6405 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006406
6407 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006408};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006409}
Richard Smithd951a1d2012-02-18 02:02:13 +00006410
John McCalld4274212012-04-09 20:53:23 +00006411/// Is the given special member inaccessible when used on the given
6412/// sub-object.
6413bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6414 CXXMethodDecl *target) {
6415 /// If we're operating on a base class, the object type is the
6416 /// type of this special member.
6417 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006418 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006419 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6420 objectTy = S.Context.getTypeDeclType(MD->getParent());
6421 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6422
6423 // If we're operating on a field, the object type is the type of the field.
6424 } else {
6425 objectTy = S.Context.getTypeDeclType(target->getParent());
6426 }
6427
6428 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6429}
6430
Richard Smith852265f2012-03-30 20:53:28 +00006431/// Check whether we should delete a special member due to the implicit
6432/// definition containing a call to a special member of a subobject.
6433bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6434 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6435 bool IsDtorCallInCtor) {
6436 CXXMethodDecl *Decl = SMOR->getMethod();
6437 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6438
6439 int DiagKind = -1;
6440
6441 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6442 DiagKind = !Decl ? 0 : 1;
6443 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6444 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006445 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006446 DiagKind = 3;
6447 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6448 !Decl->isTrivial()) {
6449 // A member of a union must have a trivial corresponding special member.
6450 // As a weird special case, a destructor call from a union's constructor
6451 // must be accessible and non-deleted, but need not be trivial. Such a
6452 // destructor is never actually called, but is semantically checked as
6453 // if it were.
6454 DiagKind = 4;
6455 }
6456
6457 if (DiagKind == -1)
6458 return false;
6459
6460 if (Diagnose) {
6461 if (Field) {
6462 S.Diag(Field->getLocation(),
6463 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006464 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006465 << Field << DiagKind << IsDtorCallInCtor;
6466 } else {
6467 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6468 S.Diag(Base->getLocStart(),
6469 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006470 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006471 << Base->getType() << DiagKind << IsDtorCallInCtor;
6472 }
6473
6474 if (DiagKind == 1)
6475 S.NoteDeletedFunction(Decl);
6476 // FIXME: Explain inaccessibility if DiagKind == 3.
6477 }
6478
6479 return true;
6480}
6481
Richard Smith921bd202012-02-26 09:11:52 +00006482/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006483/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006484bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006485 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006486 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006487 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006488
6489 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006490 // -- any direct or virtual base class, or non-static data member with no
6491 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006492 // either M has no default constructor or overload resolution as applied
6493 // to M's default constructor results in an ambiguity or in a function
6494 // that is deleted or inaccessible
6495 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6496 // -- a direct or virtual base class B that cannot be copied/moved because
6497 // overload resolution, as applied to B's corresponding special member,
6498 // results in an ambiguity or a function that is deleted or inaccessible
6499 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006500 // C++11 [class.dtor]p5:
6501 // -- any direct or virtual base class [...] has a type with a destructor
6502 // that is deleted or inaccessible
6503 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006504 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006505 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6506 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006507 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006508
Richard Smith852265f2012-03-30 20:53:28 +00006509 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6510 // -- any direct or virtual base class or non-static data member has a
6511 // type with a destructor that is deleted or inaccessible
6512 if (IsConstructor) {
6513 Sema::SpecialMemberOverloadResult *SMOR =
6514 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6515 false, false, false, false, false);
6516 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6517 return true;
6518 }
6519
Richard Smith921bd202012-02-26 09:11:52 +00006520 return false;
6521}
6522
6523/// Check whether we should delete a special member function due to the class
6524/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006525bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006526 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006527 // If program is correct, BaseClass cannot be null, but if it is, the error
6528 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006529 if (!BaseClass)
6530 return false;
6531 // If we have an inheriting constructor, check whether we're calling an
6532 // inherited constructor instead of a default constructor.
6533 if (ICI) {
6534 assert(CSM == Sema::CXXDefaultConstructor);
6535 auto *BaseCtor =
6536 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6537 ->getInheritedConstructor()
6538 .getConstructor())
6539 .first;
6540 if (BaseCtor) {
6541 if (BaseCtor->isDeleted() && Diagnose) {
6542 S.Diag(Base->getLocStart(),
6543 diag::note_deleted_special_member_class_subobject)
6544 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6545 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6546 S.NoteDeletedFunction(BaseCtor);
6547 }
6548 return BaseCtor->isDeleted();
6549 }
6550 }
6551 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006552}
6553
6554/// Check whether we should delete a special member function due to the class
6555/// having a particular non-static data member.
6556bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6557 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6558 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6559
6560 if (CSM == Sema::CXXDefaultConstructor) {
6561 // For a default constructor, all references must be initialized in-class
6562 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006563 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6564 if (Diagnose)
6565 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006566 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006567 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006568 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006569 // C++11 [class.ctor]p5: any non-variant non-static data member of
6570 // const-qualified type (or array thereof) with no
6571 // brace-or-equal-initializer does not have a user-provided default
6572 // constructor.
6573 if (!inUnion() && FieldType.isConstQualified() &&
6574 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006575 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6576 if (Diagnose)
6577 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006578 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006579 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006580 }
6581
6582 if (inUnion() && !FieldType.isConstQualified())
6583 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006584 } else if (CSM == Sema::CXXCopyConstructor) {
6585 // For a copy constructor, data members must not be of rvalue reference
6586 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006587 if (FieldType->isRValueReferenceType()) {
6588 if (Diagnose)
6589 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6590 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006591 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006592 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006593 } else if (IsAssignment) {
6594 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006595 if (FieldType->isReferenceType()) {
6596 if (Diagnose)
6597 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6598 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006599 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006600 }
6601 if (!FieldRecord && FieldType.isConstQualified()) {
6602 // C++11 [class.copy]p23:
6603 // -- a non-static data member of const non-class type (or array thereof)
6604 if (Diagnose)
6605 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00006606 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006607 return true;
6608 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006609 }
6610
6611 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006612 // Some additional restrictions exist on the variant members.
6613 if (!inUnion() && FieldRecord->isUnion() &&
6614 FieldRecord->isAnonymousStructOrUnion()) {
6615 bool AllVariantFieldsAreConst = true;
6616
Richard Smith5704fe82012-03-29 19:00:10 +00006617 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006618 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006619 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006620
6621 if (!UnionFieldType.isConstQualified())
6622 AllVariantFieldsAreConst = false;
6623
Richard Smith921bd202012-02-26 09:11:52 +00006624 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6625 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006626 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006627 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006628 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006629 }
6630
6631 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006632 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006633 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006634 if (Diagnose)
6635 S.Diag(FieldRecord->getLocation(),
6636 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006637 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006638 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006639 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006640
Richard Smith5704fe82012-03-29 19:00:10 +00006641 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006642 // This is technically non-conformant, but sanity demands it.
6643 return false;
6644 }
6645
Richard Smithaf136f82012-07-18 03:51:16 +00006646 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6647 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006648 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006649 }
6650
6651 return false;
6652}
6653
6654/// C++11 [class.ctor] p5:
6655/// A defaulted default constructor for a class X is defined as deleted if
6656/// X is a union and all of its variant members are of const-qualified type.
6657bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006658 // This is a silly definition, because it gives an empty union a deleted
6659 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00006660 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006661 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006662 if (Diagnose)
6663 S.Diag(MD->getParent()->getLocation(),
6664 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006665 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006666 return true;
6667 }
6668 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006669}
6670
6671/// Determine whether a defaulted special member function should be defined as
6672/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6673/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006674bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006675 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006676 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006677 if (MD->isInvalidDecl())
6678 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006679 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006680 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006681 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006682 return false;
6683
Richard Smithd951a1d2012-02-18 02:02:13 +00006684 // C++11 [expr.lambda.prim]p19:
6685 // The closure type associated with a lambda-expression has a
6686 // deleted (8.4.3) default constructor and a deleted copy
6687 // assignment operator.
6688 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006689 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6690 if (Diagnose)
6691 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006692 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006693 }
6694
Richard Smith6f1e2c62012-04-02 20:59:25 +00006695 // For an anonymous struct or union, the copy and assignment special members
6696 // will never be used, so skip the check. For an anonymous union declared at
6697 // namespace scope, the constructor and destructor are used.
6698 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6699 RD->isAnonymousStructOrUnion())
6700 return false;
6701
Richard Smith852265f2012-03-30 20:53:28 +00006702 // C++11 [class.copy]p7, p18:
6703 // If the class definition declares a move constructor or move assignment
6704 // operator, an implicitly declared copy constructor or copy assignment
6705 // operator is defined as deleted.
6706 if (MD->isImplicit() &&
6707 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006708 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006709
6710 // In Microsoft mode, a user-declared move only causes the deletion of the
6711 // corresponding copy operation, not both copy operations.
6712 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00006713 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006714 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006715
6716 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006717 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006718 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006719 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006720 break;
6721 }
6722 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006723 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006724 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00006725 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006726 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006727
6728 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006729 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006730 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006731 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006732 break;
6733 }
6734 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006735 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006736 }
6737
6738 if (UserDeclaredMove) {
6739 Diag(UserDeclaredMove->getLocation(),
6740 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006741 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006742 << UserDeclaredMove->isMoveAssignmentOperator();
6743 return true;
6744 }
6745 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006746
Richard Smith6f1e2c62012-04-02 20:59:25 +00006747 // Do access control from the special member function
6748 ContextRAII MethodContext(*this, MD);
6749
Richard Smith921bd202012-02-26 09:11:52 +00006750 // C++11 [class.dtor]p5:
6751 // -- for a virtual destructor, lookup of the non-array deallocation function
6752 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006753 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006754 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006755 DeclarationName Name =
6756 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6757 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00006758 OperatorDelete, false)) {
6759 if (Diagnose)
6760 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006761 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006762 }
Richard Smith921bd202012-02-26 09:11:52 +00006763 }
6764
Richard Smith80a47022016-06-29 01:10:27 +00006765 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006766
Aaron Ballman574705e2014-03-13 15:41:46 +00006767 for (auto &BI : RD->bases())
Richard Smith0786d5b2016-08-31 20:37:39 +00006768 if ((SMI.IsAssignment || !BI.isVirtual()) &&
Aaron Ballman574705e2014-03-13 15:41:46 +00006769 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00006770 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006771
Richard Smithd1627032013-07-22 18:06:23 +00006772 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smith0786d5b2016-08-31 20:37:39 +00006773 // classes, since we are not going to construct them. For assignment
6774 // operators, we only assign (and thus only consider) direct bases.
6775 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006776 for (auto &BI : RD->vbases())
6777 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00006778 return true;
6779 }
Alexis Huntea6f0322011-05-11 22:34:38 +00006780
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006781 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00006782 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006783 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00006784 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006785
Richard Smithd951a1d2012-02-18 02:02:13 +00006786 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006787 return true;
6788
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006789 if (getLangOpts().CUDA) {
6790 // We should delete the special member in CUDA mode if target inference
6791 // failed.
6792 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6793 Diagnose);
6794 }
6795
Alexis Huntea6f0322011-05-11 22:34:38 +00006796 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006797}
6798
Richard Smith92f241f2012-12-08 02:53:02 +00006799/// Perform lookup for a special member of the specified kind, and determine
6800/// whether it is trivial. If the triviality can be determined without the
6801/// lookup, skip it. This is intended for use when determining whether a
6802/// special member of a containing object is trivial, and thus does not ever
6803/// perform overload resolution for default constructors.
6804///
6805/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6806/// member that was most likely to be intended to be trivial, if any.
6807static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6808 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006809 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006810 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006811 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006812
6813 switch (CSM) {
6814 case Sema::CXXInvalid:
6815 llvm_unreachable("not a special member");
6816
6817 case Sema::CXXDefaultConstructor:
6818 // C++11 [class.ctor]p5:
6819 // A default constructor is trivial if:
6820 // - all the [direct subobjects] have trivial default constructors
6821 //
6822 // Note, no overload resolution is performed in this case.
6823 if (RD->hasTrivialDefaultConstructor())
6824 return true;
6825
6826 if (Selected) {
6827 // If there's a default constructor which could have been trivial, dig it
6828 // out. Otherwise, if there's any user-provided default constructor, point
6829 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006830 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006831 if (RD->needsImplicitDefaultConstructor())
6832 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006833 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006834 if (!CI->isDefaultConstructor())
6835 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006836 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006837 if (!DefCtor->isUserProvided())
6838 break;
6839 }
6840
6841 *Selected = DefCtor;
6842 }
6843
6844 return false;
6845
6846 case Sema::CXXDestructor:
6847 // C++11 [class.dtor]p5:
6848 // A destructor is trivial if:
6849 // - all the direct [subobjects] have trivial destructors
6850 if (RD->hasTrivialDestructor())
6851 return true;
6852
6853 if (Selected) {
6854 if (RD->needsImplicitDestructor())
6855 S.DeclareImplicitDestructor(RD);
6856 *Selected = RD->getDestructor();
6857 }
6858
6859 return false;
6860
6861 case Sema::CXXCopyConstructor:
6862 // C++11 [class.copy]p12:
6863 // A copy constructor is trivial if:
6864 // - the constructor selected to copy each direct [subobject] is trivial
6865 if (RD->hasTrivialCopyConstructor()) {
6866 if (Quals == Qualifiers::Const)
6867 // We must either select the trivial copy constructor or reach an
6868 // ambiguity; no need to actually perform overload resolution.
6869 return true;
6870 } else if (!Selected) {
6871 return false;
6872 }
6873 // In C++98, we are not supposed to perform overload resolution here, but we
6874 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6875 // cases like B as having a non-trivial copy constructor:
6876 // struct A { template<typename T> A(T&); };
6877 // struct B { mutable A a; };
6878 goto NeedOverloadResolution;
6879
6880 case Sema::CXXCopyAssignment:
6881 // C++11 [class.copy]p25:
6882 // A copy assignment operator is trivial if:
6883 // - the assignment operator selected to copy each direct [subobject] is
6884 // trivial
6885 if (RD->hasTrivialCopyAssignment()) {
6886 if (Quals == Qualifiers::Const)
6887 return true;
6888 } else if (!Selected) {
6889 return false;
6890 }
6891 // In C++98, we are not supposed to perform overload resolution here, but we
6892 // treat that as a language defect.
6893 goto NeedOverloadResolution;
6894
6895 case Sema::CXXMoveConstructor:
6896 case Sema::CXXMoveAssignment:
6897 NeedOverloadResolution:
6898 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006899 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006900
6901 // The standard doesn't describe how to behave if the lookup is ambiguous.
6902 // We treat it as not making the member non-trivial, just like the standard
6903 // mandates for the default constructor. This should rarely matter, because
6904 // the member will also be deleted.
6905 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6906 return true;
6907
6908 if (!SMOR->getMethod()) {
6909 assert(SMOR->getKind() ==
6910 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6911 return false;
6912 }
6913
6914 // We deliberately don't check if we found a deleted special member. We're
6915 // not supposed to!
6916 if (Selected)
6917 *Selected = SMOR->getMethod();
6918 return SMOR->getMethod()->isTrivial();
6919 }
6920
6921 llvm_unreachable("unknown special method kind");
6922}
6923
Benjamin Kramer3e350262013-02-15 12:30:38 +00006924static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006925 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006926 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006927 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006928
6929 // Look for constructor templates.
6930 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6931 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6932 if (CXXConstructorDecl *CD =
6933 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6934 return CD;
6935 }
6936
Craig Topperc3ec1492014-05-26 06:22:03 +00006937 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006938}
6939
6940/// The kind of subobject we are checking for triviality. The values of this
6941/// enumeration are used in diagnostics.
6942enum TrivialSubobjectKind {
6943 /// The subobject is a base class.
6944 TSK_BaseClass,
6945 /// The subobject is a non-static data member.
6946 TSK_Field,
6947 /// The object is actually the complete object.
6948 TSK_CompleteObject
6949};
6950
6951/// Check whether the special member selected for a given type would be trivial.
6952static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006953 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006954 Sema::CXXSpecialMember CSM,
6955 TrivialSubobjectKind Kind,
6956 bool Diagnose) {
6957 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6958 if (!SubRD)
6959 return true;
6960
6961 CXXMethodDecl *Selected;
6962 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006963 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006964 return true;
6965
6966 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006967 if (ConstRHS)
6968 SubType.addConst();
6969
Richard Smith92f241f2012-12-08 02:53:02 +00006970 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6971 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6972 << Kind << SubType.getUnqualifiedType();
6973 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6974 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6975 } else if (!Selected)
6976 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6977 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6978 else if (Selected->isUserProvided()) {
6979 if (Kind == TSK_CompleteObject)
6980 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6981 << Kind << SubType.getUnqualifiedType() << CSM;
6982 else {
6983 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6984 << Kind << SubType.getUnqualifiedType() << CSM;
6985 S.Diag(Selected->getLocation(), diag::note_declared_at);
6986 }
6987 } else {
6988 if (Kind != TSK_CompleteObject)
6989 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6990 << Kind << SubType.getUnqualifiedType() << CSM;
6991
6992 // Explain why the defaulted or deleted special member isn't trivial.
6993 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6994 }
6995 }
6996
6997 return false;
6998}
6999
7000/// Check whether the members of a class type allow a special member to be
7001/// trivial.
7002static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7003 Sema::CXXSpecialMember CSM,
7004 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007005 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007006 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7007 continue;
7008
7009 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7010
7011 // Pretend anonymous struct or union members are members of this class.
7012 if (FI->isAnonymousStructOrUnion()) {
7013 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7014 CSM, ConstArg, Diagnose))
7015 return false;
7016 continue;
7017 }
7018
7019 // C++11 [class.ctor]p5:
7020 // A default constructor is trivial if [...]
7021 // -- no non-static data member of its class has a
7022 // brace-or-equal-initializer
7023 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7024 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007025 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007026 return false;
7027 }
7028
7029 // Objective C ARC 4.3.5:
7030 // [...] nontrivally ownership-qualified types are [...] not trivially
7031 // default constructible, copy constructible, move constructible, copy
7032 // assignable, move assignable, or destructible [...]
7033 if (S.getLangOpts().ObjCAutoRefCount &&
7034 FieldType.hasNonTrivialObjCLifetime()) {
7035 if (Diagnose)
7036 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7037 << RD << FieldType.getObjCLifetime();
7038 return false;
7039 }
7040
Richard Smith41c35d62013-11-27 03:39:20 +00007041 bool ConstRHS = ConstArg && !FI->isMutable();
7042 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7043 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007044 return false;
7045 }
7046
7047 return true;
7048}
7049
7050/// Diagnose why the specified class does not have a trivial special member of
7051/// the given kind.
7052void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7053 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007054
Richard Smith41c35d62013-11-27 03:39:20 +00007055 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7056 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007057 TSK_CompleteObject, /*Diagnose*/true);
7058}
7059
7060/// Determine whether a defaulted or deleted special member function is trivial,
7061/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7062/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7063bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7064 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007065 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7066
7067 CXXRecordDecl *RD = MD->getParent();
7068
7069 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007070
Richard Smith2002bfe2013-11-04 02:02:27 +00007071 // C++11 [class.copy]p12, p25: [DR1593]
7072 // A [special member] is trivial if [...] its parameter-type-list is
7073 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007074 switch (CSM) {
7075 case CXXDefaultConstructor:
7076 case CXXDestructor:
7077 // Trivial default constructors and destructors cannot have parameters.
7078 break;
7079
7080 case CXXCopyConstructor:
7081 case CXXCopyAssignment: {
7082 // Trivial copy operations always have const, non-volatile parameter types.
7083 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007084 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007085 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7086 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7087 if (Diagnose)
7088 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7089 << Param0->getSourceRange() << Param0->getType()
7090 << Context.getLValueReferenceType(
7091 Context.getRecordType(RD).withConst());
7092 return false;
7093 }
7094 break;
7095 }
7096
7097 case CXXMoveConstructor:
7098 case CXXMoveAssignment: {
7099 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007100 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007101 const RValueReferenceType *RT =
7102 Param0->getType()->getAs<RValueReferenceType>();
7103 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7104 if (Diagnose)
7105 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7106 << Param0->getSourceRange() << Param0->getType()
7107 << Context.getRValueReferenceType(Context.getRecordType(RD));
7108 return false;
7109 }
7110 break;
7111 }
7112
7113 case CXXInvalid:
7114 llvm_unreachable("not a special member");
7115 }
7116
Richard Smith92f241f2012-12-08 02:53:02 +00007117 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7118 if (Diagnose)
7119 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7120 diag::note_nontrivial_default_arg)
7121 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7122 return false;
7123 }
7124 if (MD->isVariadic()) {
7125 if (Diagnose)
7126 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7127 return false;
7128 }
7129
7130 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7131 // A copy/move [constructor or assignment operator] is trivial if
7132 // -- the [member] selected to copy/move each direct base class subobject
7133 // is trivial
7134 //
7135 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7136 // A [default constructor or destructor] is trivial if
7137 // -- all the direct base classes have trivial [default constructors or
7138 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007139 for (const auto &BI : RD->bases())
7140 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007141 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007142 return false;
7143
7144 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7145 // A copy/move [constructor or assignment operator] for a class X is
7146 // trivial if
7147 // -- for each non-static data member of X that is of class type (or array
7148 // thereof), the constructor selected to copy/move that member is
7149 // trivial
7150 //
7151 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7152 // A [default constructor or destructor] is trivial if
7153 // -- for all of the non-static data members of its class that are of class
7154 // type (or array thereof), each such class has a trivial [default
7155 // constructor or destructor]
7156 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7157 return false;
7158
7159 // C++11 [class.dtor]p5:
7160 // A destructor is trivial if [...]
7161 // -- the destructor is not virtual
7162 if (CSM == CXXDestructor && MD->isVirtual()) {
7163 if (Diagnose)
7164 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7165 return false;
7166 }
7167
7168 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7169 // A [special member] for class X is trivial if [...]
7170 // -- class X has no virtual functions and no virtual base classes
7171 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7172 if (!Diagnose)
7173 return false;
7174
7175 if (RD->getNumVBases()) {
7176 // Check for virtual bases. We already know that the corresponding
7177 // member in all bases is trivial, so vbases must all be direct.
7178 CXXBaseSpecifier &BS = *RD->vbases_begin();
7179 assert(BS.isVirtual());
7180 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7181 return false;
7182 }
7183
7184 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007185 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007186 if (MI->isVirtual()) {
7187 SourceLocation MLoc = MI->getLocStart();
7188 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7189 return false;
7190 }
7191 }
7192
7193 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7194 }
7195
7196 // Looks like it's trivial!
7197 return true;
7198}
7199
Benjamin Kramer024e6192011-03-04 13:12:48 +00007200namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007201struct FindHiddenVirtualMethod {
7202 Sema *S;
7203 CXXMethodDecl *Method;
7204 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7205 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007206
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007207private:
7208 /// Check whether any most overriden method from MD in Methods
7209 static bool CheckMostOverridenMethods(
7210 const CXXMethodDecl *MD,
7211 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7212 if (MD->size_overridden_methods() == 0)
7213 return Methods.count(MD->getCanonicalDecl());
7214 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7215 E = MD->end_overridden_methods();
7216 I != E; ++I)
7217 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007218 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007219 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007220 }
7221
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007222public:
7223 /// Member lookup function that determines whether a given C++
7224 /// method overloads virtual methods in a base class without overriding any,
7225 /// to be used with CXXRecordDecl::lookupInBases().
7226 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7227 RecordDecl *BaseRecord =
7228 Specifier->getType()->getAs<RecordType>()->getDecl();
7229
7230 DeclarationName Name = Method->getDeclName();
7231 assert(Name.getNameKind() == DeclarationName::Identifier);
7232
7233 bool foundSameNameMethod = false;
7234 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7235 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7236 Path.Decls = Path.Decls.slice(1)) {
7237 NamedDecl *D = Path.Decls.front();
7238 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7239 MD = MD->getCanonicalDecl();
7240 foundSameNameMethod = true;
7241 // Interested only in hidden virtual methods.
7242 if (!MD->isVirtual())
7243 continue;
7244 // If the method we are checking overrides a method from its base
7245 // don't warn about the other overloaded methods. Clang deviates from
7246 // GCC by only diagnosing overloads of inherited virtual functions that
7247 // do not override any other virtual functions in the base. GCC's
7248 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7249 // function from a base class. These cases may be better served by a
7250 // warning (not specific to virtual functions) on call sites when the
7251 // call would select a different function from the base class, were it
7252 // visible.
7253 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7254 if (!S->IsOverload(Method, MD, false))
7255 return true;
7256 // Collect the overload only if its hidden.
7257 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7258 overloadedMethods.push_back(MD);
7259 }
7260 }
7261
7262 if (foundSameNameMethod)
7263 OverloadedMethods.append(overloadedMethods.begin(),
7264 overloadedMethods.end());
7265 return foundSameNameMethod;
7266 }
7267};
7268} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007269
David Blaikie282c92a2012-10-19 00:53:08 +00007270/// \brief Add the most overriden methods from MD to Methods
7271static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007272 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007273 if (MD->size_overridden_methods() == 0)
7274 Methods.insert(MD->getCanonicalDecl());
7275 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7276 E = MD->end_overridden_methods();
7277 I != E; ++I)
7278 AddMostOverridenMethods(*I, Methods);
7279}
7280
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007281/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007282/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007283void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7284 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007285 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007286 return;
7287
7288 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7289 /*bool RecordPaths=*/false,
7290 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007291 FindHiddenVirtualMethod FHVM;
7292 FHVM.Method = MD;
7293 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007294
7295 // Keep the base methods that were overriden or introduced in the subclass
7296 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007297 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007298 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7299 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7300 NamedDecl *ND = *I;
7301 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007302 ND = shad->getTargetDecl();
7303 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007304 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007305 }
7306
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007307 if (DC->lookupInBases(FHVM, Paths))
7308 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007309}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007310
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007311void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7312 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7313 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7314 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7315 PartialDiagnostic PD = PDiag(
7316 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7317 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7318 Diag(overloadedMD->getLocation(), PD);
7319 }
7320}
7321
7322/// \brief Diagnose methods which overload virtual methods in a base class
7323/// without overriding any.
7324void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7325 if (MD->isInvalidDecl())
7326 return;
7327
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007328 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007329 return;
7330
7331 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7332 FindHiddenVirtualMethods(MD, OverloadedMethods);
7333 if (!OverloadedMethods.empty()) {
7334 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7335 << MD << (OverloadedMethods.size() > 1);
7336
7337 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007338 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007339}
7340
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007341void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007342 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007343 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007344 SourceLocation RBrac,
7345 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007346 if (!TagDecl)
7347 return;
Mike Stump11289f42009-09-09 15:08:12 +00007348
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007349 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007350
Rafael Espindola06e1b132012-07-12 04:32:30 +00007351 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7352 if (l->getKind() != AttributeList::AT_Visibility)
7353 continue;
7354 l->setInvalid();
7355 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7356 l->getName();
7357 }
7358
David Blaikie751c5582011-09-22 02:58:26 +00007359 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007360 // strict aliasing violation!
7361 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007362 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007363
Douglas Gregor0be31a22010-07-02 17:43:08 +00007364 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007365 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007366}
7367
Douglas Gregor05379422008-11-03 17:51:48 +00007368/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7369/// special functions, such as the default constructor, copy
7370/// constructor, or destructor, to the given C++ class (C++
7371/// [special]p1). This routine can only be executed just before the
7372/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007373void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007374 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007375 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007376
Richard Smith5179eb72016-06-28 19:03:57 +00007377 if (ClassDecl->hasInheritedConstructor())
7378 DeclareImplicitDefaultConstructor(ClassDecl);
7379 }
Richard Smith12e79312016-05-13 06:47:56 +00007380
Richard Smitha87b7662016-05-13 18:48:05 +00007381 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007382 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007383
Richard Smith6b02d462012-12-08 08:32:28 +00007384 // If the properties or semantics of the copy constructor couldn't be
7385 // determined while the class was being declared, force a declaration
7386 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007387 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7388 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007389 DeclareImplicitCopyConstructor(ClassDecl);
7390 }
7391
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007392 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007393 ++ASTContext::NumImplicitMoveConstructors;
7394
Richard Smith12e79312016-05-13 06:47:56 +00007395 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7396 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007397 DeclareImplicitMoveConstructor(ClassDecl);
7398 }
7399
Richard Smitha87b7662016-05-13 18:48:05 +00007400 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007401 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007402
7403 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007404 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007405 // it shows up in the right place in the vtable and that we diagnose
7406 // problems with the implicit exception specification.
7407 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007408 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7409 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007410 DeclareImplicitCopyAssignment(ClassDecl);
7411 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007412
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007413 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007414 ++ASTContext::NumImplicitMoveAssignmentOperators;
7415
7416 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007417 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007418 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7419 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007420 DeclareImplicitMoveAssignment(ClassDecl);
7421 }
7422
Richard Smitha87b7662016-05-13 18:48:05 +00007423 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007424 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007425
7426 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007427 // have to declare the destructor immediately. This ensures that, e.g., it
7428 // shows up in the right place in the vtable and that we diagnose problems
7429 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007430 if (ClassDecl->isDynamicClass() ||
7431 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007432 DeclareImplicitDestructor(ClassDecl);
7433 }
Douglas Gregor05379422008-11-03 17:51:48 +00007434}
7435
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007436unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007437 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007438 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007439
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007440 // The order of template parameters is not important here. All names
7441 // get added to the same scope.
7442 SmallVector<TemplateParameterList *, 4> ParameterLists;
7443
7444 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7445 D = TD->getTemplatedDecl();
7446
7447 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7448 ParameterLists.push_back(PSD->getTemplateParameters());
7449
7450 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7451 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7452 ParameterLists.push_back(DD->getTemplateParameterList(i));
7453
7454 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7455 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7456 ParameterLists.push_back(FTD->getTemplateParameters());
7457 }
7458 }
7459
7460 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7461 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7462 ParameterLists.push_back(TD->getTemplateParameterList(i));
7463
7464 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7465 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7466 ParameterLists.push_back(CTD->getTemplateParameters());
7467 }
7468 }
7469
7470 unsigned Count = 0;
7471 for (TemplateParameterList *Params : ParameterLists) {
7472 if (Params->size() > 0)
7473 // Ignore explicit specializations; they don't contribute to the template
7474 // depth.
7475 ++Count;
7476 for (NamedDecl *Param : *Params) {
7477 if (Param->getDeclName()) {
7478 S->AddDecl(Param);
7479 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007480 }
7481 }
7482 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007483
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007484 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007485}
7486
John McCall48871652010-08-21 09:40:31 +00007487void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007488 if (!RecordD) return;
7489 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007490 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007491 PushDeclContext(S, Record);
7492}
7493
John McCall48871652010-08-21 09:40:31 +00007494void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007495 if (!RecordD) return;
7496 PopDeclContext();
7497}
7498
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007499/// This is used to implement the constant expression evaluation part of the
7500/// attribute enable_if extension. There is nothing in standard C++ which would
7501/// require reentering parameters.
7502void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7503 if (!Param)
7504 return;
7505
7506 S->AddDecl(Param);
7507 if (Param->getDeclName())
7508 IdResolver.AddDecl(Param);
7509}
7510
Douglas Gregor4d87df52008-12-16 21:30:33 +00007511/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7512/// parsing a top-level (non-nested) C++ class, and we are now
7513/// parsing those parts of the given Method declaration that could
7514/// not be parsed earlier (C++ [class.mem]p2), such as default
7515/// arguments. This action should enter the scope of the given
7516/// Method declaration as if we had just parsed the qualified method
7517/// name. However, it should not bring the parameters into scope;
7518/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007519void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007520}
7521
7522/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7523/// C++ method declaration. We're (re-)introducing the given
7524/// function parameter into scope for use in parsing later parts of
7525/// the method declaration. For example, we could see an
7526/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007527void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007528 if (!ParamD)
7529 return;
Mike Stump11289f42009-09-09 15:08:12 +00007530
John McCall48871652010-08-21 09:40:31 +00007531 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007532
7533 // If this parameter has an unparsed default argument, clear it out
7534 // to make way for the parsed default argument.
7535 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007536 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007537
John McCall48871652010-08-21 09:40:31 +00007538 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007539 if (Param->getDeclName())
7540 IdResolver.AddDecl(Param);
7541}
7542
7543/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7544/// processing the delayed method declaration for Method. The method
7545/// declaration is now considered finished. There may be a separate
7546/// ActOnStartOfFunctionDef action later (not necessarily
7547/// immediately!) for this method, if it was also defined inside the
7548/// class body.
John McCall48871652010-08-21 09:40:31 +00007549void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007550 if (!MethodD)
7551 return;
Mike Stump11289f42009-09-09 15:08:12 +00007552
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007553 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007554
John McCall48871652010-08-21 09:40:31 +00007555 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007556
7557 // Now that we have our default arguments, check the constructor
7558 // again. It could produce additional diagnostics or affect whether
7559 // the class has implicitly-declared destructors, among other
7560 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007561 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7562 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007563
7564 // Check the default arguments, which we may have added.
7565 if (!Method->isInvalidDecl())
7566 CheckCXXDefaultArguments(Method);
7567}
7568
Douglas Gregor831c93f2008-11-05 20:51:48 +00007569/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007570/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007571/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007572/// emit diagnostics and set the invalid bit to true. In any case, the type
7573/// will be updated to reflect a well-formed type for the constructor and
7574/// returned.
7575QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007576 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007577 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007578
7579 // C++ [class.ctor]p3:
7580 // A constructor shall not be virtual (10.3) or static (9.4). A
7581 // constructor can be invoked for a const, volatile or const
7582 // volatile object. A constructor shall not be declared const,
7583 // volatile, or const volatile (9.3.2).
7584 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007585 if (!D.isInvalidType())
7586 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7587 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7588 << SourceRange(D.getIdentifierLoc());
7589 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007590 }
John McCall8e7d6562010-08-26 03:08:43 +00007591 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007592 if (!D.isInvalidType())
7593 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7594 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7595 << SourceRange(D.getIdentifierLoc());
7596 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007597 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007598 }
Mike Stump11289f42009-09-09 15:08:12 +00007599
David Majnemer03f705f2014-07-08 18:18:04 +00007600 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7601 diagnoseIgnoredQualifiers(
7602 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7603 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7604 D.getDeclSpec().getRestrictSpecLoc(),
7605 D.getDeclSpec().getAtomicSpecLoc());
7606 D.setInvalidType();
7607 }
7608
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007609 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007610 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007611 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007612 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7613 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007614 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007615 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7616 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007617 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007618 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7619 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007620 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007621 }
Mike Stump11289f42009-09-09 15:08:12 +00007622
Douglas Gregordb9d6642011-01-26 05:01:58 +00007623 // C++0x [class.ctor]p4:
7624 // A constructor shall not be declared with a ref-qualifier.
7625 if (FTI.hasRefQualifier()) {
7626 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7627 << FTI.RefQualifierIsLValueRef
7628 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7629 D.setInvalidType();
7630 }
7631
Douglas Gregor831c93f2008-11-05 20:51:48 +00007632 // Rebuild the function type "R" without any type qualifiers (in
7633 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007634 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007635 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007636 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007637 return R;
7638
7639 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7640 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007641 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007642
7643 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007644}
7645
Douglas Gregor4d87df52008-12-16 21:30:33 +00007646/// CheckConstructor - Checks a fully-formed constructor for
7647/// well-formedness, issuing any diagnostics required. Returns true if
7648/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007649void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007650 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007651 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7652 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007653 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007654
7655 // C++ [class.copy]p3:
7656 // A declaration of a constructor for a class X is ill-formed if
7657 // its first parameter is of type (optionally cv-qualified) X and
7658 // either there are no other parameters or else all other
7659 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007660 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007661 ((Constructor->getNumParams() == 1) ||
7662 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007663 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7664 Constructor->getTemplateSpecializationKind()
7665 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007666 QualType ParamType = Constructor->getParamDecl(0)->getType();
7667 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7668 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007669 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007670 const char *ConstRef
7671 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7672 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007673 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007674 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007675
7676 // FIXME: Rather that making the constructor invalid, we should endeavor
7677 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007678 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007679 }
7680 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007681}
7682
John McCalldeb646e2010-08-04 01:04:25 +00007683/// CheckDestructor - Checks a fully-formed destructor definition for
7684/// well-formedness, issuing any diagnostics required. Returns true
7685/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007686bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007687 CXXRecordDecl *RD = Destructor->getParent();
7688
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007689 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007690 SourceLocation Loc;
7691
7692 if (!Destructor->isImplicit())
7693 Loc = Destructor->getLocation();
7694 else
7695 Loc = RD->getLocation();
7696
7697 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00007698 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007699 DeclarationName Name =
7700 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00007701 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00007702 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00007703 // If there's no class-specific operator delete, look up the global
7704 // non-array delete.
7705 if (!OperatorDelete)
7706 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00007707
Eli Friedmanfa0df832012-02-02 03:46:19 +00007708 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00007709
7710 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00007711 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007712
7713 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007714}
7715
Douglas Gregor831c93f2008-11-05 20:51:48 +00007716/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7717/// the well-formednes of the destructor declarator @p D with type @p
7718/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007719/// emit diagnostics and set the declarator to invalid. Even if this happens,
7720/// will be updated to reflect a well-formed type for the destructor and
7721/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007722QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007723 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007724 // C++ [class.dtor]p1:
7725 // [...] A typedef-name that names a class is a class-name
7726 // (7.1.3); however, a typedef-name that names a class shall not
7727 // be used as the identifier in the declarator for a destructor
7728 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007729 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007730 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007731 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007732 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007733 else if (const TemplateSpecializationType *TST =
7734 DeclaratorType->getAs<TemplateSpecializationType>())
7735 if (TST->isTypeAlias())
7736 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7737 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007738
7739 // C++ [class.dtor]p2:
7740 // A destructor is used to destroy objects of its class type. A
7741 // destructor takes no parameters, and no return type can be
7742 // specified for it (not even void). The address of a destructor
7743 // shall not be taken. A destructor shall not be static. A
7744 // destructor can be invoked for a const, volatile or const
7745 // volatile object. A destructor shall not be declared const,
7746 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007747 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007748 if (!D.isInvalidType())
7749 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7750 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007751 << SourceRange(D.getIdentifierLoc())
7752 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7753
John McCall8e7d6562010-08-26 03:08:43 +00007754 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007755 }
David Majnemer03f705f2014-07-08 18:18:04 +00007756 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007757 // Destructors don't have return types, but the parser will
7758 // happily parse something like:
7759 //
7760 // class X {
7761 // float ~X();
7762 // };
7763 //
7764 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007765 if (D.getDeclSpec().hasTypeSpecifier())
7766 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7767 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7768 << SourceRange(D.getIdentifierLoc());
7769 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7770 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7771 SourceLocation(),
7772 D.getDeclSpec().getConstSpecLoc(),
7773 D.getDeclSpec().getVolatileSpecLoc(),
7774 D.getDeclSpec().getRestrictSpecLoc(),
7775 D.getDeclSpec().getAtomicSpecLoc());
7776 D.setInvalidType();
7777 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007778 }
Mike Stump11289f42009-09-09 15:08:12 +00007779
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007780 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007781 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007782 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007783 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7784 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007785 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007786 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7787 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007788 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007789 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7790 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007791 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007792 }
7793
Douglas Gregordb9d6642011-01-26 05:01:58 +00007794 // C++0x [class.dtor]p2:
7795 // A destructor shall not be declared with a ref-qualifier.
7796 if (FTI.hasRefQualifier()) {
7797 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7798 << FTI.RefQualifierIsLValueRef
7799 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7800 D.setInvalidType();
7801 }
7802
Douglas Gregor831c93f2008-11-05 20:51:48 +00007803 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007804 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007805 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7806
7807 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007808 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007809 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007810 }
7811
Mike Stump11289f42009-09-09 15:08:12 +00007812 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007813 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007814 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007815 D.setInvalidType();
7816 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007817
7818 // Rebuild the function type "R" without any type qualifiers or
7819 // parameters (in case any of the errors above fired) and with
7820 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007821 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007822 if (!D.isInvalidType())
7823 return R;
7824
Douglas Gregor95755162010-07-01 05:10:53 +00007825 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007826 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7827 EPI.Variadic = false;
7828 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007829 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007830 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007831}
7832
Craig Toppere335f252015-10-04 04:53:55 +00007833static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007834 if (Before.isInvalid())
7835 return;
7836 R.setBegin(Before.getBegin());
7837 if (R.getEnd().isInvalid())
7838 R.setEnd(Before.getEnd());
7839}
7840
Craig Toppere335f252015-10-04 04:53:55 +00007841static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007842 if (After.isInvalid())
7843 return;
7844 if (R.getBegin().isInvalid())
7845 R.setBegin(After.getBegin());
7846 R.setEnd(After.getEnd());
7847}
7848
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007849/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7850/// well-formednes of the conversion function declarator @p D with
7851/// type @p R. If there are any errors in the declarator, this routine
7852/// will emit diagnostics and return true. Otherwise, it will return
7853/// false. Either way, the type @p R will be updated to reflect a
7854/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007855void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007856 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007857 // C++ [class.conv.fct]p1:
7858 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007859 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007860 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007861 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007862 if (!D.isInvalidType())
7863 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007864 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7865 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007866 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007867 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007868 }
John McCall212fa2e2010-04-13 00:04:31 +00007869
Richard Smitha865a162014-12-19 02:07:47 +00007870 TypeSourceInfo *ConvTSI = nullptr;
7871 QualType ConvType =
7872 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007873
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007874 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007875 // Conversion functions don't have return types, but the parser will
7876 // happily parse something like:
7877 //
7878 // class X {
7879 // float operator bool();
7880 // };
7881 //
7882 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00007883 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7884 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7885 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00007886 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007887 }
7888
John McCall212fa2e2010-04-13 00:04:31 +00007889 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7890
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007891 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00007892 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007893 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7894
7895 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007896 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007897 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00007898 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007899 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007900 D.setInvalidType();
7901 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007902
John McCall212fa2e2010-04-13 00:04:31 +00007903 // Diagnose "&operator bool()" and other such nonsense. This
7904 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007905 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007906 bool NeedsTypedef = false;
7907 SourceRange Before, After;
7908
7909 // Walk the chunks and extract information on them for our diagnostic.
7910 bool PastFunctionChunk = false;
7911 for (auto &Chunk : D.type_objects()) {
7912 switch (Chunk.Kind) {
7913 case DeclaratorChunk::Function:
7914 if (!PastFunctionChunk) {
7915 if (Chunk.Fun.HasTrailingReturnType) {
7916 TypeSourceInfo *TRT = nullptr;
7917 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7918 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7919 }
7920 PastFunctionChunk = true;
7921 break;
7922 }
7923 // Fall through.
7924 case DeclaratorChunk::Array:
7925 NeedsTypedef = true;
7926 extendRight(After, Chunk.getSourceRange());
7927 break;
7928
7929 case DeclaratorChunk::Pointer:
7930 case DeclaratorChunk::BlockPointer:
7931 case DeclaratorChunk::Reference:
7932 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007933 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007934 extendLeft(Before, Chunk.getSourceRange());
7935 break;
7936
7937 case DeclaratorChunk::Paren:
7938 extendLeft(Before, Chunk.Loc);
7939 extendRight(After, Chunk.EndLoc);
7940 break;
7941 }
7942 }
7943
7944 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7945 After.isValid() ? After.getBegin() :
7946 D.getIdentifierLoc();
7947 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7948 DB << Before << After;
7949
7950 if (!NeedsTypedef) {
7951 DB << /*don't need a typedef*/0;
7952
7953 // If we can provide a correct fix-it hint, do so.
7954 if (After.isInvalid() && ConvTSI) {
7955 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007956 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007957 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7958 << FixItHint::CreateInsertionFromRange(
7959 InsertLoc, CharSourceRange::getTokenRange(Before))
7960 << FixItHint::CreateRemoval(Before);
7961 }
7962 } else if (!Proto->getReturnType()->isDependentType()) {
7963 DB << /*typedef*/1 << Proto->getReturnType();
7964 } else if (getLangOpts().CPlusPlus11) {
7965 DB << /*alias template*/2 << Proto->getReturnType();
7966 } else {
7967 DB << /*might not be fixable*/3;
7968 }
7969
7970 // Recover by incorporating the other type chunks into the result type.
7971 // Note, this does *not* change the name of the function. This is compatible
7972 // with the GCC extension:
7973 // struct S { &operator int(); } s;
7974 // int &r = s.operator int(); // ok in GCC
7975 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007976 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007977 }
7978
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007979 // C++ [class.conv.fct]p4:
7980 // The conversion-type-id shall not represent a function type nor
7981 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007982 if (ConvType->isArrayType()) {
7983 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7984 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007985 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007986 } else if (ConvType->isFunctionType()) {
7987 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7988 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007989 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007990 }
7991
7992 // Rebuild the function type "R" without any parameters (in case any
7993 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007994 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007995 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007996 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007997
Douglas Gregor5fb53972009-01-14 15:45:31 +00007998 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007999 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008000 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008001 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008002 diag::warn_cxx98_compat_explicit_conversion_functions :
8003 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008004 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008005}
8006
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008007/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8008/// the declaration of the given C++ conversion function. This routine
8009/// is responsible for recording the conversion function in the C++
8010/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008011Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008012 assert(Conversion && "Expected to receive a conversion function declaration");
8013
Douglas Gregor4287b372008-12-12 08:25:50 +00008014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008015
8016 // Make sure we aren't redeclaring the conversion function.
8017 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008018
8019 // C++ [class.conv.fct]p1:
8020 // [...] A conversion function is never used to convert a
8021 // (possibly cv-qualified) object to the (possibly cv-qualified)
8022 // same object type (or a reference to it), to a (possibly
8023 // cv-qualified) base class of that type (or a reference to it),
8024 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008025 // FIXME: Suppress this warning if the conversion function ends up being a
8026 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008027 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008028 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008029 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008030 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008031 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8032 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008033 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008034 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008035 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8036 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008037 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008038 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008039 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008040 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008041 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008042 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008043 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008044 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008045 }
8046
Douglas Gregor457104e2010-09-29 04:25:11 +00008047 if (FunctionTemplateDecl *ConversionTemplate
8048 = Conversion->getDescribedFunctionTemplate())
8049 return ConversionTemplate;
8050
John McCall48871652010-08-21 09:40:31 +00008051 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008052}
8053
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008054//===----------------------------------------------------------------------===//
8055// Namespace Handling
8056//===----------------------------------------------------------------------===//
8057
Richard Smith45bb8852012-10-04 22:13:39 +00008058/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8059/// reopened.
8060static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8061 SourceLocation Loc,
8062 IdentifierInfo *II, bool *IsInline,
8063 NamespaceDecl *PrevNS) {
8064 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008065
Richard Smithf501cc32012-10-05 01:46:25 +00008066 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8067 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8068 // inline namespaces, with the intention of bringing names into namespace std.
8069 //
8070 // We support this just well enough to get that case working; this is not
8071 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008072 if (*IsInline && II && II->getName().startswith("__atomic") &&
8073 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008074 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008075 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8076 NS = NS->getPreviousDecl())
8077 NS->setInline(*IsInline);
8078 // Patch up the lookup table for the containing namespace. This isn't really
8079 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008080 for (auto *I : PrevNS->decls())
8081 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008082 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8083 return;
8084 }
8085
8086 if (PrevNS->isInline())
8087 // The user probably just forgot the 'inline', so suggest that it
8088 // be added back.
8089 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8090 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8091 else
Richard Smith360cb252016-09-30 23:16:08 +00008092 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008093
8094 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8095 *IsInline = PrevNS->isInline();
8096}
John McCallb1be5232010-08-26 09:15:37 +00008097
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008098/// ActOnStartNamespaceDef - This is called at the start of a namespace
8099/// definition.
John McCall48871652010-08-21 09:40:31 +00008100Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008101 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008102 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008103 SourceLocation IdentLoc,
8104 IdentifierInfo *II,
8105 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008106 AttributeList *AttrList,
8107 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008108 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8109 // For anonymous namespace, take the location of the left brace.
8110 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008111 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008112 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008113 bool IsStd = false;
8114 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008115 Scope *DeclRegionScope = NamespcScope->getParent();
8116
Craig Topperc3ec1492014-05-26 06:22:03 +00008117 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008118 if (II) {
8119 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008120 // The identifier in an original-namespace-definition shall not
8121 // have been previously defined in the declarative region in
8122 // which the original-namespace-definition appears. The
8123 // identifier in an original-namespace-definition is the name of
8124 // the namespace. Subsequently in that declarative region, it is
8125 // treated as an original-namespace-name.
8126 //
8127 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008128 // look through using directives, just look for any ordinary names
8129 // as if by qualified name lookup.
8130 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8131 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008132 NamedDecl *PrevDecl =
8133 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008134 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008135
Douglas Gregore57e7522012-01-07 09:11:48 +00008136 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008137 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008138 if (IsInline != PrevNS->isInline())
8139 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8140 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008141 } else if (PrevDecl) {
8142 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008143 Diag(Loc, diag::err_redefinition_different_kind)
8144 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008145 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008146 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008147 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008148 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008149 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008150 // This is the first "real" definition of the namespace "std", so update
8151 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008152 PrevNS = getStdNamespace();
8153 IsStd = true;
8154 AddToKnown = !IsInline;
8155 } else {
8156 // We've seen this namespace for the first time.
8157 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008158 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008159 } else {
John McCall4fa53422009-10-01 00:25:31 +00008160 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008161
8162 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008163 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008164 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008165 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008166 } else {
8167 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008168 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008169 }
8170
Richard Smith45bb8852012-10-04 22:13:39 +00008171 if (PrevNS && IsInline != PrevNS->isInline())
8172 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8173 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008174 }
8175
8176 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8177 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008178 if (IsInvalid)
8179 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008180
8181 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008182
Douglas Gregore57e7522012-01-07 09:11:48 +00008183 // FIXME: Should we be merging attributes?
8184 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008185 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008186
8187 if (IsStd)
8188 StdNamespace = Namespc;
8189 if (AddToKnown)
8190 KnownNamespaces[Namespc] = false;
8191
8192 if (II) {
8193 PushOnScopeChains(Namespc, DeclRegionScope);
8194 } else {
8195 // Link the anonymous namespace into its parent.
8196 DeclContext *Parent = CurContext->getRedeclContext();
8197 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8198 TU->setAnonymousNamespace(Namespc);
8199 } else {
8200 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008201 }
John McCall4fa53422009-10-01 00:25:31 +00008202
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008203 CurContext->addDecl(Namespc);
8204
John McCall4fa53422009-10-01 00:25:31 +00008205 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8206 // behaves as if it were replaced by
8207 // namespace unique { /* empty body */ }
8208 // using namespace unique;
8209 // namespace unique { namespace-body }
8210 // where all occurrences of 'unique' in a translation unit are
8211 // replaced by the same identifier and this identifier differs
8212 // from all other identifiers in the entire program.
8213
8214 // We just create the namespace with an empty name and then add an
8215 // implicit using declaration, just like the standard suggests.
8216 //
8217 // CodeGen enforces the "universally unique" aspect by giving all
8218 // declarations semantically contained within an anonymous
8219 // namespace internal linkage.
8220
Douglas Gregore57e7522012-01-07 09:11:48 +00008221 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008222 UD = UsingDirectiveDecl::Create(Context, Parent,
8223 /* 'using' */ LBrace,
8224 /* 'namespace' */ SourceLocation(),
8225 /* qualifier */ NestedNameSpecifierLoc(),
8226 /* identifier */ SourceLocation(),
8227 Namespc,
8228 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008229 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008230 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008231 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008232 }
8233
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008234 ActOnDocumentableDecl(Namespc);
8235
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008236 // Although we could have an invalid decl (i.e. the namespace name is a
8237 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008238 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8239 // for the namespace has the declarations that showed up in that particular
8240 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008241 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008242 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008243}
8244
Sebastian Redla6602e92009-11-23 15:34:23 +00008245/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8246/// is a namespace alias, returns the namespace it points to.
8247static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8248 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8249 return AD->getNamespace();
8250 return dyn_cast_or_null<NamespaceDecl>(D);
8251}
8252
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008253/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8254/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008255void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008256 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8257 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008258 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008259 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008260 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008261 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008262}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008263
John McCall28a0cf72010-08-25 07:42:41 +00008264CXXRecordDecl *Sema::getStdBadAlloc() const {
8265 return cast_or_null<CXXRecordDecl>(
8266 StdBadAlloc.get(Context.getExternalSource()));
8267}
8268
Richard Smith96269c52016-09-29 22:49:46 +00008269EnumDecl *Sema::getStdAlignValT() const {
8270 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8271}
8272
John McCall28a0cf72010-08-25 07:42:41 +00008273NamespaceDecl *Sema::getStdNamespace() const {
8274 return cast_or_null<NamespaceDecl>(
8275 StdNamespace.get(Context.getExternalSource()));
8276}
8277
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008278NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8279 if (!StdExperimentalNamespaceCache) {
8280 if (auto Std = getStdNamespace()) {
8281 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8282 SourceLocation(), LookupNamespaceName);
8283 if (!LookupQualifiedName(Result, Std) ||
8284 !(StdExperimentalNamespaceCache =
8285 Result.getAsSingle<NamespaceDecl>()))
8286 Result.suppressDiagnostics();
8287 }
8288 }
8289 return StdExperimentalNamespaceCache;
8290}
8291
Douglas Gregorcdf87022010-06-29 17:53:46 +00008292/// \brief Retrieve the special "std" namespace, which may require us to
8293/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008294NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008295 if (!StdNamespace) {
8296 // The "std" namespace has not yet been defined, so build one implicitly.
8297 StdNamespace = NamespaceDecl::Create(Context,
8298 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008299 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008300 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008301 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008302 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008303 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008304 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008305
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008306 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008307}
8308
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008309bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008310 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008311 "Looking for std::initializer_list outside of C++.");
8312
8313 // We're looking for implicit instantiations of
8314 // template <typename E> class std::initializer_list.
8315
8316 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8317 return false;
8318
Craig Topperc3ec1492014-05-26 06:22:03 +00008319 ClassTemplateDecl *Template = nullptr;
8320 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008321
Sebastian Redl43144e72012-01-17 22:49:58 +00008322 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008323
Sebastian Redl43144e72012-01-17 22:49:58 +00008324 ClassTemplateSpecializationDecl *Specialization =
8325 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8326 if (!Specialization)
8327 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008328
Sebastian Redl43144e72012-01-17 22:49:58 +00008329 Template = Specialization->getSpecializedTemplate();
8330 Arguments = Specialization->getTemplateArgs().data();
8331 } else if (const TemplateSpecializationType *TST =
8332 Ty->getAs<TemplateSpecializationType>()) {
8333 Template = dyn_cast_or_null<ClassTemplateDecl>(
8334 TST->getTemplateName().getAsTemplateDecl());
8335 Arguments = TST->getArgs();
8336 }
8337 if (!Template)
8338 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008339
8340 if (!StdInitializerList) {
8341 // Haven't recognized std::initializer_list yet, maybe this is it.
8342 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8343 if (TemplateClass->getIdentifier() !=
8344 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008345 !getStdNamespace()->InEnclosingNamespaceSetOf(
8346 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008347 return false;
8348 // This is a template called std::initializer_list, but is it the right
8349 // template?
8350 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008351 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008352 return false;
8353 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8354 return false;
8355
8356 // It's the right template.
8357 StdInitializerList = Template;
8358 }
8359
Richard Smith7d7dee72015-02-24 03:30:14 +00008360 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008361 return false;
8362
8363 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008364 if (Element)
8365 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008366 return true;
8367}
8368
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008369static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8370 NamespaceDecl *Std = S.getStdNamespace();
8371 if (!Std) {
8372 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008373 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008374 }
8375
8376 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8377 Loc, Sema::LookupOrdinaryName);
8378 if (!S.LookupQualifiedName(Result, Std)) {
8379 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008380 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008381 }
8382 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8383 if (!Template) {
8384 Result.suppressDiagnostics();
8385 // We found something weird. Complain about the first thing we found.
8386 NamedDecl *Found = *Result.begin();
8387 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008388 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008389 }
8390
8391 // We found some template called std::initializer_list. Now verify that it's
8392 // correct.
8393 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008394 if (Params->getMinRequiredArguments() != 1 ||
8395 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008396 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008397 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008398 }
8399
8400 return Template;
8401}
8402
8403QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8404 if (!StdInitializerList) {
8405 StdInitializerList = LookupStdInitializerList(*this, Loc);
8406 if (!StdInitializerList)
8407 return QualType();
8408 }
8409
8410 TemplateArgumentListInfo Args(Loc, Loc);
8411 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8412 Context.getTrivialTypeSourceInfo(Element,
8413 Loc)));
8414 return Context.getCanonicalType(
8415 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8416}
8417
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008418bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8419 // C++ [dcl.init.list]p2:
8420 // A constructor is an initializer-list constructor if its first parameter
8421 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8422 // std::initializer_list<E> for some type E, and either there are no other
8423 // parameters or else all other parameters have default arguments.
8424 if (Ctor->getNumParams() < 1 ||
8425 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8426 return false;
8427
8428 QualType ArgType = Ctor->getParamDecl(0)->getType();
8429 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8430 ArgType = RT->getPointeeType().getUnqualifiedType();
8431
Craig Topperc3ec1492014-05-26 06:22:03 +00008432 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008433}
8434
Douglas Gregora172e082011-03-26 22:25:30 +00008435/// \brief Determine whether a using statement is in a context where it will be
8436/// apply in all contexts.
8437static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8438 switch (CurContext->getDeclKind()) {
8439 case Decl::TranslationUnit:
8440 return true;
8441 case Decl::LinkageSpec:
8442 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8443 default:
8444 return false;
8445 }
8446}
8447
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008448namespace {
8449
8450// Callback to only accept typo corrections that are namespaces.
8451class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008452public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008453 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008454 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008455 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008456 return false;
8457 }
8458};
8459
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008460}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008461
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008462static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8463 CXXScopeSpec &SS,
8464 SourceLocation IdentLoc,
8465 IdentifierInfo *Ident) {
8466 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008467 if (TypoCorrection Corrected =
8468 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8469 llvm::make_unique<NamespaceValidatorCCC>(),
8470 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008471 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008472 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8473 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008474 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008475 S.diagnoseTypo(Corrected,
8476 S.PDiag(diag::err_using_directive_member_suggest)
8477 << Ident << DC << DroppedSpecifier << SS.getRange(),
8478 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008479 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008480 S.diagnoseTypo(Corrected,
8481 S.PDiag(diag::err_using_directive_suggest) << Ident,
8482 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008483 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008484 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008485 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008486 }
8487 return false;
8488}
8489
John McCall48871652010-08-21 09:40:31 +00008490Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008491 SourceLocation UsingLoc,
8492 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008493 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008494 SourceLocation IdentLoc,
8495 IdentifierInfo *NamespcName,
8496 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008497 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8498 assert(NamespcName && "Invalid NamespcName.");
8499 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008500
8501 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008502 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008503 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008504 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008505
Craig Topperc3ec1492014-05-26 06:22:03 +00008506 UsingDirectiveDecl *UDir = nullptr;
8507 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008508 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008509 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008510
Douglas Gregor34074322009-01-14 22:20:51 +00008511 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008512 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8513 LookupParsedName(R, S, &SS);
8514 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008515 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008516
Douglas Gregorcdf87022010-06-29 17:53:46 +00008517 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008518 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008519 // Allow "using namespace std;" or "using namespace ::std;" even if
8520 // "std" hasn't been defined yet, for GCC compatibility.
8521 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8522 NamespcName->isStr("std")) {
8523 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008524 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008525 R.resolveKind();
8526 }
8527 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008528 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008529 }
8530
John McCall9f3059a2009-10-09 21:13:30 +00008531 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008532 NamedDecl *Named = R.getRepresentativeDecl();
8533 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8534 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008535
Nico Riecke50e59a2014-11-24 17:29:52 +00008536 // The use of a nested name specifier may trigger deprecation warnings.
8537 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008538
Douglas Gregor889ceb72009-02-03 19:21:40 +00008539 // C++ [namespace.udir]p1:
8540 // A using-directive specifies that the names in the nominated
8541 // namespace can be used in the scope in which the
8542 // using-directive appears after the using-directive. During
8543 // unqualified name lookup (3.4.1), the names appear as if they
8544 // were declared in the nearest enclosing namespace which
8545 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008546 // namespace. [Note: in this context, "contains" means "contains
8547 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008548
8549 // Find enclosing context containing both using-directive and
8550 // nominated namespace.
8551 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8552 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8553 CommonAncestor = CommonAncestor->getParent();
8554
Sebastian Redla6602e92009-11-23 15:34:23 +00008555 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008556 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008557 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008558
Douglas Gregora172e082011-03-26 22:25:30 +00008559 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008560 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008561 Diag(IdentLoc, diag::warn_using_directive_in_header);
8562 }
8563
Douglas Gregor889ceb72009-02-03 19:21:40 +00008564 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008565 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008566 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008567 }
8568
Richard Smith54ecd982013-02-20 19:22:51 +00008569 if (UDir)
8570 ProcessDeclAttributeList(S, UDir, AttrList);
8571
John McCall48871652010-08-21 09:40:31 +00008572 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008573}
8574
8575void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008576 // If the scope has an associated entity and the using directive is at
8577 // namespace or translation unit scope, add the UsingDirectiveDecl into
8578 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008579 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008580 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008581 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008582 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008583 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008584 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008585 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008586}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008587
Douglas Gregorfec52632009-06-20 00:51:54 +00008588
John McCall48871652010-08-21 09:40:31 +00008589Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008590 AccessSpecifier AS,
8591 bool HasUsingKeyword,
8592 SourceLocation UsingLoc,
8593 CXXScopeSpec &SS,
8594 UnqualifiedId &Name,
8595 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008596 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00008597 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008598 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008599
Douglas Gregor220f4272009-11-04 16:30:06 +00008600 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008601 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008602 case UnqualifiedId::IK_Identifier:
8603 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008604 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008605 case UnqualifiedId::IK_ConversionFunctionId:
8606 break;
8607
8608 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008609 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008610 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008611 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008612 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008613 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008614 diag::err_using_decl_constructor)
8615 << SS.getRange();
8616
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008617 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008618
Craig Topperc3ec1492014-05-26 06:22:03 +00008619 return nullptr;
8620
Douglas Gregor220f4272009-11-04 16:30:06 +00008621 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008622 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008623 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008624 return nullptr;
8625
Douglas Gregor220f4272009-11-04 16:30:06 +00008626 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008627 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008628 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008629 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00008630 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008631
8632 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8633 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008634 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008635 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008636
Richard Smithc2bc61b2013-03-18 21:12:30 +00008637 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00008638 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008639 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008640 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8641 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008642 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008643 }
8644
Douglas Gregorc4356532010-12-16 00:46:58 +00008645 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8646 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00008647 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00008648
John McCall3f746822009-11-17 05:59:44 +00008649 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008650 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008651 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008652 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00008653 if (UD)
8654 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008655
John McCall48871652010-08-21 09:40:31 +00008656 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008657}
8658
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008659/// \brief Determine whether a using declaration considers the given
8660/// declarations as "equivalent", e.g., if they are redeclarations of
8661/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008662static bool
8663IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8664 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008665 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008666
Richard Smithdda56e42011-04-15 14:24:37 +00008667 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008668 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008669 return Context.hasSameType(TD1->getUnderlyingType(),
8670 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008671
8672 return false;
8673}
8674
8675
John McCall84d87672009-12-10 09:41:52 +00008676/// Determines whether to create a using shadow decl for a particular
8677/// decl, given the set of decls existing prior to this using lookup.
8678bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008679 const LookupResult &Previous,
8680 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008681 // Diagnose finding a decl which is not from a base class of the
8682 // current class. We do this now because there are cases where this
8683 // function will silently decide not to build a shadow decl, which
8684 // will pre-empt further diagnostics.
8685 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008686 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008687 // the qualifier.
8688 //
8689 // FIXME: diagnose the following if we care enough:
8690 // struct A { int foo; };
8691 // struct B : A { using A::foo; };
8692 // template <class T> struct C : A {};
8693 // template <class T> struct D : C<T> { using B::foo; } // <---
8694 // This is invalid (during instantiation) in C++03 because B::foo
8695 // resolves to the using decl in B, which is not a base class of D<T>.
8696 // We can't diagnose it immediately because C<T> is an unknown
8697 // specialization. The UsingShadowDecl in D<T> then points directly
8698 // to A::foo, which will look well-formed when we instantiate.
8699 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008700 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008701 DeclContext *OrigDC = Orig->getDeclContext();
8702
8703 // Handle enums and anonymous structs.
8704 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8705 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8706 while (OrigRec->isAnonymousStructOrUnion())
8707 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8708
8709 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8710 if (OrigDC == CurContext) {
8711 Diag(Using->getLocation(),
8712 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008713 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008714 Diag(Orig->getLocation(), diag::note_using_decl_target);
8715 return true;
8716 }
8717
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008718 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00008719 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008720 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00008721 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008722 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008723 Diag(Orig->getLocation(), diag::note_using_decl_target);
8724 return true;
8725 }
8726 }
8727
8728 if (Previous.empty()) return false;
8729
8730 NamedDecl *Target = Orig;
8731 if (isa<UsingShadowDecl>(Target))
8732 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8733
John McCalla17e83e2009-12-11 02:33:26 +00008734 // If the target happens to be one of the previous declarations, we
8735 // don't have a conflict.
8736 //
8737 // FIXME: but we might be increasing its access, in which case we
8738 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008739 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008740 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00008741 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8742 I != E; ++I) {
8743 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00008744 // We can have UsingDecls in our Previous results because we use the same
8745 // LookupResult for checking whether the UsingDecl itself is a valid
8746 // redeclaration.
8747 if (isa<UsingDecl>(D))
8748 continue;
8749
Richard Smithfd8634a2013-10-23 02:17:46 +00008750 if (IsEquivalentForUsingDecl(Context, D, Target)) {
8751 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8752 PrevShadow = Shadow;
8753 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00008754 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8755 // We don't conflict with an existing using shadow decl of an equivalent
8756 // declaration, but we're not a redeclaration of it.
8757 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00008758 }
John McCalla17e83e2009-12-11 02:33:26 +00008759
Richard Smithf091e122015-09-15 01:28:55 +00008760 if (isVisible(D))
8761 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00008762 }
8763
Richard Smithfd8634a2013-10-23 02:17:46 +00008764 if (FoundEquivalentDecl)
8765 return false;
8766
Alp Tokera2794f92014-01-22 07:29:52 +00008767 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008768 NamedDecl *OldDecl = nullptr;
8769 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8770 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00008771 case Ovl_Overload:
8772 return false;
8773
8774 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00008775 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008776 break;
Richard Smith18819302014-02-06 01:31:33 +00008777
John McCall84d87672009-12-10 09:41:52 +00008778 // We found a decl with the exact signature.
8779 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00008780 // If we're in a record, we want to hide the target, so we
8781 // return true (without a diagnostic) to tell the caller not to
8782 // build a shadow decl.
8783 if (CurContext->isRecord())
8784 return true;
8785
8786 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00008787 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008788 break;
8789 }
8790
8791 Diag(Target->getLocation(), diag::note_using_decl_target);
8792 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8793 return true;
8794 }
8795
8796 // Target is not a function.
8797
John McCall84d87672009-12-10 09:41:52 +00008798 if (isa<TagDecl>(Target)) {
8799 // No conflict between a tag and a non-tag.
8800 if (!Tag) return false;
8801
John McCalle29c5cd2009-12-10 19:51:03 +00008802 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008803 Diag(Target->getLocation(), diag::note_using_decl_target);
8804 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8805 return true;
8806 }
8807
8808 // No conflict between a tag and a non-tag.
8809 if (!NonTag) return false;
8810
John McCalle29c5cd2009-12-10 19:51:03 +00008811 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008812 Diag(Target->getLocation(), diag::note_using_decl_target);
8813 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8814 return true;
8815}
8816
Richard Smith5179eb72016-06-28 19:03:57 +00008817/// Determine whether a direct base class is a virtual base class.
8818static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8819 if (!Derived->getNumVBases())
8820 return false;
8821 for (auto &B : Derived->bases())
8822 if (B.getType()->getAsCXXRecordDecl() == Base)
8823 return B.isVirtual();
8824 llvm_unreachable("not a direct base class");
8825}
8826
John McCall3f746822009-11-17 05:59:44 +00008827/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00008828UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00008829 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00008830 NamedDecl *Orig,
8831 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00008832 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00008833 NamedDecl *Target = Orig;
8834 if (isa<UsingShadowDecl>(Target)) {
8835 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8836 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00008837 }
Richard Smithfd8634a2013-10-23 02:17:46 +00008838
Richard Smith5179eb72016-06-28 19:03:57 +00008839 NamedDecl *NonTemplateTarget = Target;
8840 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8841 NonTemplateTarget = TargetTD->getTemplatedDecl();
8842
8843 UsingShadowDecl *Shadow;
8844 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8845 bool IsVirtualBase =
8846 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8847 UD->getQualifier()->getAsRecordDecl());
8848 Shadow = ConstructorUsingShadowDecl::Create(
8849 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8850 } else {
8851 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8852 Target);
8853 }
John McCall3f746822009-11-17 05:59:44 +00008854 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00008855
Douglas Gregor457104e2010-09-29 04:25:11 +00008856 Shadow->setAccess(UD->getAccess());
8857 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8858 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00008859
8860 Shadow->setPreviousDecl(PrevDecl);
8861
John McCall3f746822009-11-17 05:59:44 +00008862 if (S)
John McCall3969e302009-12-08 07:46:18 +00008863 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00008864 else
John McCall3969e302009-12-08 07:46:18 +00008865 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00008866
John McCall3969e302009-12-08 07:46:18 +00008867
John McCall84d87672009-12-10 09:41:52 +00008868 return Shadow;
8869}
John McCall3969e302009-12-08 07:46:18 +00008870
John McCall84d87672009-12-10 09:41:52 +00008871/// Hides a using shadow declaration. This is required by the current
8872/// using-decl implementation when a resolvable using declaration in a
8873/// class is followed by a declaration which would hide or override
8874/// one or more of the using decl's targets; for example:
8875///
8876/// struct Base { void foo(int); };
8877/// struct Derived : Base {
8878/// using Base::foo;
8879/// void foo(int);
8880/// };
8881///
8882/// The governing language is C++03 [namespace.udecl]p12:
8883///
8884/// When a using-declaration brings names from a base class into a
8885/// derived class scope, member functions in the derived class
8886/// override and/or hide member functions with the same name and
8887/// parameter types in a base class (rather than conflicting).
8888///
8889/// There are two ways to implement this:
8890/// (1) optimistically create shadow decls when they're not hidden
8891/// by existing declarations, or
8892/// (2) don't create any shadow decls (or at least don't make them
8893/// visible) until we've fully parsed/instantiated the class.
8894/// The problem with (1) is that we might have to retroactively remove
8895/// a shadow decl, which requires several O(n) operations because the
8896/// decl structures are (very reasonably) not designed for removal.
8897/// (2) avoids this but is very fiddly and phase-dependent.
8898void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00008899 if (Shadow->getDeclName().getNameKind() ==
8900 DeclarationName::CXXConversionFunctionName)
8901 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8902
John McCall84d87672009-12-10 09:41:52 +00008903 // Remove it from the DeclContext...
8904 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008905
John McCall84d87672009-12-10 09:41:52 +00008906 // ...and the scope, if applicable...
8907 if (S) {
John McCall48871652010-08-21 09:40:31 +00008908 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00008909 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008910 }
8911
John McCall84d87672009-12-10 09:41:52 +00008912 // ...and the using decl.
8913 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8914
8915 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00008916 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00008917}
8918
Richard Smith09d5b3a2014-05-01 00:35:04 +00008919/// Find the base specifier for a base class with the given type.
8920static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8921 QualType DesiredBase,
8922 bool &AnyDependentBases) {
8923 // Check whether the named type is a direct base class.
8924 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8925 for (auto &Base : Derived->bases()) {
8926 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8927 if (CanonicalDesiredBase == BaseType)
8928 return &Base;
8929 if (BaseType->isDependentType())
8930 AnyDependentBases = true;
8931 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008932 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008933}
8934
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008935namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008936class UsingValidatorCCC : public CorrectionCandidateCallback {
8937public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00008938 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008939 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008940 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00008941 IsInstantiation(IsInstantiation), OldNNS(NNS),
8942 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008943
Craig Toppera798a9d2014-03-02 09:32:10 +00008944 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008945 NamedDecl *ND = Candidate.getCorrectionDecl();
8946
8947 // Keywords are not valid here.
8948 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008949 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008950
8951 // Completely unqualified names are invalid for a 'using' declaration.
8952 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8953 return false;
8954
Richard Smith9385d702016-05-14 01:58:49 +00008955 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8956 // reject.
8957
Richard Smith09d5b3a2014-05-01 00:35:04 +00008958 if (RequireMemberOf) {
8959 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8960 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8961 // No-one ever wants a using-declaration to name an injected-class-name
8962 // of a base class, unless they're declaring an inheriting constructor.
8963 ASTContext &Ctx = ND->getASTContext();
8964 if (!Ctx.getLangOpts().CPlusPlus11)
8965 return false;
8966 QualType FoundType = Ctx.getRecordType(FoundRecord);
8967
8968 // Check that the injected-class-name is named as a member of its own
8969 // type; we don't want to suggest 'using Derived::Base;', since that
8970 // means something else.
8971 NestedNameSpecifier *Specifier =
8972 Candidate.WillReplaceSpecifier()
8973 ? Candidate.getCorrectionSpecifier()
8974 : OldNNS;
8975 if (!Specifier->getAsType() ||
8976 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8977 return false;
8978
8979 // Check that this inheriting constructor declaration actually names a
8980 // direct base class of the current class.
8981 bool AnyDependentBases = false;
8982 if (!findDirectBaseWithType(RequireMemberOf,
8983 Ctx.getRecordType(FoundRecord),
8984 AnyDependentBases) &&
8985 !AnyDependentBases)
8986 return false;
8987 } else {
8988 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8989 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8990 return false;
8991
8992 // FIXME: Check that the base class member is accessible?
8993 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00008994 } else {
8995 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8996 if (FoundRecord && FoundRecord->isInjectedClassName())
8997 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008998 }
8999
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009000 if (isa<TypeDecl>(ND))
9001 return HasTypenameKeyword || !IsInstantiation;
9002
9003 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009004 }
9005
9006private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009007 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009008 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009009 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009010 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009011};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009012} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009013
John McCalle61f2ba2009-11-18 02:36:19 +00009014/// Builds a using declaration.
9015///
9016/// \param IsInstantiation - Whether this call arises from an
9017/// instantiation of an unresolved using declaration. We treat
9018/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009019NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9020 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009021 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009022 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009023 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00009024 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009025 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00009026 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009027 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009028 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009029 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009030
Anders Carlssonf038fc22009-08-28 05:49:21 +00009031 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009032
Anders Carlsson59140b32009-08-28 03:16:11 +00009033 if (SS.isEmpty()) {
9034 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00009035 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00009036 }
Mike Stump11289f42009-09-09 15:08:12 +00009037
Richard Smith5179eb72016-06-28 19:03:57 +00009038 // For an inheriting constructor declaration, the name of the using
9039 // declaration is the name of a constructor in this class, not in the
9040 // base class.
9041 DeclarationNameInfo UsingName = NameInfo;
9042 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9043 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9044 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9045 Context.getCanonicalType(Context.getRecordType(RD))));
9046
John McCall84d87672009-12-10 09:41:52 +00009047 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009048 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009049 ForRedeclaration);
9050 Previous.setHideTags(false);
9051 if (S) {
9052 LookupName(Previous, S);
9053
9054 // It is really dumb that we have to do this.
9055 LookupResult::Filter F = Previous.makeFilter();
9056 while (F.hasNext()) {
9057 NamedDecl *D = F.next();
9058 if (!isDeclInScope(D, CurContext, S))
9059 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009060 // If we found a local extern declaration that's not ordinarily visible,
9061 // and this declaration is being added to a non-block scope, ignore it.
9062 // We're only checking for scope conflicts here, not also for violations
9063 // of the linkage rules.
9064 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9065 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9066 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009067 }
9068 F.done();
9069 } else {
9070 assert(IsInstantiation && "no scope in non-instantiation");
9071 assert(CurContext->isRecord() && "scope not record in instantiation");
9072 LookupQualifiedName(Previous, CurContext);
9073 }
9074
John McCall84d87672009-12-10 09:41:52 +00009075 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009076 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9077 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009078 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009079
9080 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00009081 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009082 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009083
John McCall84c16cf2009-11-12 03:15:40 +00009084 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009085 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009086 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00009087 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009088 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009089 // FIXME: not all declaration name kinds are legal here
9090 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9091 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009092 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009093 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00009094 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009095 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9096 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00009097 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009098 D->setAccess(AS);
9099 CurContext->addDecl(D);
9100 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009101 }
John McCallb96ec562009-12-04 22:46:56 +00009102
Richard Smith09d5b3a2014-05-01 00:35:04 +00009103 auto Build = [&](bool Invalid) {
9104 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009105 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9106 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009107 UD->setAccess(AS);
9108 CurContext->addDecl(UD);
9109 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009110 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009111 };
9112 auto BuildInvalid = [&]{ return Build(true); };
9113 auto BuildValid = [&]{ return Build(false); };
9114
9115 if (RequireCompleteDeclContext(SS, LookupContext))
9116 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009117
Richard Smith78163e22015-04-01 19:31:06 +00009118 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009119 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009120
John McCall3969e302009-12-08 07:46:18 +00009121 // Unlike most lookups, we don't always want to hide tag
9122 // declarations: tag names are visible through the using declaration
9123 // even if hidden by ordinary names, *except* in a dependent context
9124 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009125 if (!IsInstantiation)
9126 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009127
John McCall5dadb652012-04-07 03:04:20 +00009128 // For the purposes of this lookup, we have a base object type
9129 // equal to that of the current context.
9130 if (CurContext->isRecord()) {
9131 R.setBaseObjectType(
9132 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9133 }
9134
John McCall27b18f82009-11-17 02:14:36 +00009135 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009136
Richard Smith78163e22015-04-01 19:31:06 +00009137 // Try to correct typos if possible. If constructor name lookup finds no
9138 // results, that means the named class has no explicit constructors, and we
9139 // suppressed declaring implicit ones (probably because it's dependent or
9140 // invalid).
9141 if (R.empty() &&
9142 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009143 if (TypoCorrection Corrected = CorrectTypo(
9144 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9145 llvm::make_unique<UsingValidatorCCC>(
9146 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9147 dyn_cast<CXXRecordDecl>(CurContext)),
9148 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009149 // We reject any correction for which ND would be NULL.
9150 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009151
Richard Smithf9b15102013-08-17 00:46:16 +00009152 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009153 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009154 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9155 << NameInfo.getName() << LookupContext << 0
9156 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009157
9158 // If we corrected to an inheriting constructor, handle it as one.
9159 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9160 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009161 // The parent of the injected class name is the class itself.
9162 RD = cast<CXXRecordDecl>(RD->getParent());
9163
Richard Smith09d5b3a2014-05-01 00:35:04 +00009164 // Fix up the information we'll use to build the using declaration.
9165 if (Corrected.WillReplaceSpecifier()) {
9166 NestedNameSpecifierLocBuilder Builder;
9167 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9168 QualifierLoc.getSourceRange());
9169 QualifierLoc = Builder.getWithLocInContext(Context);
9170 }
9171
Richard Smith5179eb72016-06-28 19:03:57 +00009172 // In this case, the name we introduce is the name of a derived class
9173 // constructor.
9174 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9175 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9176 Context.getCanonicalType(Context.getRecordType(CurClass))));
9177 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009178 for (auto *Ctor : LookupConstructors(RD))
9179 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009180 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009181 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009182 // FIXME: Pick up all the declarations if we found an overloaded
9183 // function.
9184 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009185 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009186 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009187 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009188 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009189 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009190 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009191 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009192 }
9193
Richard Smith09d5b3a2014-05-01 00:35:04 +00009194 if (R.isAmbiguous())
9195 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009196
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009197 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009198 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009199 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009200 Diag(IdentLoc, diag::err_using_typename_non_type);
9201 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9202 Diag((*I)->getUnderlyingDecl()->getLocation(),
9203 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009204 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009205 }
9206 } else {
9207 // If we asked for a non-typename and we got a type, error out,
9208 // but only if this is an instantiation of an unresolved using
9209 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009210 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009211 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9212 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009213 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009214 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009215 }
9216
Richard Smith5cbeb752016-05-05 02:13:49 +00009217 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009218 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009219 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009220 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9221 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009222 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009223 }
Mike Stump11289f42009-09-09 15:08:12 +00009224
Richard Smith5cbeb752016-05-05 02:13:49 +00009225 // C++14 [namespace.udecl]p7:
9226 // A using-declaration shall not name a scoped enumerator.
9227 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9228 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9229 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9230 << SS.getRange();
9231 return BuildInvalid();
9232 }
9233 }
9234
Richard Smith09d5b3a2014-05-01 00:35:04 +00009235 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009236
Richard Smith5179eb72016-06-28 19:03:57 +00009237 // Some additional rules apply to inheriting constructors.
9238 if (UsingName.getName().getNameKind() ==
9239 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009240 // Suppress access diagnostics; the access check is instead performed at the
9241 // point of use for an inheriting constructor.
9242 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009243 if (CheckInheritingConstructorUsingDecl(UD))
9244 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009245 }
9246
John McCall84d87672009-12-10 09:41:52 +00009247 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009248 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009249 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9250 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009251 }
John McCall3f746822009-11-17 05:59:44 +00009252
9253 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009254}
9255
Sebastian Redl08905022011-02-05 19:23:19 +00009256/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009257bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009258 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009259
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009260 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009261 assert(SourceType &&
9262 "Using decl naming constructor doesn't have type in scope spec.");
9263 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9264
9265 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009266 bool AnyDependentBases = false;
9267 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9268 AnyDependentBases);
9269 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009270 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009271 diag::err_using_decl_constructor_not_in_direct_base)
9272 << UD->getNameInfo().getSourceRange()
9273 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009274 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009275 return true;
9276 }
9277
Richard Smith09d5b3a2014-05-01 00:35:04 +00009278 if (Base)
9279 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009280
9281 return false;
9282}
9283
John McCall84d87672009-12-10 09:41:52 +00009284/// Checks that the given using declaration is not an invalid
9285/// redeclaration. Note that this is checking only for the using decl
9286/// itself, not for any ill-formedness among the UsingShadowDecls.
9287bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009288 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009289 const CXXScopeSpec &SS,
9290 SourceLocation NameLoc,
9291 const LookupResult &Prev) {
9292 // C++03 [namespace.udecl]p8:
9293 // C++0x [namespace.udecl]p10:
9294 // A using-declaration is a declaration and can therefore be used
9295 // repeatedly where (and only where) multiple declarations are
9296 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009297 //
John McCall032092f2010-11-29 18:01:58 +00009298 // That's in non-member contexts.
9299 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00009300 return false;
9301
Aaron Ballman4a979672014-01-03 13:56:08 +00009302 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00009303
9304 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9305 NamedDecl *D = *I;
9306
9307 bool DTypename;
9308 NestedNameSpecifier *DQual;
9309 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009310 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009311 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009312 } else if (UnresolvedUsingValueDecl *UD
9313 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9314 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009315 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009316 } else if (UnresolvedUsingTypenameDecl *UD
9317 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9318 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009319 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009320 } else continue;
9321
9322 // using decls differ if one says 'typename' and the other doesn't.
9323 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009324 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009325
9326 // using decls differ if they name different scopes (but note that
9327 // template instantiation can cause this check to trigger when it
9328 // didn't before instantiation).
9329 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9330 Context.getCanonicalNestedNameSpecifier(DQual))
9331 continue;
9332
9333 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009334 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009335 return true;
9336 }
9337
9338 return false;
9339}
9340
John McCall3969e302009-12-08 07:46:18 +00009341
John McCallb96ec562009-12-04 22:46:56 +00009342/// Checks that the given nested-name qualifier used in a using decl
9343/// in the current context is appropriately related to the current
9344/// scope. If an error is found, diagnoses it and returns true.
9345bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9346 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009347 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009348 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009349 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009350
John McCall3969e302009-12-08 07:46:18 +00009351 if (!CurContext->isRecord()) {
9352 // C++03 [namespace.udecl]p3:
9353 // C++0x [namespace.udecl]p8:
9354 // A using-declaration for a class member shall be a member-declaration.
9355
9356 // If we weren't able to compute a valid scope, it must be a
9357 // dependent class scope.
Richard Smith5cbeb752016-05-05 02:13:49 +00009358 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9359 auto *RD = NamedContext
9360 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9361 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009362 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009363 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009364
John McCall3969e302009-12-08 07:46:18 +00009365 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9366 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009367
9368 // If we have a complete, non-dependent source type, try to suggest a
9369 // way to get the same effect.
9370 if (!RD)
9371 return true;
9372
9373 // Find what this using-declaration was referring to.
9374 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9375 R.setHideTags(false);
9376 R.suppressDiagnostics();
9377 LookupQualifiedName(R, RD);
9378
9379 if (R.getAsSingle<TypeDecl>()) {
9380 if (getLangOpts().CPlusPlus11) {
9381 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9382 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9383 << 0 // alias declaration
9384 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9385 NameInfo.getName().getAsString() +
9386 " = ");
9387 } else {
9388 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9389 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009390 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009391 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9392 << 1 // typedef declaration
9393 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9394 << FixItHint::CreateInsertion(
9395 InsertLoc, " " + NameInfo.getName().getAsString());
9396 }
9397 } else if (R.getAsSingle<VarDecl>()) {
9398 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9399 // repeating the type of the static data member here.
9400 FixItHint FixIt;
9401 if (getLangOpts().CPlusPlus11) {
9402 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9403 FixIt = FixItHint::CreateReplacement(
9404 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9405 }
9406
9407 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9408 << 2 // reference declaration
9409 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009410 } else if (R.getAsSingle<EnumConstantDecl>()) {
9411 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9412 // repeating the type of the enumeration here, and we can't do so if
9413 // the type is anonymous.
9414 FixItHint FixIt;
9415 if (getLangOpts().CPlusPlus11) {
9416 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9417 FixIt = FixItHint::CreateReplacement(
9418 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9419 }
9420
9421 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9422 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9423 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009424 }
John McCall3969e302009-12-08 07:46:18 +00009425 return true;
9426 }
9427
9428 // Otherwise, everything is known to be fine.
9429 return false;
9430 }
9431
9432 // The current scope is a record.
9433
9434 // If the named context is dependent, we can't decide much.
9435 if (!NamedContext) {
9436 // FIXME: in C++0x, we can diagnose if we can prove that the
9437 // nested-name-specifier does not refer to a base class, which is
9438 // still possible in some cases.
9439
9440 // Otherwise we have to conservatively report that things might be
9441 // okay.
9442 return false;
9443 }
9444
9445 if (!NamedContext->isRecord()) {
9446 // Ideally this would point at the last name in the specifier,
9447 // but we don't have that level of source info.
9448 Diag(SS.getRange().getBegin(),
9449 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009450 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009451 return true;
9452 }
9453
Douglas Gregor7c842292010-12-21 07:41:49 +00009454 if (!NamedContext->isDependentContext() &&
9455 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9456 return true;
9457
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009458 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009459 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009460 // In a using-declaration used as a member-declaration, the
9461 // nested-name-specifier shall name a base class of the class
9462 // being defined.
9463
9464 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9465 cast<CXXRecordDecl>(NamedContext))) {
9466 if (CurContext == NamedContext) {
9467 Diag(NameLoc,
9468 diag::err_using_decl_nested_name_specifier_is_current_class)
9469 << SS.getRange();
9470 return true;
9471 }
9472
9473 Diag(SS.getRange().getBegin(),
9474 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009475 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009476 << cast<CXXRecordDecl>(CurContext)
9477 << SS.getRange();
9478 return true;
9479 }
9480
9481 return false;
9482 }
9483
9484 // C++03 [namespace.udecl]p4:
9485 // A using-declaration used as a member-declaration shall refer
9486 // to a member of a base class of the class being defined [etc.].
9487
9488 // Salient point: SS doesn't have to name a base class as long as
9489 // lookup only finds members from base classes. Therefore we can
9490 // diagnose here only if we can prove that that can't happen,
9491 // i.e. if the class hierarchies provably don't intersect.
9492
9493 // TODO: it would be nice if "definitely valid" results were cached
9494 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9495 // need to be repeated.
9496
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009497 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9498 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9499 Bases.insert(Base);
9500 return true;
John McCall3969e302009-12-08 07:46:18 +00009501 };
9502
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009503 // Collect all bases. Return false if we find a dependent base.
9504 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009505 return false;
9506
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009507 // Returns true if the base is dependent or is one of the accumulated base
9508 // classes.
9509 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9510 return !Bases.count(Base);
9511 };
9512
9513 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009514 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009515 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9516 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009517 return false;
9518
9519 Diag(SS.getRange().getBegin(),
9520 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009521 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009522 << cast<CXXRecordDecl>(CurContext)
9523 << SS.getRange();
9524
9525 return true;
John McCallb96ec562009-12-04 22:46:56 +00009526}
9527
Richard Smithdda56e42011-04-15 14:24:37 +00009528Decl *Sema::ActOnAliasDeclaration(Scope *S,
9529 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009530 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009531 SourceLocation UsingLoc,
9532 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009533 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009534 TypeResult Type,
9535 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009536 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009537 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009538 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009539 assert((S->getFlags() & Scope::DeclScope) &&
9540 "got alias-declaration outside of declaration scope");
9541
9542 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009543 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009544
9545 bool Invalid = false;
9546 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009547 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009548 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009549
9550 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009551 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009552
9553 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009554 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009555 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009556 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9557 TInfo->getTypeLoc().getBeginLoc());
9558 }
Richard Smithdda56e42011-04-15 14:24:37 +00009559
9560 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9561 LookupName(Previous, S);
9562
9563 // Warn about shadowing the name of a template parameter.
9564 if (Previous.isSingleResult() &&
9565 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009566 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009567 Previous.clear();
9568 }
9569
9570 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9571 "name in alias declaration must be an identifier");
9572 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9573 Name.StartLocation,
9574 Name.Identifier, TInfo);
9575
9576 NewTD->setAccess(AS);
9577
9578 if (Invalid)
9579 NewTD->setInvalidDecl();
9580
Richard Smith54ecd982013-02-20 19:22:51 +00009581 ProcessDeclAttributeList(S, NewTD, AttrList);
9582
Richard Smith3f1b5d02011-05-05 21:57:07 +00009583 CheckTypedefForVariablyModifiedType(S, NewTD);
9584 Invalid |= NewTD->isInvalidDecl();
9585
Richard Smithdda56e42011-04-15 14:24:37 +00009586 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009587
9588 NamedDecl *NewND;
9589 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009590 TypeAliasTemplateDecl *OldDecl = nullptr;
9591 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009592
9593 if (TemplateParamLists.size() != 1) {
9594 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009595 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9596 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009597 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009598 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009599
Richard Smith882593f2016-04-06 17:38:58 +00009600 // Check that we can declare a template here.
9601 if (CheckTemplateDeclScope(S, TemplateParams))
9602 return nullptr;
9603
Richard Smith3f1b5d02011-05-05 21:57:07 +00009604 // Only consider previous declarations in the same scope.
9605 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9606 /*ExplicitInstantiationOrSpecialization*/false);
9607 if (!Previous.empty()) {
9608 Redeclaration = true;
9609
9610 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9611 if (!OldDecl && !Invalid) {
9612 Diag(UsingLoc, diag::err_redefinition_different_kind)
9613 << Name.Identifier;
9614
9615 NamedDecl *OldD = Previous.getRepresentativeDecl();
9616 if (OldD->getLocation().isValid())
9617 Diag(OldD->getLocation(), diag::note_previous_definition);
9618
9619 Invalid = true;
9620 }
9621
9622 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9623 if (TemplateParameterListsAreEqual(TemplateParams,
9624 OldDecl->getTemplateParameters(),
9625 /*Complain=*/true,
9626 TPL_TemplateMatch))
9627 OldTemplateParams = OldDecl->getTemplateParameters();
9628 else
9629 Invalid = true;
9630
9631 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9632 if (!Invalid &&
9633 !Context.hasSameType(OldTD->getUnderlyingType(),
9634 NewTD->getUnderlyingType())) {
9635 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9636 // but we can't reasonably accept it.
9637 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9638 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9639 if (OldTD->getLocation().isValid())
9640 Diag(OldTD->getLocation(), diag::note_previous_definition);
9641 Invalid = true;
9642 }
9643 }
9644 }
9645
9646 // Merge any previous default template arguments into our parameters,
9647 // and check the parameter list.
9648 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9649 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00009650 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009651
9652 TypeAliasTemplateDecl *NewDecl =
9653 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9654 Name.Identifier, TemplateParams,
9655 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00009656 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009657
9658 NewDecl->setAccess(AS);
9659
9660 if (Invalid)
9661 NewDecl->setInvalidDecl();
9662 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00009663 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009664
9665 NewND = NewDecl;
9666 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00009667 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9668 setTagNameForLinkagePurposes(TD, NewTD);
9669 handleTagNumbering(TD, S);
9670 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00009671 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9672 NewND = NewTD;
9673 }
Richard Smithdda56e42011-04-15 14:24:37 +00009674
Richard Smith3cbf3f12016-07-15 20:53:25 +00009675 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00009676 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009677 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00009678}
9679
Richard Smithf4634362014-09-03 23:11:22 +00009680Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9681 SourceLocation AliasLoc,
9682 IdentifierInfo *Alias, CXXScopeSpec &SS,
9683 SourceLocation IdentLoc,
9684 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00009685
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009686 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00009687 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9688 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009689
John McCall27b18f82009-11-17 02:14:36 +00009690 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00009691 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009692
John McCall9f3059a2009-10-09 21:13:30 +00009693 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00009694 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00009695 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00009696 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00009697 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00009698 }
Richard Smithf4634362014-09-03 23:11:22 +00009699 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00009700 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00009701
9702 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00009703 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9704 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00009705 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00009706
Richard Smith2b2a1762015-12-03 23:24:04 +00009707 // Check we're not shadowing a template parameter.
9708 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9709 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9710 PrevR.clear();
9711 }
Aaron Ballman43f40102014-11-14 22:34:56 +00009712
Richard Smith2b2a1762015-12-03 23:24:04 +00009713 // Filter out any other lookup result from an enclosing scope.
9714 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9715 /*AllowInlineNamespace*/false);
9716
9717 // Find the previous declaration and check that we can redeclare it.
9718 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00009719 if (PrevR.isSingleResult()) {
9720 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9721 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009722 // We already have an alias with the same name that points to the same
9723 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00009724 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9725 Prev = AD;
9726 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009727 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9728 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +00009729 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +00009730 << AD->getNamespace();
9731 return nullptr;
9732 }
Richard Smith2b2a1762015-12-03 23:24:04 +00009733 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +00009734 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +00009735 ? diag::err_redefinition
9736 : diag::err_redefinition_different_kind;
9737 Diag(AliasLoc, DiagID) << Alias;
9738 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9739 return nullptr;
9740 }
9741 }
Mike Stump11289f42009-09-09 15:08:12 +00009742
Nico Riecke50e59a2014-11-24 17:29:52 +00009743 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00009744 DiagnoseUseOfDecl(ND, IdentLoc);
9745
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009746 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00009747 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00009748 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00009749 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00009750 if (Prev)
9751 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00009752
John McCalld8d0d432010-02-16 06:53:13 +00009753 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00009754 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00009755}
9756
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009757Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009758Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9759 CXXMethodDecl *MD) {
9760 CXXRecordDecl *ClassDecl = MD->getParent();
9761
Douglas Gregor6d880b12010-07-01 22:31:05 +00009762 // C++ [except.spec]p14:
9763 // An implicitly declared special member function (Clause 12) shall have an
9764 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00009765 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009766 if (ClassDecl->isInvalidDecl())
9767 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00009768
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009769 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009770 for (const auto &B : ClassDecl->bases()) {
9771 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00009772 continue;
9773
Aaron Ballman574705e2014-03-13 15:41:46 +00009774 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009775 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009776 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9777 // If this is a deleted function, add it anyway. This might be conformant
9778 // with the standard. This might not. I'm not sure. It might not matter.
9779 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00009780 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009781 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009782 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009783
9784 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009785 for (const auto &B : ClassDecl->vbases()) {
9786 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009787 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009788 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9789 // If this is a deleted function, add it anyway. This might be conformant
9790 // with the standard. This might not. I'm not sure. It might not matter.
9791 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009792 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009793 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009794 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009795
9796 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009797 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00009798 if (F->hasInClassInitializer()) {
9799 if (Expr *E = F->getInClassInitializer())
9800 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00009801 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00009802 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00009803 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9804 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9805 // If this is a deleted function, add it anyway. This might be conformant
9806 // with the standard. This might not. I'm not sure. It might not matter.
9807 // In particular, the problem is that this function never gets called. It
9808 // might just be ill-formed because this function attempts to refer to
9809 // a deleted function here.
9810 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009811 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009812 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009813 }
John McCalldb40c7f2010-12-14 08:05:40 +00009814
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009815 return ExceptSpec;
9816}
9817
Richard Smithc2bc61b2013-03-18 21:12:30 +00009818Sema::ImplicitExceptionSpecification
Richard Smith5179eb72016-06-28 19:03:57 +00009819Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9820 CXXConstructorDecl *CD) {
Richard Smithb7151b92013-04-10 06:11:48 +00009821 CXXRecordDecl *ClassDecl = CD->getParent();
9822
9823 // C++ [except.spec]p14:
9824 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00009825 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00009826 if (ClassDecl->isInvalidDecl())
9827 return ExceptSpec;
9828
Richard Smith5179eb72016-06-28 19:03:57 +00009829 auto Inherited = CD->getInheritedConstructor();
9830 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
Richard Smithb7151b92013-04-10 06:11:48 +00009831
Richard Smith5179eb72016-06-28 19:03:57 +00009832 // Direct and virtual base-class constructors.
9833 for (bool VBase : {false, true}) {
9834 for (CXXBaseSpecifier &B :
9835 VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9836 // Don't visit direct vbases twice.
9837 if (B.isVirtual() != VBase)
Richard Smithb7151b92013-04-10 06:11:48 +00009838 continue;
Richard Smithb7151b92013-04-10 06:11:48 +00009839
Richard Smith5179eb72016-06-28 19:03:57 +00009840 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9841 if (!BaseClass)
Richard Smithb7151b92013-04-10 06:11:48 +00009842 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00009843
9844 CXXConstructorDecl *Constructor =
9845 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9846 .first;
9847 if (!Constructor)
9848 Constructor = LookupDefaultConstructor(BaseClass);
Richard Smithb7151b92013-04-10 06:11:48 +00009849 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009850 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00009851 }
9852 }
9853
9854 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009855 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00009856 if (F->hasInClassInitializer()) {
9857 if (Expr *E = F->getInClassInitializer())
9858 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00009859 } else if (const RecordType *RecordTy
9860 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9861 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9862 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9863 if (Constructor)
9864 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9865 }
9866 }
9867
Richard Smithc2bc61b2013-03-18 21:12:30 +00009868 return ExceptSpec;
9869}
9870
Richard Smith8bf22e52012-11-29 01:34:07 +00009871namespace {
9872/// RAII object to register a special member as being currently declared.
9873struct DeclaringSpecialMember {
9874 Sema &S;
9875 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +00009876 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +00009877 bool WasAlreadyBeingDeclared;
9878
9879 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +00009880 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +00009881 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00009882 if (WasAlreadyBeingDeclared)
9883 // This almost never happens, but if it does, ensure that our cache
9884 // doesn't contain a stale result.
9885 S.SpecialMemberCache.clear();
9886
9887 // FIXME: Register a note to be produced if we encounter an error while
9888 // declaring the special member.
9889 }
9890 ~DeclaringSpecialMember() {
9891 if (!WasAlreadyBeingDeclared)
9892 S.SpecialMembersBeingDeclared.erase(D);
9893 }
9894
9895 /// \brief Are we already trying to declare this special member?
9896 bool isAlreadyBeingDeclared() const {
9897 return WasAlreadyBeingDeclared;
9898 }
9899};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009900}
Richard Smith8bf22e52012-11-29 01:34:07 +00009901
Richard Smith12e79312016-05-13 06:47:56 +00009902void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9903 // Look up any existing declarations, but don't trigger declaration of all
9904 // implicit special members with this name.
9905 DeclarationName Name = FD->getDeclName();
9906 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9907 ForRedeclaration);
9908 for (auto *D : FD->getParent()->lookup(Name))
9909 if (auto *Acceptable = R.getAcceptableDecl(D))
9910 R.addDecl(Acceptable);
9911 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +00009912 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +00009913
9914 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9915}
9916
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009917CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9918 CXXRecordDecl *ClassDecl) {
9919 // C++ [class.ctor]p5:
9920 // A default constructor for a class X is a constructor of class X
9921 // that can be called without an argument. If there is no
9922 // user-declared constructor for class X, a default constructor is
9923 // implicitly declared. An implicitly-declared default constructor
9924 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009925 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009926 "Should not build implicit default constructor!");
9927
Richard Smith8bf22e52012-11-29 01:34:07 +00009928 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9929 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009930 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009931
Richard Smithb5800092012-06-10 05:43:50 +00009932 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9933 CXXDefaultConstructor,
9934 false);
9935
Douglas Gregor6d880b12010-07-01 22:31:05 +00009936 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009937 CanQualType ClassType
9938 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009939 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009940 DeclarationName Name
9941 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009942 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00009943 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009944 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9945 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9946 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009947 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00009948 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009949
9950 if (getLangOpts().CUDA) {
9951 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9952 DefaultCon,
9953 /* ConstRHS */ false,
9954 /* Diagnose */ false);
9955 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009956
9957 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009958 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009959 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009960
Richard Smith6b02d462012-12-08 08:32:28 +00009961 // We don't need to use SpecialMemberIsTrivial here; triviality for default
9962 // constructors is easy to compute.
9963 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9964
Douglas Gregor9672f922010-07-03 00:47:00 +00009965 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00009966 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00009967
Richard Smith12e79312016-05-13 06:47:56 +00009968 Scope *S = getScopeForContext(ClassDecl);
9969 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9970
9971 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9972 SetDeclDeleted(DefaultCon, ClassLoc);
9973
9974 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +00009975 PushOnScopeChains(DefaultCon, S, false);
9976 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00009977
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009978 return DefaultCon;
9979}
9980
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009981void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9982 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009983 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009984 !Constructor->doesThisDeclarationHaveABody() &&
9985 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009986 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00009987
Anders Carlsson423f5d82010-04-23 16:04:08 +00009988 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00009989 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00009990
Eli Friedmaneaf34142012-10-18 20:14:08 +00009991 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009992 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00009993 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00009994 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009995 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009996 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00009997 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00009998 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00009999 }
Douglas Gregor73193272010-09-20 16:48:21 +000010000
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010001 // The exception specification is needed because we are defining the
10002 // function.
10003 ResolveExceptionSpec(CurrentLocation,
10004 Constructor->getType()->castAs<FunctionProtoType>());
10005
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010006 SourceLocation Loc = Constructor->getLocEnd().isValid()
10007 ? Constructor->getLocEnd()
10008 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010009 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010010
Eli Friedman276dd182013-09-05 00:02:25 +000010011 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010012 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010013
10014 if (ASTMutationListener *L = getASTMutationListener()) {
10015 L->CompletedImplicitDefinition(Constructor);
10016 }
Richard Trieuef64e942013-10-25 00:56:00 +000010017
10018 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010019}
10020
Richard Smith938f40b2011-06-11 17:19:42 +000010021void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010022 // Perform any delayed checks on exception specifications.
10023 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010024}
10025
Richard Smith5179eb72016-06-28 19:03:57 +000010026/// Find or create the fake constructor we synthesize to model constructing an
10027/// object of a derived class via a constructor of a base class.
10028CXXConstructorDecl *
10029Sema::findInheritingConstructor(SourceLocation Loc,
10030 CXXConstructorDecl *BaseCtor,
10031 ConstructorUsingShadowDecl *Shadow) {
10032 CXXRecordDecl *Derived = Shadow->getParent();
10033 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010034
Richard Smith5179eb72016-06-28 19:03:57 +000010035 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10036 // For now we use the name of the base class constructor as a member of the
10037 // derived class to indicate a (fake) inherited constructor name.
10038 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010039
Richard Smith5179eb72016-06-28 19:03:57 +000010040 // Check to see if we already have a fake constructor for this inherited
10041 // constructor call.
10042 for (NamedDecl *Ctor : Derived->lookup(Name))
10043 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10044 ->getInheritedConstructor()
10045 .getConstructor(),
10046 BaseCtor))
10047 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010048
Richard Smith5179eb72016-06-28 19:03:57 +000010049 DeclarationNameInfo NameInfo(Name, UsingLoc);
10050 TypeSourceInfo *TInfo =
10051 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10052 FunctionProtoTypeLoc ProtoLoc =
10053 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010054
Richard Smith5179eb72016-06-28 19:03:57 +000010055 // Check the inherited constructor is valid and find the list of base classes
10056 // from which it was inherited.
10057 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010058
Richard Smith5179eb72016-06-28 19:03:57 +000010059 bool Constexpr =
10060 BaseCtor->isConstexpr() &&
10061 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10062 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010063
Richard Smith5179eb72016-06-28 19:03:57 +000010064 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10065 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10066 BaseCtor->isExplicit(), /*Inline=*/true,
10067 /*ImplicitlyDeclared=*/true, Constexpr,
10068 InheritedConstructor(Shadow, BaseCtor));
10069 if (Shadow->isInvalidDecl())
10070 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010071
Richard Smith5179eb72016-06-28 19:03:57 +000010072 // Build an unevaluated exception specification for this fake constructor.
10073 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10074 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10075 EPI.ExceptionSpec.Type = EST_Unevaluated;
10076 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10077 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10078 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010079
Richard Smith5179eb72016-06-28 19:03:57 +000010080 // Build the parameter declarations.
10081 SmallVector<ParmVarDecl *, 16> ParamDecls;
10082 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010083 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010084 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10085 ParmVarDecl *PD = ParmVarDecl::Create(
10086 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10087 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10088 PD->setScopeInfo(0, I);
10089 PD->setImplicit();
10090 // Ensure attributes are propagated onto parameters (this matters for
10091 // format, pass_object_size, ...).
10092 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10093 ParamDecls.push_back(PD);
10094 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010095 }
10096
Richard Smith5179eb72016-06-28 19:03:57 +000010097 // Set up the new constructor.
10098 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10099 DerivedCtor->setAccess(BaseCtor->getAccess());
10100 DerivedCtor->setParams(ParamDecls);
10101 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010102
10103 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10104 SetDeclDeleted(DerivedCtor, UsingLoc);
10105
Richard Smith5179eb72016-06-28 19:03:57 +000010106 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010107}
10108
Richard Smith80a47022016-06-29 01:10:27 +000010109void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10110 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10111 Ctor->getInheritedConstructor().getShadowDecl());
10112 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10113 /*Diagnose*/true);
10114}
10115
Richard Smithc2bc61b2013-03-18 21:12:30 +000010116void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10117 CXXConstructorDecl *Constructor) {
10118 CXXRecordDecl *ClassDecl = Constructor->getParent();
10119 assert(Constructor->getInheritedConstructor() &&
10120 !Constructor->doesThisDeclarationHaveABody() &&
10121 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010122 if (Constructor->isInvalidDecl())
10123 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010124
Richard Smith5179eb72016-06-28 19:03:57 +000010125 ConstructorUsingShadowDecl *Shadow =
10126 Constructor->getInheritedConstructor().getShadowDecl();
10127 CXXConstructorDecl *InheritedCtor =
10128 Constructor->getInheritedConstructor().getConstructor();
10129
10130 // [class.inhctor.init]p1:
10131 // initialization proceeds as if a defaulted default constructor is used to
10132 // initialize the D object and each base class subobject from which the
10133 // constructor was inherited
10134
10135 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10136 CXXRecordDecl *RD = Shadow->getParent();
10137 SourceLocation InitLoc = Shadow->getLocation();
10138
10139 // Initializations are performed "as if by a defaulted default constructor",
10140 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010141 SynthesizedFunctionScope Scope(*this, Constructor);
10142 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010143
10144 // Build explicit initializers for all base classes from which the
10145 // constructor was inherited.
10146 SmallVector<CXXCtorInitializer*, 8> Inits;
10147 for (bool VBase : {false, true}) {
10148 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10149 if (B.isVirtual() != VBase)
10150 continue;
10151
10152 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10153 if (!BaseRD)
10154 continue;
10155
10156 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10157 if (!BaseCtor.first)
10158 continue;
10159
10160 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10161 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10162 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10163
10164 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10165 Inits.push_back(new (Context) CXXCtorInitializer(
10166 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10167 SourceLocation()));
10168 }
10169 }
10170
10171 // We now proceed as if for a defaulted default constructor, with the relevant
10172 // initializers replaced.
10173
10174 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10175 if (HadError || Trap.hasErrorOccurred()) {
10176 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010177 Constructor->setInvalidDecl();
10178 return;
10179 }
10180
Richard Smith5179eb72016-06-28 19:03:57 +000010181 // The exception specification is needed because we are defining the
10182 // function.
10183 ResolveExceptionSpec(CurrentLocation,
10184 Constructor->getType()->castAs<FunctionProtoType>());
10185
10186 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010187
Eli Friedman276dd182013-09-05 00:02:25 +000010188 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010189 MarkVTableUsed(CurrentLocation, ClassDecl);
10190
10191 if (ASTMutationListener *L = getASTMutationListener()) {
10192 L->CompletedImplicitDefinition(Constructor);
10193 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010194
Richard Smith5179eb72016-06-28 19:03:57 +000010195 DiagnoseUninitializedFields(*this, Constructor);
10196}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010197
Alexis Huntf91729462011-05-12 22:46:25 +000010198Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010199Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10200 CXXRecordDecl *ClassDecl = MD->getParent();
10201
Douglas Gregorf1203042010-07-01 19:09:28 +000010202 // C++ [except.spec]p14:
10203 // An implicitly declared special member function (Clause 12) shall have
10204 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +000010205 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010206 if (ClassDecl->isInvalidDecl())
10207 return ExceptSpec;
10208
Douglas Gregorf1203042010-07-01 19:09:28 +000010209 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010210 for (const auto &B : ClassDecl->bases()) {
10211 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +000010212 continue;
10213
Aaron Ballman574705e2014-03-13 15:41:46 +000010214 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10215 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010216 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010217 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010218
Douglas Gregorf1203042010-07-01 19:09:28 +000010219 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010220 for (const auto &B : ClassDecl->vbases()) {
10221 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10222 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010223 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010224 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010225
Douglas Gregorf1203042010-07-01 19:09:28 +000010226 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010227 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +000010228 if (const RecordType *RecordTy
10229 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +000010230 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010231 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010232 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010233
Alexis Huntf91729462011-05-12 22:46:25 +000010234 return ExceptSpec;
10235}
10236
10237CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10238 // C++ [class.dtor]p2:
10239 // If a class has no user-declared destructor, a destructor is
10240 // declared implicitly. An implicitly-declared destructor is an
10241 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010242 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010243
Richard Smith8bf22e52012-11-29 01:34:07 +000010244 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10245 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010246 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010247
Douglas Gregor7454c562010-07-02 20:37:36 +000010248 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010249 CanQualType ClassType
10250 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010251 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010252 DeclarationName Name
10253 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010254 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010255 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010256 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010257 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010258 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010259 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010260 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010261
10262 if (getLangOpts().CUDA) {
10263 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10264 Destructor,
10265 /* ConstRHS */ false,
10266 /* Diagnose */ false);
10267 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010268
10269 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010270 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010271 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010272
Richard Smith6b02d462012-12-08 08:32:28 +000010273 // We don't need to use SpecialMemberIsTrivial here; triviality for
10274 // destructors is easy to compute.
10275 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10276
Douglas Gregor7454c562010-07-02 20:37:36 +000010277 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010278 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010279
Richard Smith12e79312016-05-13 06:47:56 +000010280 Scope *S = getScopeForContext(ClassDecl);
10281 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10282
10283 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10284 SetDeclDeleted(Destructor, ClassLoc);
10285
Douglas Gregor7454c562010-07-02 20:37:36 +000010286 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010287 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010288 PushOnScopeChains(Destructor, S, false);
10289 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010290
Douglas Gregorf1203042010-07-01 19:09:28 +000010291 return Destructor;
10292}
10293
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010294void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010295 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010296 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010297 !Destructor->doesThisDeclarationHaveABody() &&
10298 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010299 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010300 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010301 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010302
Douglas Gregor54818f02010-05-12 16:39:35 +000010303 if (Destructor->isInvalidDecl())
10304 return;
10305
Eli Friedmaneaf34142012-10-18 20:14:08 +000010306 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010307
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010308 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010309 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10310 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010311
Douglas Gregor54818f02010-05-12 16:39:35 +000010312 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010313 Diag(CurrentLocation, diag::note_member_synthesized_at)
10314 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10315
10316 Destructor->setInvalidDecl();
10317 return;
10318 }
10319
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010320 // The exception specification is needed because we are defining the
10321 // function.
10322 ResolveExceptionSpec(CurrentLocation,
10323 Destructor->getType()->castAs<FunctionProtoType>());
10324
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010325 SourceLocation Loc = Destructor->getLocEnd().isValid()
10326 ? Destructor->getLocEnd()
10327 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010328 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010329 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010330 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010331
10332 if (ASTMutationListener *L = getASTMutationListener()) {
10333 L->CompletedImplicitDefinition(Destructor);
10334 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010335}
10336
Richard Smith84973e52012-04-21 18:42:51 +000010337/// \brief Perform any semantic analysis which needs to be delayed until all
10338/// pending class member declarations have been parsed.
10339void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010340 // If the context is an invalid C++ class, just suppress these checks.
10341 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10342 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010343 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010344 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010345 return;
10346 }
10347 }
Richard Smith84973e52012-04-21 18:42:51 +000010348}
10349
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010350static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10351 // Don't do anything for template patterns.
10352 if (Class->getDescribedClassTemplate())
10353 return;
10354
David Majnemer474b3232015-12-31 05:36:46 +000010355 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10356 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10357
10358 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010359 for (Decl *Member : Class->decls()) {
10360 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10361 if (!CD) {
10362 // Recurse on nested classes.
10363 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10364 getDefaultArgExprsForConstructors(S, NestedRD);
10365 continue;
10366 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10367 continue;
10368 }
10369
David Majnemer474b3232015-12-31 05:36:46 +000010370 CallingConv ActualCallingConv =
10371 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10372
10373 // Skip default constructors with typical calling conventions and no default
10374 // arguments.
10375 unsigned NumParams = CD->getNumParams();
10376 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10377 continue;
10378
10379 if (LastExportedDefaultCtor) {
10380 S.Diag(LastExportedDefaultCtor->getLocation(),
10381 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10382 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10383 << CD->getDeclName();
10384 return;
10385 }
10386 LastExportedDefaultCtor = CD;
10387
10388 for (unsigned I = 0; I != NumParams; ++I) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010389 // Skip any default arguments that we've already instantiated.
10390 if (S.Context.getDefaultArgExprForConstructor(CD, I))
10391 continue;
10392
10393 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10394 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +000010395 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010396 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10397 }
10398 }
10399}
10400
Hans Wennborg99000c22015-08-15 01:18:16 +000010401void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010402 auto *RD = dyn_cast<CXXRecordDecl>(D);
10403
10404 // Default constructors that are annotated with __declspec(dllexport) which
10405 // have default arguments or don't use the standard calling convention are
10406 // wrapped with a thunk called the default constructor closure.
10407 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10408 getDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +000010409
Reid Kleckner5b640342016-02-26 19:51:02 +000010410 referenceDLLExportedClassMethods();
10411}
10412
10413void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010414 if (!DelayedDllExportClasses.empty()) {
10415 // Calling ReferenceDllExportedMethods might cause the current function to
10416 // be called again, so use a local copy of DelayedDllExportClasses.
10417 SmallVector<CXXRecordDecl *, 4> WorkList;
10418 std::swap(DelayedDllExportClasses, WorkList);
10419 for (CXXRecordDecl *Class : WorkList)
10420 ReferenceDllExportedMethods(*this, Class);
10421 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010422}
10423
Richard Smithd3b5c9082012-07-27 04:22:15 +000010424void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10425 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010426 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010427 "adjusting dtor exception specs was introduced in c++11");
10428
Sebastian Redl623ea822011-05-19 05:13:44 +000010429 // C++11 [class.dtor]p3:
10430 // A declaration of a destructor that does not have an exception-
10431 // specification is implicitly considered to have the same exception-
10432 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010433 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010434 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010435 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010436 return;
10437
Chandler Carruth9a797572011-09-20 04:55:26 +000010438 // Replace the destructor's type, building off the existing one. Fortunately,
10439 // the only thing of interest in the destructor type is its extended info.
10440 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010441 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010442 EPI.ExceptionSpec.Type = EST_Unevaluated;
10443 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010444 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010445
Sebastian Redl623ea822011-05-19 05:13:44 +000010446 // FIXME: If the destructor has a body that could throw, and the newly created
10447 // spec doesn't allow exceptions, we should emit a warning, because this
10448 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010449 // However, we don't have a body or an exception specification yet, so it
10450 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010451}
10452
Pavel Labath58934982013-08-30 08:52:28 +000010453namespace {
10454/// \brief An abstract base class for all helper classes used in building the
10455// copy/move operators. These classes serve as factory functions and help us
10456// avoid using the same Expr* in the AST twice.
10457class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010458 ExprBuilder(const ExprBuilder&) = delete;
10459 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010460
10461protected:
10462 static Expr *assertNotNull(Expr *E) {
10463 assert(E && "Expression construction must not fail.");
10464 return E;
10465 }
10466
10467public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010468 ExprBuilder() {}
10469 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010470
10471 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10472};
10473
10474class RefBuilder: public ExprBuilder {
10475 VarDecl *Var;
10476 QualType VarType;
10477
10478public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010479 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010480 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010481 }
10482
10483 RefBuilder(VarDecl *Var, QualType VarType)
10484 : Var(Var), VarType(VarType) {}
10485};
10486
10487class ThisBuilder: public ExprBuilder {
10488public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010489 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010490 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010491 }
10492};
10493
10494class CastBuilder: public ExprBuilder {
10495 const ExprBuilder &Builder;
10496 QualType Type;
10497 ExprValueKind Kind;
10498 const CXXCastPath &Path;
10499
10500public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010501 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010502 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10503 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010504 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010505 }
10506
10507 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10508 const CXXCastPath &Path)
10509 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10510};
10511
10512class DerefBuilder: public ExprBuilder {
10513 const ExprBuilder &Builder;
10514
10515public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010516 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010517 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010518 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010519 }
10520
10521 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10522};
10523
10524class MemberBuilder: public ExprBuilder {
10525 const ExprBuilder &Builder;
10526 QualType Type;
10527 CXXScopeSpec SS;
10528 bool IsArrow;
10529 LookupResult &MemberLookup;
10530
10531public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010532 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010533 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010534 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010535 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010536 }
10537
10538 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10539 LookupResult &MemberLookup)
10540 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10541 MemberLookup(MemberLookup) {}
10542};
10543
10544class MoveCastBuilder: public ExprBuilder {
10545 const ExprBuilder &Builder;
10546
10547public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010548 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010549 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10550 }
10551
10552 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10553};
10554
10555class LvalueConvBuilder: public ExprBuilder {
10556 const ExprBuilder &Builder;
10557
10558public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010559 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010560 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010561 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010562 }
10563
10564 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10565};
10566
10567class SubscriptBuilder: public ExprBuilder {
10568 const ExprBuilder &Base;
10569 const ExprBuilder &Index;
10570
10571public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010572 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010573 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010574 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010575 }
10576
10577 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10578 : Base(Base), Index(Index) {}
10579};
10580
10581} // end anonymous namespace
10582
Richard Smith41ae3282012-11-14 00:50:40 +000010583/// When generating a defaulted copy or move assignment operator, if a field
10584/// should be copied with __builtin_memcpy rather than via explicit assignments,
10585/// do so. This optimization only applies for arrays of scalars, and for arrays
10586/// of class type where the selected copy/move-assignment operator is trivial.
10587static StmtResult
10588buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010589 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010590 // Compute the size of the memory buffer to be copied.
10591 QualType SizeType = S.Context.getSizeType();
10592 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10593 S.Context.getTypeSizeInChars(T).getQuantity());
10594
10595 // Take the address of the field references for "from" and "to". We
10596 // directly construct UnaryOperators here because semantic analysis
10597 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010598 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010599 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10600 S.Context.getPointerType(From->getType()),
10601 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010602 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010603 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10604 S.Context.getPointerType(To->getType()),
10605 VK_RValue, OK_Ordinary, Loc);
10606
10607 const Type *E = T->getBaseElementTypeUnsafe();
10608 bool NeedsCollectableMemCpy =
10609 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10610
10611 // Create a reference to the __builtin_objc_memmove_collectable function
10612 StringRef MemCpyName = NeedsCollectableMemCpy ?
10613 "__builtin_objc_memmove_collectable" :
10614 "__builtin_memcpy";
10615 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10616 Sema::LookupOrdinaryName);
10617 S.LookupName(R, S.TUScope, true);
10618
10619 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10620 if (!MemCpy)
10621 // Something went horribly wrong earlier, and we will have complained
10622 // about it.
10623 return StmtError();
10624
10625 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010626 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010627 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10628
10629 Expr *CallArgs[] = {
10630 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10631 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010632 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010633 Loc, CallArgs, Loc);
10634
10635 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010636 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010637}
10638
Sebastian Redl22653ba2011-08-30 19:58:05 +000010639/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010640/// \c To.
10641///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010642/// This routine is used to copy/move the members of a class with an
10643/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010644/// copied are arrays, this routine builds for loops to copy them.
10645///
10646/// \param S The Sema object used for type-checking.
10647///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010648/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010649///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010650/// \param T The type of the expressions being copied/moved. Both expressions
10651/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010652///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010653/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010654///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010655/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010656///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010657/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010658/// Otherwise, it's a non-static member subobject.
10659///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010660/// \param Copying Whether we're copying or moving.
10661///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010662/// \param Depth Internal parameter recording the depth of the recursion.
10663///
Richard Smith41ae3282012-11-14 00:50:40 +000010664/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10665/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010666static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010667buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010668 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010669 bool CopyingBaseSubobject, bool Copying,
10670 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010671 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010672 // Each subobject is assigned in the manner appropriate to its type:
10673 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010674 // - if the subobject is of class type, as if by a call to operator= with
10675 // the subobject as the object expression and the corresponding
10676 // subobject of x as a single function argument (as if by explicit
10677 // qualification; that is, ignoring any possible virtual overriding
10678 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010679 //
10680 // C++03 [class.copy]p13:
10681 // - if the subobject is of class type, the copy assignment operator for
10682 // the class is used (as if by explicit qualification; that is,
10683 // ignoring any possible virtual overriding functions in more derived
10684 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010685 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10686 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010687
Douglas Gregorb139cd52010-05-01 20:49:11 +000010688 // Look for operator=.
10689 DeclarationName Name
10690 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10691 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10692 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010693
Richard Smith52c0b582012-11-13 00:54:12 +000010694 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10695 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010696 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010697 LookupResult::Filter F = OpLookup.makeFilter();
10698 while (F.hasNext()) {
10699 NamedDecl *D = F.next();
10700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10701 if (Method->isCopyAssignmentOperator() ||
10702 (!Copying && Method->isMoveAssignmentOperator()))
10703 continue;
10704
10705 F.erase();
10706 }
10707 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010708 }
Richard Smith52c0b582012-11-13 00:54:12 +000010709
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010710 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010711 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010712 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010713 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010714 // ambiguities), we need to cast "this" to that subobject type; to
10715 // ensure that we don't go through the virtual call mechanism, we need
10716 // to qualify the operator= name with the base class (see below). However,
10717 // this means that if the base class has a protected copy assignment
10718 // operator, the protected member access check will fail. So, we
10719 // rewrite "protected" access to "public" access in this case, since we
10720 // know by construction that we're calling from a derived class.
10721 if (CopyingBaseSubobject) {
10722 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10723 L != LEnd; ++L) {
10724 if (L.getAccess() == AS_protected)
10725 L.setAccess(AS_public);
10726 }
10727 }
Richard Smith52c0b582012-11-13 00:54:12 +000010728
Douglas Gregorb139cd52010-05-01 20:49:11 +000010729 // Create the nested-name-specifier that will be used to qualify the
10730 // reference to operator=; this is required to suppress the virtual
10731 // call mechanism.
10732 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000010733 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000010734 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000010735 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000010736 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000010737 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000010738
Douglas Gregorb139cd52010-05-01 20:49:11 +000010739 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000010740 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000010741 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10742 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010743 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000010744 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010745 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010746 /*SuppressQualifierCheck=*/true);
10747 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010748 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010749
Douglas Gregorb139cd52010-05-01 20:49:11 +000010750 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000010751
Pavel Labath58934982013-08-30 08:52:28 +000010752 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000010753 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010754 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000010755 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010756 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010757 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010758
Richard Smith41ae3282012-11-14 00:50:40 +000010759 // If we built a call to a trivial 'operator=' while copying an array,
10760 // bail out. We'll replace the whole shebang with a memcpy.
10761 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10762 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000010763 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010764
Richard Smith52c0b582012-11-13 00:54:12 +000010765 // Convert to an expression-statement, and clean up any produced
10766 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000010767 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010768 }
John McCallab8c2732010-03-16 06:11:48 +000010769
Richard Smith52c0b582012-11-13 00:54:12 +000010770 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000010771 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000010772 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010773 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000010774 ExprResult Assignment = S.CreateBuiltinBinOp(
10775 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010776 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010777 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000010778 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010779 }
Richard Smith52c0b582012-11-13 00:54:12 +000010780
10781 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000010782 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000010783
Douglas Gregorb139cd52010-05-01 20:49:11 +000010784 // Construct a loop over the array bounds, e.g.,
10785 //
10786 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10787 //
10788 // that will copy each of the array elements.
10789 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000010790
Douglas Gregorb139cd52010-05-01 20:49:11 +000010791 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000010792 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010793 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010794 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010795 llvm::raw_svector_ostream OS(Str);
10796 OS << "__i" << Depth;
10797 IterationVarName = &S.Context.Idents.get(OS.str());
10798 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000010799 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010800 IterationVarName, SizeType,
10801 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000010802 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000010803
Douglas Gregorb139cd52010-05-01 20:49:11 +000010804 // Initialize the iteration variable to zero.
10805 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010806 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010807
Pavel Labath58934982013-08-30 08:52:28 +000010808 // Creates a reference to the iteration variable.
10809 RefBuilder IterationVarRef(IterationVar, SizeType);
10810 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000010811
Douglas Gregorb139cd52010-05-01 20:49:11 +000010812 // Create the DeclStmt that holds the iteration variable.
10813 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010814
Douglas Gregorb139cd52010-05-01 20:49:11 +000010815 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000010816 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10817 MoveCastBuilder FromIndexMove(FromIndexCopy);
10818 const ExprBuilder *FromIndex;
10819 if (Copying)
10820 FromIndex = &FromIndexCopy;
10821 else
10822 FromIndex = &FromIndexMove;
10823
10824 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010825
10826 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000010827 StmtResult Copy =
10828 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000010829 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000010830 Copying, Depth + 1);
10831 // Bail out if copying fails or if we determined that we should use memcpy.
10832 if (Copy.isInvalid() || !Copy.get())
10833 return Copy;
10834
10835 // Create the comparison against the array bound.
10836 llvm::APInt Upper
10837 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10838 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000010839 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000010840 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10841 BO_NE, S.Context.BoolTy,
10842 VK_RValue, OK_Ordinary, Loc, false);
10843
10844 // Create the pre-increment of the iteration variable.
10845 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000010846 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10847 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010848
Douglas Gregorb139cd52010-05-01 20:49:11 +000010849 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000010850 return S.ActOnForStmt(
10851 Loc, Loc, InitStmt,
10852 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10853 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010854}
10855
Richard Smith41ae3282012-11-14 00:50:40 +000010856static StmtResult
10857buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010858 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010859 bool CopyingBaseSubobject, bool Copying) {
10860 // Maybe we should use a memcpy?
10861 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10862 T.isTriviallyCopyableType(S.Context))
10863 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10864
10865 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10866 CopyingBaseSubobject,
10867 Copying, 0));
10868
10869 // If we ended up picking a trivial assignment operator for an array of a
10870 // non-trivially-copyable class type, just emit a memcpy.
10871 if (!Result.isInvalid() && !Result.get())
10872 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10873
10874 return Result;
10875}
10876
Richard Smithd3b5c9082012-07-27 04:22:15 +000010877Sema::ImplicitExceptionSpecification
10878Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10879 CXXRecordDecl *ClassDecl = MD->getParent();
10880
10881 ImplicitExceptionSpecification ExceptSpec(*this);
10882 if (ClassDecl->isInvalidDecl())
10883 return ExceptSpec;
10884
10885 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010886 assert(T->getNumParams() == 1 && "not a copy assignment op");
10887 unsigned ArgQuals =
10888 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010889
Douglas Gregor68e11362010-07-01 17:48:08 +000010890 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010891 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010892 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010893
10894 // It is unspecified whether or not an implicit copy assignment operator
10895 // attempts to deduplicate calls to assignment operators of virtual bases are
10896 // made. As such, this exception specification is effectively unspecified.
10897 // Based on a similar decision made for constness in C++0x, we're erring on
10898 // the side of assuming such calls to be made regardless of whether they
10899 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010900 for (const auto &Base : ClassDecl->bases()) {
10901 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010902 continue;
10903
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010904 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010905 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010906 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10907 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010908 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010909 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010910
Aaron Ballman445a9392014-03-13 16:15:17 +000010911 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010912 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010913 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010914 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10915 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010916 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010917 }
10918
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010919 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010920 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010921 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10922 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010923 LookupCopyingAssignment(FieldClassDecl,
10924 ArgQuals | FieldType.getCVRQualifiers(),
10925 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010926 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010927 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010928 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010929
Richard Smithd3b5c9082012-07-27 04:22:15 +000010930 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010931}
10932
10933CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10934 // Note: The following rules are largely analoguous to the copy
10935 // constructor rules. Note that virtual bases are not taken into account
10936 // for determining the argument type of the operator. Note also that
10937 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010938 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010939
Richard Smith8bf22e52012-11-29 01:34:07 +000010940 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10941 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010942 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010943
Alexis Hunt119f3652011-05-14 05:23:20 +000010944 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10945 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010946 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10947 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010948 ArgType = ArgType.withConst();
10949 ArgType = Context.getLValueReferenceType(ArgType);
10950
Richard Smith99005e62013-05-07 03:19:20 +000010951 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10952 CXXCopyAssignment,
10953 Const);
10954
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010955 // An implicitly-declared copy assignment operator is an inline public
10956 // member of its class.
10957 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010958 SourceLocation ClassLoc = ClassDecl->getLocation();
10959 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010960 CXXMethodDecl *CopyAssignment =
10961 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010962 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10963 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010964 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010965 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010966 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010967
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010968 if (getLangOpts().CUDA) {
10969 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10970 CopyAssignment,
10971 /* ConstRHS */ Const,
10972 /* Diagnose */ false);
10973 }
10974
Richard Smithd3b5c9082012-07-27 04:22:15 +000010975 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010976 FunctionProtoType::ExtProtoInfo EPI =
10977 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010978 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010979
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010980 // Add the parameter to the operator.
10981 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010982 ClassLoc, ClassLoc,
10983 /*Id=*/nullptr, ArgType,
10984 /*TInfo=*/nullptr, SC_None,
10985 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010986 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010987
Richard Smith6b02d462012-12-08 08:32:28 +000010988 CopyAssignment->setTrivial(
10989 ClassDecl->needsOverloadResolutionForCopyAssignment()
10990 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10991 : ClassDecl->hasTrivialCopyAssignment());
10992
Richard Smith6b02d462012-12-08 08:32:28 +000010993 // Note that we have added this copy-assignment operator.
10994 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10995
Richard Smith12e79312016-05-13 06:47:56 +000010996 Scope *S = getScopeForContext(ClassDecl);
10997 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10998
10999 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11000 SetDeclDeleted(CopyAssignment, ClassLoc);
11001
11002 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011003 PushOnScopeChains(CopyAssignment, S, false);
11004 ClassDecl->addDecl(CopyAssignment);
11005
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011006 return CopyAssignment;
11007}
11008
Richard Smithd577fbb2013-06-13 03:23:42 +000011009/// Diagnose an implicit copy operation for a class which is odr-used, but
11010/// which is deprecated because the class has a user-declared copy constructor,
11011/// copy assignment operator, or destructor.
11012static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11013 SourceLocation UseLoc) {
11014 assert(CopyOp->isImplicit());
11015
11016 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011017 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011018
11019 // In Microsoft mode, assignment operations don't affect constructors and
11020 // vice versa.
11021 if (RD->hasUserDeclaredDestructor()) {
11022 UserDeclaredOperation = RD->getDestructor();
11023 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11024 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011025 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011026 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011027 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011028 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011029 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011030 break;
11031 }
11032 }
11033 assert(UserDeclaredOperation);
11034 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11035 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011036 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011037 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011038 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011039 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011040 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011041 break;
11042 }
11043 }
11044 assert(UserDeclaredOperation);
11045 }
11046
11047 if (UserDeclaredOperation) {
11048 S.Diag(UserDeclaredOperation->getLocation(),
11049 diag::warn_deprecated_copy_operation)
11050 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11051 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11052 S.Diag(UseLoc, diag::note_member_synthesized_at)
11053 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11054 : Sema::CXXCopyAssignment)
11055 << RD;
11056 }
11057}
11058
Douglas Gregorb139cd52010-05-01 20:49:11 +000011059void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11060 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011061 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011062 CopyAssignOperator->isOverloadedOperator() &&
11063 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011064 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11065 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011066 "DefineImplicitCopyAssignment called for wrong function");
11067
11068 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11069
11070 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11071 CopyAssignOperator->setInvalidDecl();
11072 return;
11073 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011074
11075 // C++11 [class.copy]p18:
11076 // The [definition of an implicitly declared copy assignment operator] is
11077 // deprecated if the class has a user-declared copy constructor or a
11078 // user-declared destructor.
11079 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11080 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11081
Eli Friedman276dd182013-09-05 00:02:25 +000011082 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011083
Eli Friedmaneaf34142012-10-18 20:14:08 +000011084 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011085 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011086
11087 // C++0x [class.copy]p30:
11088 // The implicitly-defined or explicitly-defaulted copy assignment operator
11089 // for a non-union class X performs memberwise copy assignment of its
11090 // subobjects. The direct base classes of X are assigned first, in the
11091 // order of their declaration in the base-specifier-list, and then the
11092 // immediate non-static data members of X are assigned, in the order in
11093 // which they were declared in the class definition.
11094
11095 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011096 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011097
11098 // The parameter for the "other" object, which we are copying from.
11099 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11100 Qualifiers OtherQuals = Other->getType().getQualifiers();
11101 QualType OtherRefType = Other->getType();
11102 if (const LValueReferenceType *OtherRef
11103 = OtherRefType->getAs<LValueReferenceType>()) {
11104 OtherRefType = OtherRef->getPointeeType();
11105 OtherQuals = OtherRefType.getQualifiers();
11106 }
11107
11108 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011109 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11110 ? CopyAssignOperator->getLocEnd()
11111 : CopyAssignOperator->getLocation();
11112
Pavel Labath58934982013-08-30 08:52:28 +000011113 // Builds a DeclRefExpr for the "other" object.
11114 RefBuilder OtherRef(Other, OtherRefType);
11115
11116 // Builds the "this" pointer.
11117 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011118
11119 // Assign base classes.
11120 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011121 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011122 // Form the assignment:
11123 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011124 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011125 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011126 Invalid = true;
11127 continue;
11128 }
11129
John McCallcf142162010-08-07 06:22:56 +000011130 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011131 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011132
Douglas Gregorb139cd52010-05-01 20:49:11 +000011133 // Construct the "from" expression, which is an implicit cast to the
11134 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011135 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11136 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011137
11138 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011139 DerefBuilder DerefThis(This);
11140 CastBuilder To(DerefThis,
11141 Context.getCVRQualifiedType(
11142 BaseType, CopyAssignOperator->getTypeQualifiers()),
11143 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011144
11145 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011146 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011147 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011148 /*CopyingBaseSubobject=*/true,
11149 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011150 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011151 Diag(CurrentLocation, diag::note_member_synthesized_at)
11152 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11153 CopyAssignOperator->setInvalidDecl();
11154 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011155 }
11156
11157 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011158 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011159 }
11160
Douglas Gregorb139cd52010-05-01 20:49:11 +000011161 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011162 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011163 // FIXME: We should form some kind of AST representation for the implied
11164 // memcpy in a union copy operation.
11165 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011166 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011167
11168 if (Field->isInvalidDecl()) {
11169 Invalid = true;
11170 continue;
11171 }
11172
Douglas Gregorb139cd52010-05-01 20:49:11 +000011173 // Check for members of reference type; we can't copy those.
11174 if (Field->getType()->isReferenceType()) {
11175 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11176 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11177 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011178 Diag(CurrentLocation, diag::note_member_synthesized_at)
11179 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011180 Invalid = true;
11181 continue;
11182 }
11183
11184 // Check for members of const-qualified, non-class type.
11185 QualType BaseType = Context.getBaseElementType(Field->getType());
11186 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11187 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11188 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11189 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011190 Diag(CurrentLocation, diag::note_member_synthesized_at)
11191 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011192 Invalid = true;
11193 continue;
11194 }
John McCall1b1a1db2011-06-17 00:18:42 +000011195
11196 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011197 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11198 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011199
11200 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011201 if (FieldType->isIncompleteArrayType()) {
11202 assert(ClassDecl->hasFlexibleArrayMember() &&
11203 "Incomplete array type is not valid");
11204 continue;
11205 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011206
11207 // Build references to the field in the object we're copying from and to.
11208 CXXScopeSpec SS; // Intentionally empty
11209 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11210 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011211 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011212 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011213
11214 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11215
11216 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011217
Douglas Gregorb139cd52010-05-01 20:49:11 +000011218 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011219 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011220 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011221 /*CopyingBaseSubobject=*/false,
11222 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011223 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011224 Diag(CurrentLocation, diag::note_member_synthesized_at)
11225 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11226 CopyAssignOperator->setInvalidDecl();
11227 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011228 }
11229
11230 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011231 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011232 }
11233
11234 if (!Invalid) {
11235 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011236 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011237
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011238 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011239 if (Return.isInvalid())
11240 Invalid = true;
11241 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011242 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011243
11244 if (Trap.hasErrorOccurred()) {
11245 Diag(CurrentLocation, diag::note_member_synthesized_at)
11246 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11247 Invalid = true;
11248 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011249 }
11250 }
11251
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011252 // The exception specification is needed because we are defining the
11253 // function.
11254 ResolveExceptionSpec(CurrentLocation,
11255 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11256
Douglas Gregorb139cd52010-05-01 20:49:11 +000011257 if (Invalid) {
11258 CopyAssignOperator->setInvalidDecl();
11259 return;
11260 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011261
11262 StmtResult Body;
11263 {
11264 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011265 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011266 /*isStmtExpr=*/false);
11267 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11268 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011269 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011270
11271 if (ASTMutationListener *L = getASTMutationListener()) {
11272 L->CompletedImplicitDefinition(CopyAssignOperator);
11273 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011274}
11275
Sebastian Redl22653ba2011-08-30 19:58:05 +000011276Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011277Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11278 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011279
Richard Smithd3b5c9082012-07-27 04:22:15 +000011280 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011281 if (ClassDecl->isInvalidDecl())
11282 return ExceptSpec;
11283
11284 // C++0x [except.spec]p14:
11285 // An implicitly declared special member function (Clause 12) shall have an
11286 // exception-specification. [...]
11287
11288 // It is unspecified whether or not an implicit move assignment operator
11289 // attempts to deduplicate calls to assignment operators of virtual bases are
11290 // made. As such, this exception specification is effectively unspecified.
11291 // Based on a similar decision made for constness in C++0x, we're erring on
11292 // the side of assuming such calls to be made regardless of whether they
11293 // actually happen.
11294 // Note that a move constructor is not implicitly declared when there are
11295 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000011296 for (const auto &Base : ClassDecl->bases()) {
11297 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000011298 continue;
11299
11300 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011301 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011302 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011303 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011304 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011305 }
11306
Aaron Ballman445a9392014-03-13 16:15:17 +000011307 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011308 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011309 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011310 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011311 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011312 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011313 }
11314
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011315 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011316 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011317 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011318 if (CXXMethodDecl *MoveAssign =
11319 LookupMovingAssignment(FieldClassDecl,
11320 FieldType.getCVRQualifiers(),
11321 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011322 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011323 }
11324 }
11325
11326 return ExceptSpec;
11327}
11328
11329CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011330 assert(ClassDecl->needsImplicitMoveAssignment());
11331
Richard Smith8bf22e52012-11-29 01:34:07 +000011332 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11333 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011334 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011335
Sebastian Redl22653ba2011-08-30 19:58:05 +000011336 // Note: The following rules are largely analoguous to the move
11337 // constructor rules.
11338
Sebastian Redl22653ba2011-08-30 19:58:05 +000011339 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11340 QualType RetType = Context.getLValueReferenceType(ArgType);
11341 ArgType = Context.getRValueReferenceType(ArgType);
11342
Richard Smith99005e62013-05-07 03:19:20 +000011343 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11344 CXXMoveAssignment,
11345 false);
11346
Sebastian Redl22653ba2011-08-30 19:58:05 +000011347 // An implicitly-declared move assignment operator is an inline public
11348 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011349 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11350 SourceLocation ClassLoc = ClassDecl->getLocation();
11351 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011352 CXXMethodDecl *MoveAssignment =
11353 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011354 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011355 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011356 MoveAssignment->setAccess(AS_public);
11357 MoveAssignment->setDefaulted();
11358 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011359
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011360 if (getLangOpts().CUDA) {
11361 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11362 MoveAssignment,
11363 /* ConstRHS */ false,
11364 /* Diagnose */ false);
11365 }
11366
Richard Smithd3b5c9082012-07-27 04:22:15 +000011367 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011368 FunctionProtoType::ExtProtoInfo EPI =
11369 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011370 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011371
Sebastian Redl22653ba2011-08-30 19:58:05 +000011372 // Add the parameter to the operator.
11373 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011374 ClassLoc, ClassLoc,
11375 /*Id=*/nullptr, ArgType,
11376 /*TInfo=*/nullptr, SC_None,
11377 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011378 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011379
Richard Smith6b02d462012-12-08 08:32:28 +000011380 MoveAssignment->setTrivial(
11381 ClassDecl->needsOverloadResolutionForMoveAssignment()
11382 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11383 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011384
Richard Smith12e79312016-05-13 06:47:56 +000011385 // Note that we have added this copy-assignment operator.
11386 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11387
11388 Scope *S = getScopeForContext(ClassDecl);
11389 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11390
Richard Smithd951a1d2012-02-18 02:02:13 +000011391 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011392 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11393 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011394 }
11395
Richard Smith12e79312016-05-13 06:47:56 +000011396 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011397 PushOnScopeChains(MoveAssignment, S, false);
11398 ClassDecl->addDecl(MoveAssignment);
11399
Sebastian Redl22653ba2011-08-30 19:58:05 +000011400 return MoveAssignment;
11401}
11402
Richard Smithb2504bd2013-11-04 04:26:14 +000011403/// Check if we're implicitly defining a move assignment operator for a class
11404/// with virtual bases. Such a move assignment might move-assign the virtual
11405/// base multiple times.
11406static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11407 SourceLocation CurrentLocation) {
11408 assert(!Class->isDependentContext() && "should not define dependent move");
11409
11410 // Only a virtual base could get implicitly move-assigned multiple times.
11411 // Only a non-trivial move assignment can observe this. We only want to
11412 // diagnose if we implicitly define an assignment operator that assigns
11413 // two base classes, both of which move-assign the same virtual base.
11414 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11415 Class->getNumBases() < 2)
11416 return;
11417
11418 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11419 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11420 VBaseMap VBases;
11421
Aaron Ballman574705e2014-03-13 15:41:46 +000011422 for (auto &BI : Class->bases()) {
11423 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011424 while (!Worklist.empty()) {
11425 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11426 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11427
11428 // If the base has no non-trivial move assignment operators,
11429 // we don't care about moves from it.
11430 if (!Base->hasNonTrivialMoveAssignment())
11431 continue;
11432
11433 // If there's nothing virtual here, skip it.
11434 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11435 continue;
11436
11437 // If we're not actually going to call a move assignment for this base,
11438 // or the selected move assignment is trivial, skip it.
11439 Sema::SpecialMemberOverloadResult *SMOR =
11440 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11441 /*ConstArg*/false, /*VolatileArg*/false,
11442 /*RValueThis*/true, /*ConstThis*/false,
11443 /*VolatileThis*/false);
11444 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11445 !SMOR->getMethod()->isMoveAssignmentOperator())
11446 continue;
11447
11448 if (BaseSpec->isVirtual()) {
11449 // We're going to move-assign this virtual base, and its move
11450 // assignment operator is not trivial. If this can happen for
11451 // multiple distinct direct bases of Class, diagnose it. (If it
11452 // only happens in one base, we'll diagnose it when synthesizing
11453 // that base class's move assignment operator.)
11454 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011455 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011456 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011457 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011458 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11459 << Class << Base;
11460 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11461 << (Base->getCanonicalDecl() ==
11462 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11463 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011464 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011465 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011466 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11467 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011468
11469 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011470 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011471 }
11472 } else {
11473 // Only walk over bases that have defaulted move assignment operators.
11474 // We assume that any user-provided move assignment operator handles
11475 // the multiple-moves-of-vbase case itself somehow.
11476 if (!SMOR->getMethod()->isDefaulted())
11477 continue;
11478
11479 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011480 for (auto &BI : Base->bases())
11481 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011482 }
11483 }
11484 }
11485}
11486
Sebastian Redl22653ba2011-08-30 19:58:05 +000011487void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11488 CXXMethodDecl *MoveAssignOperator) {
11489 assert((MoveAssignOperator->isDefaulted() &&
11490 MoveAssignOperator->isOverloadedOperator() &&
11491 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011492 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11493 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011494 "DefineImplicitMoveAssignment called for wrong function");
11495
11496 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11497
11498 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11499 MoveAssignOperator->setInvalidDecl();
11500 return;
11501 }
11502
Eli Friedman276dd182013-09-05 00:02:25 +000011503 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011504
Eli Friedmaneaf34142012-10-18 20:14:08 +000011505 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011506 DiagnosticErrorTrap Trap(Diags);
11507
11508 // C++0x [class.copy]p28:
11509 // The implicitly-defined or move assignment operator for a non-union class
11510 // X performs memberwise move assignment of its subobjects. The direct base
11511 // classes of X are assigned first, in the order of their declaration in the
11512 // base-specifier-list, and then the immediate non-static data members of X
11513 // are assigned, in the order in which they were declared in the class
11514 // definition.
11515
Richard Smithb2504bd2013-11-04 04:26:14 +000011516 // Issue a warning if our implicit move assignment operator will move
11517 // from a virtual base more than once.
11518 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011519
Sebastian Redl22653ba2011-08-30 19:58:05 +000011520 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011521 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011522
11523 // The parameter for the "other" object, which we are move from.
11524 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11525 QualType OtherRefType = Other->getType()->
11526 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011527 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011528 "Bad argument type of defaulted move assignment");
11529
11530 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011531 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11532 ? MoveAssignOperator->getLocEnd()
11533 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011534
Pavel Labath58934982013-08-30 08:52:28 +000011535 // Builds a reference to the "other" object.
11536 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011537 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011538 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011539
Pavel Labath58934982013-08-30 08:52:28 +000011540 // Builds the "this" pointer.
11541 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011542
Sebastian Redl22653ba2011-08-30 19:58:05 +000011543 // Assign base classes.
11544 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011545 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011546 // C++11 [class.copy]p28:
11547 // It is unspecified whether subobjects representing virtual base classes
11548 // are assigned more than once by the implicitly-defined copy assignment
11549 // operator.
11550 // FIXME: Do not assign to a vbase that will be assigned by some other base
11551 // class. For a move-assignment, this can result in the vbase being moved
11552 // multiple times.
11553
Sebastian Redl22653ba2011-08-30 19:58:05 +000011554 // Form the assignment:
11555 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011556 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011557 if (!BaseType->isRecordType()) {
11558 Invalid = true;
11559 continue;
11560 }
11561
11562 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011563 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011564
11565 // Construct the "from" expression, which is an implicit cast to the
11566 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011567 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011568
11569 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011570 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011571
11572 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011573 CastBuilder To(DerefThis,
11574 Context.getCVRQualifiedType(
11575 BaseType, MoveAssignOperator->getTypeQualifiers()),
11576 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011577
11578 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011579 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011580 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011581 /*CopyingBaseSubobject=*/true,
11582 /*Copying=*/false);
11583 if (Move.isInvalid()) {
11584 Diag(CurrentLocation, diag::note_member_synthesized_at)
11585 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11586 MoveAssignOperator->setInvalidDecl();
11587 return;
11588 }
11589
11590 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011591 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011592 }
11593
Sebastian Redl22653ba2011-08-30 19:58:05 +000011594 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011595 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011596 // FIXME: We should form some kind of AST representation for the implied
11597 // memcpy in a union copy operation.
11598 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011599 continue;
11600
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011601 if (Field->isInvalidDecl()) {
11602 Invalid = true;
11603 continue;
11604 }
11605
Sebastian Redl22653ba2011-08-30 19:58:05 +000011606 // Check for members of reference type; we can't move those.
11607 if (Field->getType()->isReferenceType()) {
11608 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11609 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11610 Diag(Field->getLocation(), diag::note_declared_at);
11611 Diag(CurrentLocation, diag::note_member_synthesized_at)
11612 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11613 Invalid = true;
11614 continue;
11615 }
11616
11617 // Check for members of const-qualified, non-class type.
11618 QualType BaseType = Context.getBaseElementType(Field->getType());
11619 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11620 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11621 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11622 Diag(Field->getLocation(), diag::note_declared_at);
11623 Diag(CurrentLocation, diag::note_member_synthesized_at)
11624 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11625 Invalid = true;
11626 continue;
11627 }
11628
11629 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011630 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11631 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011632
11633 QualType FieldType = Field->getType().getNonReferenceType();
11634 if (FieldType->isIncompleteArrayType()) {
11635 assert(ClassDecl->hasFlexibleArrayMember() &&
11636 "Incomplete array type is not valid");
11637 continue;
11638 }
11639
11640 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011641 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11642 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011643 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011644 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011645 MemberBuilder From(MoveOther, OtherRefType,
11646 /*IsArrow=*/false, MemberLookup);
11647 MemberBuilder To(This, getCurrentThisType(),
11648 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011649
Pavel Labath58934982013-08-30 08:52:28 +000011650 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011651 "Member reference with rvalue base must be rvalue except for reference "
11652 "members, which aren't allowed for move assignment.");
11653
Sebastian Redl22653ba2011-08-30 19:58:05 +000011654 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011655 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011656 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011657 /*CopyingBaseSubobject=*/false,
11658 /*Copying=*/false);
11659 if (Move.isInvalid()) {
11660 Diag(CurrentLocation, diag::note_member_synthesized_at)
11661 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11662 MoveAssignOperator->setInvalidDecl();
11663 return;
11664 }
Richard Smith11d19592012-11-12 23:33:00 +000011665
Sebastian Redl22653ba2011-08-30 19:58:05 +000011666 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011667 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011668 }
11669
11670 if (!Invalid) {
11671 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011672 ExprResult ThisObj =
11673 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11674
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011675 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011676 if (Return.isInvalid())
11677 Invalid = true;
11678 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011679 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011680
11681 if (Trap.hasErrorOccurred()) {
11682 Diag(CurrentLocation, diag::note_member_synthesized_at)
11683 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11684 Invalid = true;
11685 }
11686 }
11687 }
11688
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011689 // The exception specification is needed because we are defining the
11690 // function.
11691 ResolveExceptionSpec(CurrentLocation,
11692 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11693
Sebastian Redl22653ba2011-08-30 19:58:05 +000011694 if (Invalid) {
11695 MoveAssignOperator->setInvalidDecl();
11696 return;
11697 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011698
11699 StmtResult Body;
11700 {
11701 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011702 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011703 /*isStmtExpr=*/false);
11704 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11705 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011706 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011707
11708 if (ASTMutationListener *L = getASTMutationListener()) {
11709 L->CompletedImplicitDefinition(MoveAssignOperator);
11710 }
11711}
11712
Richard Smithd3b5c9082012-07-27 04:22:15 +000011713Sema::ImplicitExceptionSpecification
11714Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11715 CXXRecordDecl *ClassDecl = MD->getParent();
11716
11717 ImplicitExceptionSpecification ExceptSpec(*this);
11718 if (ClassDecl->isInvalidDecl())
11719 return ExceptSpec;
11720
11721 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011722 assert(T->getNumParams() >= 1 && "not a copy ctor");
11723 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011724
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011725 // C++ [except.spec]p14:
11726 // An implicitly declared special member function (Clause 12) shall have an
11727 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000011728 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011729 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000011730 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011731 continue;
11732
Douglas Gregora6d69502010-07-02 23:41:54 +000011733 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011734 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011735 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011736 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000011737 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011738 }
Aaron Ballman445a9392014-03-13 16:15:17 +000011739 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000011740 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011741 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011742 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011743 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000011744 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011745 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011746 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011747 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000011748 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11749 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000011750 LookupCopyingConstructor(FieldClassDecl,
11751 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000011752 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011753 }
11754 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011755
Richard Smithd3b5c9082012-07-27 04:22:15 +000011756 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000011757}
11758
11759CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11760 CXXRecordDecl *ClassDecl) {
11761 // C++ [class.copy]p4:
11762 // If the class definition does not explicitly declare a copy
11763 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011764 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011765
Richard Smith8bf22e52012-11-29 01:34:07 +000011766 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11767 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011768 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011769
Alexis Hunt913820d2011-05-13 06:10:58 +000011770 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11771 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011772 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011773 if (Const)
11774 ArgType = ArgType.withConst();
11775 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011776
Richard Smithb5800092012-06-10 05:43:50 +000011777 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11778 CXXCopyConstructor,
11779 Const);
11780
Douglas Gregor54be3392010-07-01 17:57:27 +000011781 DeclarationName Name
11782 = Context.DeclarationNames.getCXXConstructorName(
11783 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011784 SourceLocation ClassLoc = ClassDecl->getLocation();
11785 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011786
11787 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011788 // member of its class.
11789 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011790 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011791 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011792 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011793 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011794 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011795
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011796 if (getLangOpts().CUDA) {
11797 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11798 CopyConstructor,
11799 /* ConstRHS */ Const,
11800 /* Diagnose */ false);
11801 }
11802
Richard Smithd3b5c9082012-07-27 04:22:15 +000011803 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011804 FunctionProtoType::ExtProtoInfo EPI =
11805 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011806 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011807 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011808
Douglas Gregor54be3392010-07-01 17:57:27 +000011809 // Add the parameter to the constructor.
11810 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011811 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011812 /*IdentifierInfo=*/nullptr,
11813 ArgType, /*TInfo=*/nullptr,
11814 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011815 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011816
Richard Smith6b02d462012-12-08 08:32:28 +000011817 CopyConstructor->setTrivial(
11818 ClassDecl->needsOverloadResolutionForCopyConstructor()
11819 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11820 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011821
Richard Smith6b02d462012-12-08 08:32:28 +000011822 // Note that we have declared this constructor.
11823 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11824
Richard Smith12e79312016-05-13 06:47:56 +000011825 Scope *S = getScopeForContext(ClassDecl);
11826 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11827
11828 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11829 SetDeclDeleted(CopyConstructor, ClassLoc);
11830
11831 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011832 PushOnScopeChains(CopyConstructor, S, false);
11833 ClassDecl->addDecl(CopyConstructor);
11834
Douglas Gregor54be3392010-07-01 17:57:27 +000011835 return CopyConstructor;
11836}
11837
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011838void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011839 CXXConstructorDecl *CopyConstructor) {
11840 assert((CopyConstructor->isDefaulted() &&
11841 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011842 !CopyConstructor->doesThisDeclarationHaveABody() &&
11843 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011844 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011845
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011846 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011847 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011848
Richard Smithd577fbb2013-06-13 03:23:42 +000011849 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011850 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011851 // deprecated if the class has a user-declared copy assignment operator
11852 // or a user-declared destructor.
11853 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11854 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11855
Eli Friedmaneaf34142012-10-18 20:14:08 +000011856 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011857 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011858
David Blaikie3fc2f912013-01-17 05:26:25 +000011859 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011860 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011861 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011862 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011863 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011864 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011865 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11866 ? CopyConstructor->getLocEnd()
11867 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011868 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011869 CopyConstructor->setBody(
11870 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011871 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011872
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011873 // The exception specification is needed because we are defining the
11874 // function.
11875 ResolveExceptionSpec(CurrentLocation,
11876 CopyConstructor->getType()->castAs<FunctionProtoType>());
11877
Eli Friedman276dd182013-09-05 00:02:25 +000011878 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011879 MarkVTableUsed(CurrentLocation, ClassDecl);
11880
Sebastian Redlab238a72011-04-24 16:28:06 +000011881 if (ASTMutationListener *L = getASTMutationListener()) {
11882 L->CompletedImplicitDefinition(CopyConstructor);
11883 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011884}
11885
Sebastian Redl22653ba2011-08-30 19:58:05 +000011886Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011887Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11888 CXXRecordDecl *ClassDecl = MD->getParent();
11889
Sebastian Redl22653ba2011-08-30 19:58:05 +000011890 // C++ [except.spec]p14:
11891 // An implicitly declared special member function (Clause 12) shall have an
11892 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011893 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011894 if (ClassDecl->isInvalidDecl())
11895 return ExceptSpec;
11896
11897 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011898 for (const auto &B : ClassDecl->bases()) {
11899 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011900 continue;
11901
Aaron Ballman574705e2014-03-13 15:41:46 +000011902 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011903 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011904 CXXConstructorDecl *Constructor =
11905 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011906 // If this is a deleted function, add it anyway. This might be conformant
11907 // with the standard. This might not. I'm not sure. It might not matter.
11908 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011909 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011910 }
11911 }
11912
11913 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011914 for (const auto &B : ClassDecl->vbases()) {
11915 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011916 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011917 CXXConstructorDecl *Constructor =
11918 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011919 // If this is a deleted function, add it anyway. This might be conformant
11920 // with the standard. This might not. I'm not sure. It might not matter.
11921 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011922 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011923 }
11924 }
11925
11926 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011927 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011928 QualType FieldType = Context.getBaseElementType(F->getType());
11929 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11930 CXXConstructorDecl *Constructor =
11931 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011932 // If this is a deleted function, add it anyway. This might be conformant
11933 // with the standard. This might not. I'm not sure. It might not matter.
11934 // In particular, the problem is that this function never gets called. It
11935 // might just be ill-formed because this function attempts to refer to
11936 // a deleted function here.
11937 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011938 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011939 }
11940 }
11941
11942 return ExceptSpec;
11943}
11944
11945CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11946 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011947 assert(ClassDecl->needsImplicitMoveConstructor());
11948
Richard Smith8bf22e52012-11-29 01:34:07 +000011949 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11950 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011951 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011952
Sebastian Redl22653ba2011-08-30 19:58:05 +000011953 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11954 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011955
Richard Smithb5800092012-06-10 05:43:50 +000011956 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11957 CXXMoveConstructor,
11958 false);
11959
Sebastian Redl22653ba2011-08-30 19:58:05 +000011960 DeclarationName Name
11961 = Context.DeclarationNames.getCXXConstructorName(
11962 Context.getCanonicalType(ClassType));
11963 SourceLocation ClassLoc = ClassDecl->getLocation();
11964 DeclarationNameInfo NameInfo(Name, ClassLoc);
11965
Richard Smith99005e62013-05-07 03:19:20 +000011966 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011967 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011968 // member of its class.
11969 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011970 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011971 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011972 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011973 MoveConstructor->setAccess(AS_public);
11974 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011975
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011976 if (getLangOpts().CUDA) {
11977 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11978 MoveConstructor,
11979 /* ConstRHS */ false,
11980 /* Diagnose */ false);
11981 }
11982
Richard Smithd3b5c9082012-07-27 04:22:15 +000011983 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011984 FunctionProtoType::ExtProtoInfo EPI =
11985 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011986 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011987 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011988
Sebastian Redl22653ba2011-08-30 19:58:05 +000011989 // Add the parameter to the constructor.
11990 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11991 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011992 /*IdentifierInfo=*/nullptr,
11993 ArgType, /*TInfo=*/nullptr,
11994 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011995 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011996
Richard Smith6b02d462012-12-08 08:32:28 +000011997 MoveConstructor->setTrivial(
11998 ClassDecl->needsOverloadResolutionForMoveConstructor()
11999 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12000 : ClassDecl->hasTrivialMoveConstructor());
12001
Richard Smith12e79312016-05-13 06:47:56 +000012002 // Note that we have declared this constructor.
12003 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12004
12005 Scope *S = getScopeForContext(ClassDecl);
12006 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12007
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012008 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012009 ClassDecl->setImplicitMoveConstructorIsDeleted();
12010 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012011 }
12012
Richard Smith12e79312016-05-13 06:47:56 +000012013 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012014 PushOnScopeChains(MoveConstructor, S, false);
12015 ClassDecl->addDecl(MoveConstructor);
12016
12017 return MoveConstructor;
12018}
12019
12020void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12021 CXXConstructorDecl *MoveConstructor) {
12022 assert((MoveConstructor->isDefaulted() &&
12023 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012024 !MoveConstructor->doesThisDeclarationHaveABody() &&
12025 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012026 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12027
12028 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12029 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12030
Eli Friedmaneaf34142012-10-18 20:14:08 +000012031 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012032 DiagnosticErrorTrap Trap(Diags);
12033
David Blaikie3fc2f912013-01-17 05:26:25 +000012034 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012035 Trap.hasErrorOccurred()) {
12036 Diag(CurrentLocation, diag::note_member_synthesized_at)
12037 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12038 MoveConstructor->setInvalidDecl();
12039 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012040 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12041 ? MoveConstructor->getLocEnd()
12042 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012043 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012044 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012045 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012046 }
12047
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012048 // The exception specification is needed because we are defining the
12049 // function.
12050 ResolveExceptionSpec(CurrentLocation,
12051 MoveConstructor->getType()->castAs<FunctionProtoType>());
12052
Eli Friedman276dd182013-09-05 00:02:25 +000012053 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012054 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012055
12056 if (ASTMutationListener *L = getASTMutationListener()) {
12057 L->CompletedImplicitDefinition(MoveConstructor);
12058 }
12059}
12060
Douglas Gregor74f7d502012-02-15 19:33:52 +000012061bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012062 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012063}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012064
12065void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012066 SourceLocation CurrentLocation,
12067 CXXConversionDecl *Conv) {
12068 CXXRecordDecl *Lambda = Conv->getParent();
12069 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12070 // If we are defining a specialization of a conversion to function-ptr
12071 // cache the deduced template arguments for this specialization
12072 // so that we can use them to retrieve the corresponding call-operator
12073 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012074 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12075
Faisal Vali571df122013-09-29 08:45:24 +000012076 // Retrieve the corresponding call-operator specialization.
12077 if (Lambda->isGenericLambda()) {
12078 assert(Conv->isFunctionTemplateSpecialization());
12079 FunctionTemplateDecl *CallOpTemplate =
12080 CallOp->getDescribedFunctionTemplate();
12081 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012082 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012083 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012084 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012085 InsertPos);
12086 assert(CallOpSpec &&
12087 "Conversion operator must have a corresponding call operator");
12088 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12089 }
12090 // Mark the call operator referenced (and add to pending instantiations
12091 // if necessary).
12092 // For both the conversion and static-invoker template specializations
12093 // we construct their body's in this function, so no need to add them
12094 // to the PendingInstantiations.
12095 MarkFunctionReferenced(CurrentLocation, CallOp);
12096
Eli Friedmaneaf34142012-10-18 20:14:08 +000012097 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012098 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012099
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012100 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012101 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12102 // ... and get the corresponding specialization for a generic lambda.
12103 if (Lambda->isGenericLambda()) {
12104 assert(DeducedTemplateArgs &&
12105 "Must have deduced template arguments from Conversion Operator");
12106 FunctionTemplateDecl *InvokeTemplate =
12107 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012108 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012109 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012110 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012111 InsertPos);
12112 assert(InvokeSpec &&
12113 "Must have a corresponding static invoker specialization");
12114 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12115 }
12116 // Construct the body of the conversion function { return __invoke; }.
12117 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012118 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012119 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012120 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012121 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12122 Conv->getLocation(),
12123 Conv->getLocation()));
12124
12125 Conv->markUsed(Context);
12126 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012127
Faisal Vali571df122013-09-29 08:45:24 +000012128 // Fill in the __invoke function with a dummy implementation. IR generation
12129 // will fill in the actual details.
12130 Invoker->markUsed(Context);
12131 Invoker->setReferenced();
12132 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12133
Douglas Gregord3b672c2012-02-16 01:06:16 +000012134 if (ASTMutationListener *L = getASTMutationListener()) {
12135 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012136 L->CompletedImplicitDefinition(Invoker);
12137 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012138}
12139
Faisal Vali571df122013-09-29 08:45:24 +000012140
12141
Douglas Gregord3b672c2012-02-16 01:06:16 +000012142void Sema::DefineImplicitLambdaToBlockPointerConversion(
12143 SourceLocation CurrentLocation,
12144 CXXConversionDecl *Conv)
12145{
Faisal Vali850da1a2013-09-29 17:08:32 +000012146 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012147
Eli Friedman276dd182013-09-05 00:02:25 +000012148 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012149
Eli Friedmaneaf34142012-10-18 20:14:08 +000012150 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012151 DiagnosticErrorTrap Trap(Diags);
12152
Douglas Gregored90df32012-02-22 05:02:47 +000012153 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012154 Expr *This = ActOnCXXThis(CurrentLocation).get();
12155 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012156
Eli Friedman98b01ed2012-03-01 04:01:32 +000012157 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12158 Conv->getLocation(),
12159 Conv, DerefThis);
12160
12161 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12162 // behavior. Note that only the general conversion function does this
12163 // (since it's unusable otherwise); in the case where we inline the
12164 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012165 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012166 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12167 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012168 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012169
12170 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012171 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012172 Conv->setInvalidDecl();
12173 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012174 }
Douglas Gregored90df32012-02-22 05:02:47 +000012175
Douglas Gregored90df32012-02-22 05:02:47 +000012176 // Create the return statement that returns the block from the conversion
12177 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012178 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012179 if (Return.isInvalid()) {
12180 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12181 Conv->setInvalidDecl();
12182 return;
12183 }
12184
12185 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012186 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012187 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012188 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012189 Conv->getLocation()));
12190
Douglas Gregored90df32012-02-22 05:02:47 +000012191 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012192 if (ASTMutationListener *L = getASTMutationListener()) {
12193 L->CompletedImplicitDefinition(Conv);
12194 }
12195}
12196
Douglas Gregord2f70072012-03-10 06:53:13 +000012197/// \brief Determine whether the given list arguments contains exactly one
12198/// "real" (non-default) argument.
12199static bool hasOneRealArgument(MultiExprArg Args) {
12200 switch (Args.size()) {
12201 case 0:
12202 return false;
12203
12204 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012205 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012206 return false;
12207
12208 // fall through
12209 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012210 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012211 }
12212
12213 return false;
12214}
12215
John McCalldadc5752010-08-24 06:29:42 +000012216ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012217Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012218 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012219 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012220 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012221 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012222 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012223 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012224 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012225 unsigned ConstructKind,
12226 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012227 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012228
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012229 // C++0x [class.copy]p34:
12230 // When certain criteria are met, an implementation is allowed to
12231 // omit the copy/move construction of a class object, even if the
12232 // copy/move constructor and/or destructor for the object have
12233 // side effects. [...]
12234 // - when a temporary class object that has not been bound to a
12235 // reference (12.2) would be copied/moved to a class object
12236 // with the same cv-unqualified type, the copy/move operation
12237 // can be omitted by constructing the temporary object
12238 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012239 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012240 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012241 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012242 Elidable = SubExpr->isTemporaryObject(
12243 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012244 }
Mike Stump11289f42009-09-09 15:08:12 +000012245
Richard Smithc2bebe92016-05-11 20:37:46 +000012246 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12247 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012248 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012249 IsListInitialization,
12250 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012251 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012252}
12253
John McCalldadc5752010-08-24 06:29:42 +000012254ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012255Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012256 NamedDecl *FoundDecl,
12257 CXXConstructorDecl *Constructor,
12258 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012259 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012260 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012261 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012262 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012263 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012264 unsigned ConstructKind,
12265 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012266 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012267 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012268 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12269 return ExprError();
12270 }
Richard Smith5179eb72016-06-28 19:03:57 +000012271
Richard Smithc83bf822016-06-10 00:58:19 +000012272 return BuildCXXConstructExpr(
12273 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12274 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12275 RequiresZeroInit, ConstructKind, ParenRange);
12276}
12277
12278/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12279/// including handling of its default argument expressions.
12280ExprResult
12281Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12282 CXXConstructorDecl *Constructor,
12283 bool Elidable,
12284 MultiExprArg ExprArgs,
12285 bool HadMultipleCandidates,
12286 bool IsListInitialization,
12287 bool IsStdInitListInitialization,
12288 bool RequiresZeroInit,
12289 unsigned ConstructKind,
12290 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012291 assert(declaresSameEntity(
12292 Constructor->getParent(),
12293 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12294 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012295 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012296 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12297 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012298
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012299 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012300 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012301 ExprArgs, HadMultipleCandidates, IsListInitialization,
12302 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012303 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12304 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012305}
12306
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012307ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12308 assert(Field->hasInClassInitializer());
12309
12310 // If we already have the in-class initializer nothing needs to be done.
12311 if (Field->getInClassInitializer())
12312 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12313
12314 // Maybe we haven't instantiated the in-class initializer. Go check the
12315 // pattern FieldDecl to see if it has one.
12316 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12317
12318 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12319 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12320 DeclContext::lookup_result Lookup =
12321 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012322
12323 // Lookup can return at most two results: the pattern for the field, or the
12324 // injected class name of the parent record. No other member can have the
12325 // same name as the field.
12326 assert(!Lookup.empty() && Lookup.size() <= 2 &&
12327 "more than two lookup results for field name");
12328 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12329 if (!Pattern) {
12330 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12331 "cannot have other non-field member with same name");
12332 Pattern = cast<FieldDecl>(Lookup[1]);
12333 }
12334
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012335 if (InstantiateInClassInitializer(Loc, Field, Pattern,
12336 getTemplateInstantiationArgs(Field)))
12337 return ExprError();
12338 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12339 }
12340
12341 // DR1351:
12342 // If the brace-or-equal-initializer of a non-static data member
12343 // invokes a defaulted default constructor of its class or of an
12344 // enclosing class in a potentially evaluated subexpression, the
12345 // program is ill-formed.
12346 //
12347 // This resolution is unworkable: the exception specification of the
12348 // default constructor can be needed in an unevaluated context, in
12349 // particular, in the operand of a noexcept-expression, and we can be
12350 // unable to compute an exception specification for an enclosed class.
12351 //
12352 // Any attempt to resolve the exception specification of a defaulted default
12353 // constructor before the initializer is lexically complete will ultimately
12354 // come here at which point we can diagnose it.
12355 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12356 if (OutermostClass == ParentRD) {
12357 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12358 << ParentRD << Field;
12359 } else {
12360 Diag(Field->getLocEnd(),
12361 diag::err_in_class_initializer_not_yet_parsed_outer_class)
12362 << ParentRD << OutermostClass << Field;
12363 }
12364
12365 return ExprError();
12366}
12367
John McCall03c48482010-02-02 09:10:11 +000012368void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012369 if (VD->isInvalidDecl()) return;
12370
John McCall03c48482010-02-02 09:10:11 +000012371 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012372 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012373 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012374 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012375
Chandler Carruth86d17d32011-03-27 21:26:48 +000012376 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012377 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012378 CheckDestructorAccess(VD->getLocation(), Destructor,
12379 PDiag(diag::err_access_dtor_var)
12380 << VD->getDeclName()
12381 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012382 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012383
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012384 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012385 if (!VD->hasGlobalStorage()) return;
12386
12387 // Emit warning for non-trivial dtor in global scope (a real global,
12388 // class-static, function-static).
12389 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12390
12391 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012392 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012393 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012394}
12395
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012396/// \brief Given a constructor and the set of arguments provided for the
12397/// constructor, convert the arguments and add any required default arguments
12398/// to form a proper call to this constructor.
12399///
12400/// \returns true if an error occurred, false otherwise.
12401bool
12402Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12403 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012404 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012405 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012406 bool AllowExplicit,
12407 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012408 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12409 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012410 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012411
12412 const FunctionProtoType *Proto
12413 = Constructor->getType()->getAs<FunctionProtoType>();
12414 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012415 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012416
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012417 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012418 if (NumArgs < NumParams)
12419 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012420 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012421 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012422
12423 VariadicCallType CallType =
12424 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012425 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012426 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012427 Proto, 0,
12428 llvm::makeArrayRef(Args, NumArgs),
12429 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012430 CallType, AllowExplicit,
12431 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012432 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012433
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012434 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012435
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012436 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012437 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012438 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012439
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012440 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012441}
12442
Anders Carlssone363c8e2009-12-12 00:32:00 +000012443static inline bool
12444CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12445 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012446 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012447 if (isa<NamespaceDecl>(DC)) {
12448 return SemaRef.Diag(FnDecl->getLocation(),
12449 diag::err_operator_new_delete_declared_in_namespace)
12450 << FnDecl->getDeclName();
12451 }
12452
12453 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012454 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012455 return SemaRef.Diag(FnDecl->getLocation(),
12456 diag::err_operator_new_delete_declared_static)
12457 << FnDecl->getDeclName();
12458 }
12459
Anders Carlsson60659a82009-12-12 02:43:16 +000012460 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012461}
12462
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012463static inline bool
12464CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12465 CanQualType ExpectedResultType,
12466 CanQualType ExpectedFirstParamType,
12467 unsigned DependentParamTypeDiag,
12468 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012469 QualType ResultType =
12470 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012471
12472 // Check that the result type is not dependent.
12473 if (ResultType->isDependentType())
12474 return SemaRef.Diag(FnDecl->getLocation(),
12475 diag::err_operator_new_delete_dependent_result_type)
12476 << FnDecl->getDeclName() << ExpectedResultType;
12477
12478 // Check that the result type is what we expect.
12479 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12480 return SemaRef.Diag(FnDecl->getLocation(),
12481 diag::err_operator_new_delete_invalid_result_type)
12482 << FnDecl->getDeclName() << ExpectedResultType;
12483
12484 // A function template must have at least 2 parameters.
12485 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12486 return SemaRef.Diag(FnDecl->getLocation(),
12487 diag::err_operator_new_delete_template_too_few_parameters)
12488 << FnDecl->getDeclName();
12489
12490 // The function decl must have at least 1 parameter.
12491 if (FnDecl->getNumParams() == 0)
12492 return SemaRef.Diag(FnDecl->getLocation(),
12493 diag::err_operator_new_delete_too_few_parameters)
12494 << FnDecl->getDeclName();
12495
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012496 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012497 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12498 if (FirstParamType->isDependentType())
12499 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12500 << FnDecl->getDeclName() << ExpectedFirstParamType;
12501
12502 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012503 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012504 ExpectedFirstParamType)
12505 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12506 << FnDecl->getDeclName() << ExpectedFirstParamType;
12507
12508 return false;
12509}
12510
Anders Carlsson12308f42009-12-11 23:23:22 +000012511static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012512CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012513 // C++ [basic.stc.dynamic.allocation]p1:
12514 // A program is ill-formed if an allocation function is declared in a
12515 // namespace scope other than global scope or declared static in global
12516 // scope.
12517 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12518 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012519
12520 CanQualType SizeTy =
12521 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12522
12523 // C++ [basic.stc.dynamic.allocation]p1:
12524 // The return type shall be void*. The first parameter shall have type
12525 // std::size_t.
12526 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12527 SizeTy,
12528 diag::err_operator_new_dependent_param_type,
12529 diag::err_operator_new_param_type))
12530 return true;
12531
12532 // C++ [basic.stc.dynamic.allocation]p1:
12533 // The first parameter shall not have an associated default argument.
12534 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012535 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012536 diag::err_operator_new_default_arg)
12537 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12538
12539 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012540}
12541
12542static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012543CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012544 // C++ [basic.stc.dynamic.deallocation]p1:
12545 // A program is ill-formed if deallocation functions are declared in a
12546 // namespace scope other than global scope or declared static in global
12547 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012548 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12549 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012550
12551 // C++ [basic.stc.dynamic.deallocation]p2:
12552 // Each deallocation function shall return void and its first parameter
12553 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012554 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12555 SemaRef.Context.VoidPtrTy,
12556 diag::err_operator_delete_dependent_param_type,
12557 diag::err_operator_delete_param_type))
12558 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012559
Anders Carlsson12308f42009-12-11 23:23:22 +000012560 return false;
12561}
12562
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012563/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12564/// of this overloaded operator is well-formed. If so, returns false;
12565/// otherwise, emits appropriate diagnostics and returns true.
12566bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012567 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012568 "Expected an overloaded operator declaration");
12569
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012570 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12571
Mike Stump11289f42009-09-09 15:08:12 +000012572 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012573 // The allocation and deallocation functions, operator new,
12574 // operator new[], operator delete and operator delete[], are
12575 // described completely in 3.7.3. The attributes and restrictions
12576 // found in the rest of this subclause do not apply to them unless
12577 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012578 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012579 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012580
Anders Carlsson22f443f2009-12-12 00:26:23 +000012581 if (Op == OO_New || Op == OO_Array_New)
12582 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012583
12584 // C++ [over.oper]p6:
12585 // An operator function shall either be a non-static member
12586 // function or be a non-member function and have at least one
12587 // parameter whose type is a class, a reference to a class, an
12588 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012589 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12590 if (MethodDecl->isStatic())
12591 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012592 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012593 } else {
12594 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012595 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012596 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012597 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12598 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012599 ClassOrEnumParam = true;
12600 break;
12601 }
12602 }
12603
Douglas Gregord69246b2008-11-17 16:14:12 +000012604 if (!ClassOrEnumParam)
12605 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012606 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012607 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012608 }
12609
12610 // C++ [over.oper]p8:
12611 // An operator function cannot have default arguments (8.3.6),
12612 // except where explicitly stated below.
12613 //
Mike Stump11289f42009-09-09 15:08:12 +000012614 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012615 // (C++ [over.call]p1).
12616 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012617 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012618 if (Param->hasDefaultArg())
12619 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012620 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012621 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012622 }
12623 }
12624
Douglas Gregor6cf08062008-11-10 13:38:07 +000012625 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12626 { false, false, false }
12627#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12628 , { Unary, Binary, MemberOnly }
12629#include "clang/Basic/OperatorKinds.def"
12630 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012631
Douglas Gregor6cf08062008-11-10 13:38:07 +000012632 bool CanBeUnaryOperator = OperatorUses[Op][0];
12633 bool CanBeBinaryOperator = OperatorUses[Op][1];
12634 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012635
12636 // C++ [over.oper]p8:
12637 // [...] Operator functions cannot have more or fewer parameters
12638 // than the number required for the corresponding operator, as
12639 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012640 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012641 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012642 if (Op != OO_Call &&
12643 ((NumParams == 1 && !CanBeUnaryOperator) ||
12644 (NumParams == 2 && !CanBeBinaryOperator) ||
12645 (NumParams < 1) || (NumParams > 2))) {
12646 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012647 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012648 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012649 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012650 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012651 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012652 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012653 assert(CanBeBinaryOperator &&
12654 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012655 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012656 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012657
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012658 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012659 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012660 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012661
Douglas Gregord69246b2008-11-17 16:14:12 +000012662 // Overloaded operators other than operator() cannot be variadic.
12663 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012664 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012665 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012666 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012667 }
12668
12669 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012670 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12671 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012672 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012673 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012674 }
12675
12676 // C++ [over.inc]p1:
12677 // The user-defined function called operator++ implements the
12678 // prefix and postfix ++ operator. If this function is a member
12679 // function with no parameters, or a non-member function with one
12680 // parameter of class or enumeration type, it defines the prefix
12681 // increment operator ++ for objects of that type. If the function
12682 // is a member function with one parameter (which shall be of type
12683 // int) or a non-member function with two parameters (the second
12684 // of which shall be of type int), it defines the postfix
12685 // increment operator ++ for objects of that type.
12686 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12687 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012688 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012689
Richard Smith538b52a2014-01-30 22:24:05 +000012690 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12691 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012692 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012693 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012694 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012695 }
12696
Douglas Gregord69246b2008-11-17 16:14:12 +000012697 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012698}
Chris Lattner3b024a32008-12-17 07:09:26 +000012699
Richard Smithc28aee62016-02-17 00:04:04 +000012700static bool
12701checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12702 FunctionTemplateDecl *TpDecl) {
12703 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12704
12705 // Must have one or two template parameters.
12706 if (TemplateParams->size() == 1) {
12707 NonTypeTemplateParmDecl *PmDecl =
12708 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12709
12710 // The template parameter must be a char parameter pack.
12711 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12712 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12713 return false;
12714
12715 } else if (TemplateParams->size() == 2) {
12716 TemplateTypeParmDecl *PmType =
12717 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12718 NonTypeTemplateParmDecl *PmArgs =
12719 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12720
12721 // The second template parameter must be a parameter pack with the
12722 // first template parameter as its type.
12723 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12724 PmArgs->isTemplateParameterPack()) {
12725 const TemplateTypeParmType *TArgs =
12726 PmArgs->getType()->getAs<TemplateTypeParmType>();
12727 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12728 TArgs->getIndex() == PmType->getIndex()) {
12729 if (SemaRef.ActiveTemplateInstantiations.empty())
12730 SemaRef.Diag(TpDecl->getLocation(),
12731 diag::ext_string_literal_operator_template);
12732 return false;
12733 }
12734 }
12735 }
12736
12737 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12738 diag::err_literal_operator_template)
12739 << TpDecl->getTemplateParameters()->getSourceRange();
12740 return true;
12741}
12742
Alexis Huntc88db062010-01-13 09:01:02 +000012743/// CheckLiteralOperatorDeclaration - Check whether the declaration
12744/// of this literal operator function is well-formed. If so, returns
12745/// false; otherwise, emits appropriate diagnostics and returns true.
12746bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012747 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012748 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12749 << FnDecl->getDeclName();
12750 return true;
12751 }
12752
Richard Smith72eebee2012-03-04 09:41:16 +000012753 if (FnDecl->isExternC()) {
12754 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12755 return true;
12756 }
12757
Richard Smithbcc22fc2012-03-09 08:00:36 +000012758 // This might be the definition of a literal operator template.
12759 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012760
Richard Smithbcc22fc2012-03-09 08:00:36 +000012761 // This might be a specialization of a literal operator template.
12762 if (!TpDecl)
12763 TpDecl = FnDecl->getPrimaryTemplate();
12764
Richard Smithb8b41d32013-10-07 19:57:58 +000012765 // template <char...> type operator "" name() and
12766 // template <class T, T...> type operator "" name() are the only valid
12767 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012768 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012769 if (FnDecl->param_size() != 0) {
12770 Diag(FnDecl->getLocation(),
12771 diag::err_literal_operator_template_with_params);
12772 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012773 }
Richard Smithc28aee62016-02-17 00:04:04 +000012774
12775 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12776 return true;
12777
12778 } else if (FnDecl->param_size() == 1) {
12779 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12780
12781 QualType ParamType = Param->getType().getUnqualifiedType();
12782
12783 // Only unsigned long long int, long double, any character type, and const
12784 // char * are allowed as the only parameters.
12785 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12786 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12787 Context.hasSameType(ParamType, Context.CharTy) ||
12788 Context.hasSameType(ParamType, Context.WideCharTy) ||
12789 Context.hasSameType(ParamType, Context.Char16Ty) ||
12790 Context.hasSameType(ParamType, Context.Char32Ty)) {
12791 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12792 QualType InnerType = Ptr->getPointeeType();
12793
12794 // Pointer parameter must be a const char *.
12795 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12796 Context.CharTy) &&
12797 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12798 Diag(Param->getSourceRange().getBegin(),
12799 diag::err_literal_operator_param)
12800 << ParamType << "'const char *'" << Param->getSourceRange();
12801 return true;
12802 }
12803
12804 } else if (ParamType->isRealFloatingType()) {
12805 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12806 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12807 return true;
12808
12809 } else if (ParamType->isIntegerType()) {
12810 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12811 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12812 return true;
12813
12814 } else {
12815 Diag(Param->getSourceRange().getBegin(),
12816 diag::err_literal_operator_invalid_param)
12817 << ParamType << Param->getSourceRange();
12818 return true;
12819 }
12820
12821 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012822 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12823
Richard Smithc28aee62016-02-17 00:04:04 +000012824 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012825
Richard Smithc28aee62016-02-17 00:04:04 +000012826 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12827
12828 // Two parameter function must have a pointer to const as a
12829 // first parameter; let's strip those qualifiers.
12830 const PointerType *PT = FirstParamType->getAs<PointerType>();
12831
12832 if (!PT) {
12833 Diag((*Param)->getSourceRange().getBegin(),
12834 diag::err_literal_operator_param)
12835 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12836 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012837 }
12838
Richard Smithc28aee62016-02-17 00:04:04 +000012839 QualType PointeeType = PT->getPointeeType();
12840 // First parameter must be const
12841 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12842 Diag((*Param)->getSourceRange().getBegin(),
12843 diag::err_literal_operator_param)
12844 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12845 return true;
12846 }
Alexis Huntc88db062010-01-13 09:01:02 +000012847
Richard Smithc28aee62016-02-17 00:04:04 +000012848 QualType InnerType = PointeeType.getUnqualifiedType();
12849 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12850 // are allowed as the first parameter to a two-parameter function
12851 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12852 Context.hasSameType(InnerType, Context.WideCharTy) ||
12853 Context.hasSameType(InnerType, Context.Char16Ty) ||
12854 Context.hasSameType(InnerType, Context.Char32Ty))) {
12855 Diag((*Param)->getSourceRange().getBegin(),
12856 diag::err_literal_operator_param)
12857 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12858 return true;
12859 }
12860
12861 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012862 ++Param;
12863
Richard Smithc28aee62016-02-17 00:04:04 +000012864 // The second parameter must be a std::size_t.
12865 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12866 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12867 Diag((*Param)->getSourceRange().getBegin(),
12868 diag::err_literal_operator_param)
12869 << SecondParamType << Context.getSizeType()
12870 << (*Param)->getSourceRange();
12871 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012872 }
Richard Smithc28aee62016-02-17 00:04:04 +000012873 } else {
12874 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012875 return true;
12876 }
12877
Richard Smithc28aee62016-02-17 00:04:04 +000012878 // Parameters are good.
12879
Richard Smith768cecc2012-03-09 08:16:22 +000012880 // A parameter-declaration-clause containing a default argument is not
12881 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012882 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012883 if (Param->hasDefaultArg()) {
12884 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012885 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012886 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012887 break;
12888 }
12889 }
12890
Richard Smith0df56f42012-03-08 02:39:21 +000012891 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012892 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12893 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012894 // C++11 [usrlit.suffix]p1:
12895 // Literal suffix identifiers that do not start with an underscore
12896 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012897 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12898 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012899 }
Richard Smith0df56f42012-03-08 02:39:21 +000012900
Alexis Huntc88db062010-01-13 09:01:02 +000012901 return false;
12902}
12903
Douglas Gregor07665a62009-01-05 19:45:36 +000012904/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12905/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012906/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12907/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012908/// the '{' brace. Otherwise, this linkage specification does not
12909/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012910Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012911 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012912 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012913 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12914 if (!Lit->isAscii()) {
12915 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12916 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012917 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012918 }
12919
12920 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012921 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012922 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012923 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012924 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012925 Language = LinkageSpecDecl::lang_cxx;
12926 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012927 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12928 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012929 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012930 }
Mike Stump11289f42009-09-09 15:08:12 +000012931
Chris Lattner438e5012008-12-17 07:13:27 +000012932 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000012933
Richard Smith4ee696d2014-02-17 23:25:27 +000012934 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12935 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000012936 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012937 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000012938 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000012939 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000012940}
12941
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000012942/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000012943/// the C++ linkage specification LinkageSpec. If RBraceLoc is
12944/// valid, it's the position of the closing '}' brace in a linkage
12945/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000012946Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012947 Decl *LinkageSpec,
12948 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012949 if (RBraceLoc.isValid()) {
12950 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12951 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012952 }
Richard Smith4ee696d2014-02-17 23:25:27 +000012953 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000012954 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000012955}
12956
Michael Han84324352013-02-22 17:15:32 +000012957Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12958 AttributeList *AttrList,
12959 SourceLocation SemiLoc) {
12960 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12961 // Attribute declarations appertain to empty declaration so we handle
12962 // them here.
12963 if (AttrList)
12964 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000012965
Michael Han84324352013-02-22 17:15:32 +000012966 CurContext->addDecl(ED);
12967 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000012968}
12969
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012970/// \brief Perform semantic analysis for the variable declaration that
12971/// occurs within a C++ catch clause, returning the newly-created
12972/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012973VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000012974 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012975 SourceLocation StartLoc,
12976 SourceLocation Loc,
12977 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012978 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012979 QualType ExDeclType = TInfo->getType();
12980
Sebastian Redl54c04d42008-12-22 19:15:10 +000012981 // Arrays and functions decay.
12982 if (ExDeclType->isArrayType())
12983 ExDeclType = Context.getArrayDecayedType(ExDeclType);
12984 else if (ExDeclType->isFunctionType())
12985 ExDeclType = Context.getPointerType(ExDeclType);
12986
12987 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12988 // The exception-declaration shall not denote a pointer or reference to an
12989 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000012990 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000012991 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012992 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000012993 Invalid = true;
12994 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012995
David Majnemere56d1a02016-06-08 16:05:07 +000012996 if (ExDeclType->isVariablyModifiedType()) {
12997 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12998 Invalid = true;
12999 }
13000
Sebastian Redl54c04d42008-12-22 19:15:10 +000013001 QualType BaseType = ExDeclType;
13002 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013003 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013004 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013005 BaseType = Ptr->getPointeeType();
13006 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013007 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013008 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013009 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013010 BaseType = Ref->getPointeeType();
13011 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013012 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013013 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013014 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013015 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013016 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013017
Mike Stump11289f42009-09-09 15:08:12 +000013018 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013019 RequireNonAbstractType(Loc, ExDeclType,
13020 diag::err_abstract_type_in_decl,
13021 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013022 Invalid = true;
13023
John McCall2ca705e2010-07-24 00:37:23 +000013024 // Only the non-fragile NeXT runtime currently supports C++ catches
13025 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013026 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013027 QualType T = ExDeclType;
13028 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13029 T = RT->getPointeeType();
13030
13031 if (T->isObjCObjectType()) {
13032 Diag(Loc, diag::err_objc_object_catch);
13033 Invalid = true;
13034 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013035 // FIXME: should this be a test for macosx-fragile specifically?
13036 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013037 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013038 }
13039 }
13040
Abramo Bagnaradff19302011-03-08 08:55:46 +000013041 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013042 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013043 ExDecl->setExceptionVariable(true);
13044
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013045 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013046 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013047 Invalid = true;
13048
Douglas Gregor750734c2011-07-06 18:14:43 +000013049 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013050 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013051 // Insulate this from anything else we might currently be parsing.
13052 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13053
Douglas Gregor6de584c2010-03-05 23:38:39 +000013054 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013055 // The object declared in an exception-declaration or, if the
13056 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013057 // copy-initialized (8.5) from the exception object. [...]
13058 // The object is destroyed when the handler exits, after the destruction
13059 // of any automatic objects initialized within the handler.
13060 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013061 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013062 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013063 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013064
13065 InitializedEntity entity =
13066 InitializedEntity::InitializeVariable(ExDecl);
13067 InitializationKind initKind =
13068 InitializationKind::CreateCopy(Loc, SourceLocation());
13069
13070 Expr *opaqueValue =
13071 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013072 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13073 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013074 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013075 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013076 else {
13077 // If the constructor used was non-trivial, set this as the
13078 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013079 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013080 if (!construct->getConstructor()->isTrivial()) {
13081 Expr *init = MaybeCreateExprWithCleanups(construct);
13082 ExDecl->setInit(init);
13083 }
13084
13085 // And make sure it's destructable.
13086 FinalizeVarWithDestructor(ExDecl, recordType);
13087 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013088 }
13089 }
13090
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013091 if (Invalid)
13092 ExDecl->setInvalidDecl();
13093
13094 return ExDecl;
13095}
13096
13097/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13098/// handler.
John McCall48871652010-08-21 09:40:31 +000013099Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013101 bool Invalid = D.isInvalidType();
13102
13103 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013104 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13105 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013106 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13107 D.getIdentifierLoc());
13108 Invalid = true;
13109 }
13110
Sebastian Redl54c04d42008-12-22 19:15:10 +000013111 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013112 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013113 LookupOrdinaryName,
13114 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013115 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013116 // it contains any previous declaration, except for function parameters in
13117 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013118 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013119 if (isDeclInScope(PrevDecl, CurContext, S)) {
13120 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13121 << D.getIdentifier();
13122 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13123 Invalid = true;
13124 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013125 // Maybe we will complain about the shadowed template parameter.
13126 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013127 }
13128
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013129 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013130 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13131 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013132 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013133 }
13134
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013135 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013136 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013137 D.getIdentifierLoc(),
13138 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013139 if (Invalid)
13140 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013141
Sebastian Redl54c04d42008-12-22 19:15:10 +000013142 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013143 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013144 PushOnScopeChains(ExDecl, S);
13145 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013146 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013147
Douglas Gregor758a8692009-06-17 21:51:59 +000013148 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013149 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013150}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013151
Abramo Bagnaraea947882011-03-08 16:41:52 +000013152Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013153 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013154 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013155 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013156 StringLiteral *AssertMessage =
13157 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013158
Richard Smithded9c2e2012-07-11 22:37:56 +000013159 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013160 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013161
13162 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13163 AssertMessage, RParenLoc, false);
13164}
13165
13166Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13167 Expr *AssertExpr,
13168 StringLiteral *AssertMessage,
13169 SourceLocation RParenLoc,
13170 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013171 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013172 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13173 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013174 // In a static_assert-declaration, the constant-expression shall be a
13175 // constant expression that can be contextually converted to bool.
13176 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13177 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013178 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013179
Richard Smith902ca212011-12-14 23:32:26 +000013180 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013181 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013182 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013183 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013184 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013185
Richard Smithded9c2e2012-07-11 22:37:56 +000013186 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013187 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013188 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013189 if (AssertMessage)
13190 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013191 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013192 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013193 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013194 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013195 }
Mike Stump11289f42009-09-09 15:08:12 +000013196
Abramo Bagnaraea947882011-03-08 16:41:52 +000013197 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013198 AssertExpr, AssertMessage, RParenLoc,
13199 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013200
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013201 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013202 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013203}
Sebastian Redlf769df52009-03-24 22:27:57 +000013204
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013205/// \brief Perform semantic analysis of the given friend type declaration.
13206///
13207/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013208FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013209 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013210 TypeSourceInfo *TSInfo) {
13211 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13212
13213 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013214 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013215
Richard Smithc8239732011-10-18 21:39:00 +000013216 // C++03 [class.friend]p2:
13217 // An elaborated-type-specifier shall be used in a friend declaration
13218 // for a class.*
13219 //
13220 // * The class-key of the elaborated-type-specifier is required.
13221 if (!ActiveTemplateInstantiations.empty()) {
13222 // Do not complain about the form of friend template types during
13223 // template instantiation; we will already have complained when the
13224 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000013225 } else {
13226 if (!T->isElaboratedTypeSpecifier()) {
13227 // If we evaluated the type to a record type, suggest putting
13228 // a tag in front.
13229 if (const RecordType *RT = T->getAs<RecordType>()) {
13230 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013231
13232 SmallString<16> InsertionText(" ");
13233 InsertionText += RD->getKindName();
13234
Nick Lewycky36722d22013-02-06 05:59:33 +000013235 Diag(TypeRange.getBegin(),
13236 getLangOpts().CPlusPlus11 ?
13237 diag::warn_cxx98_compat_unelaborated_friend_type :
13238 diag::ext_unelaborated_friend_type)
13239 << (unsigned) RD->getTagKind()
13240 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013241 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013242 InsertionText);
13243 } else {
13244 Diag(FriendLoc,
13245 getLangOpts().CPlusPlus11 ?
13246 diag::warn_cxx98_compat_nonclass_type_friend :
13247 diag::ext_nonclass_type_friend)
13248 << T
13249 << TypeRange;
13250 }
13251 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013252 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013253 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013254 diag::warn_cxx98_compat_enum_friend :
13255 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013256 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013257 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013258 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013259
Nick Lewycky36722d22013-02-06 05:59:33 +000013260 // C++11 [class.friend]p3:
13261 // A friend declaration that does not declare a function shall have one
13262 // of the following forms:
13263 // friend elaborated-type-specifier ;
13264 // friend simple-type-specifier ;
13265 // friend typename-specifier ;
13266 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13267 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13268 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013269
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013270 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013271 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013272 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013273 return FriendDecl::Create(Context, CurContext,
13274 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13275 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013276}
13277
John McCallace48cd2010-10-19 01:40:49 +000013278/// Handle a friend tag declaration where the scope specifier was
13279/// templated.
13280Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13281 unsigned TagSpec, SourceLocation TagLoc,
13282 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013283 IdentifierInfo *Name,
13284 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013285 AttributeList *Attr,
13286 MultiTemplateParamsArg TempParamLists) {
13287 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13288
13289 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013290 bool Invalid = false;
13291
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013292 if (TemplateParameterList *TemplateParams =
13293 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013294 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013295 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013296 if (TemplateParams->size() > 0) {
13297 // This is a declaration of a class template.
13298 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013299 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013300
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013301 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13302 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013303 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013304 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013305 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013306 } else {
13307 // The "template<>" header is extraneous.
13308 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13309 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13310 isExplicitSpecialization = true;
13311 }
13312 }
13313
Craig Topperc3ec1492014-05-26 06:22:03 +000013314 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013315
John McCallace48cd2010-10-19 01:40:49 +000013316 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013317 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013318 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013319 isAllExplicitSpecializations = false;
13320 break;
13321 }
13322 }
13323
13324 // FIXME: don't ignore attributes.
13325
13326 // If it's explicit specializations all the way down, just forget
13327 // about the template header and build an appropriate non-templated
13328 // friend. TODO: for source fidelity, remember the headers.
13329 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013330 if (SS.isEmpty()) {
13331 bool Owned = false;
13332 bool IsDependent = false;
13333 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013334 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013335 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013336 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013337 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013338 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013339 /*UnderlyingType=*/TypeResult(),
13340 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013341 }
Richard Smith649c7b062014-01-08 00:56:48 +000013342
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013343 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013344 ElaboratedTypeKeyword Keyword
13345 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013346 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013347 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013348 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013349 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013350
13351 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13352 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013353 DependentNameTypeLoc TL =
13354 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013355 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013356 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013357 TL.setNameLoc(NameLoc);
13358 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013359 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013360 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013361 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013362 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013363 }
13364
13365 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013366 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013367 Friend->setAccess(AS_public);
13368 CurContext->addDecl(Friend);
13369 return Friend;
13370 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013371
13372 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13373
13374
John McCallace48cd2010-10-19 01:40:49 +000013375
13376 // Handle the case of a templated-scope friend class. e.g.
13377 // template <class T> class A<T>::B;
13378 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013379 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13380 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013381 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13382 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13383 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013384 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013385 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013386 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013387 TL.setNameLoc(NameLoc);
13388
13389 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013390 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013391 Friend->setAccess(AS_public);
13392 Friend->setUnsupportedFriend(true);
13393 CurContext->addDecl(Friend);
13394 return Friend;
13395}
13396
13397
John McCall11083da2009-09-16 22:47:08 +000013398/// Handle a friend type declaration. This works in tandem with
13399/// ActOnTag.
13400///
13401/// Notes on friend class templates:
13402///
13403/// We generally treat friend class declarations as if they were
13404/// declaring a class. So, for example, the elaborated type specifier
13405/// in a friend declaration is required to obey the restrictions of a
13406/// class-head (i.e. no typedefs in the scope chain), template
13407/// parameters are required to match up with simple template-ids, &c.
13408/// However, unlike when declaring a template specialization, it's
13409/// okay to refer to a template specialization without an empty
13410/// template parameter declaration, e.g.
13411/// friend class A<T>::B<unsigned>;
13412/// We permit this as a special case; if there are any template
13413/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013414/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013415Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013416 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013417 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013418
13419 assert(DS.isFriendSpecified());
13420 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13421
John McCall11083da2009-09-16 22:47:08 +000013422 // Try to convert the decl specifier to a type. This works for
13423 // friend templates because ActOnTag never produces a ClassTemplateDecl
13424 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013425 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013426 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13427 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013428 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013429 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013430
Douglas Gregor6c110f32010-12-16 01:14:37 +000013431 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013432 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013433
John McCall11083da2009-09-16 22:47:08 +000013434 // This is definitely an error in C++98. It's probably meant to
13435 // be forbidden in C++0x, too, but the specification is just
13436 // poorly written.
13437 //
13438 // The problem is with declarations like the following:
13439 // template <T> friend A<T>::foo;
13440 // where deciding whether a class C is a friend or not now hinges
13441 // on whether there exists an instantiation of A that causes
13442 // 'foo' to equal C. There are restrictions on class-heads
13443 // (which we declare (by fiat) elaborated friend declarations to
13444 // be) that makes this tractable.
13445 //
13446 // FIXME: handle "template <> friend class A<T>;", which
13447 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013448 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013449 Diag(Loc, diag::err_tagless_friend_type_template)
13450 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013451 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013452 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013453
John McCallaa74a0c2009-08-28 07:59:38 +000013454 // C++98 [class.friend]p1: A friend of a class is a function
13455 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013456 // This is fixed in DR77, which just barely didn't make the C++03
13457 // deadline. It's also a very silly restriction that seriously
13458 // affects inner classes and which nobody else seems to implement;
13459 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013460 //
13461 // But note that we could warn about it: it's always useless to
13462 // friend one of your own members (it's not, however, worthless to
13463 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013464
John McCall11083da2009-09-16 22:47:08 +000013465 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013466 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013467 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013468 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013469 TSI,
John McCall11083da2009-09-16 22:47:08 +000013470 DS.getFriendSpecLoc());
13471 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013472 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013473
13474 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013475 return nullptr;
13476
John McCall11083da2009-09-16 22:47:08 +000013477 D->setAccess(AS_public);
13478 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013479
John McCall48871652010-08-21 09:40:31 +000013480 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013481}
13482
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013483NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13484 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013485 const DeclSpec &DS = D.getDeclSpec();
13486
13487 assert(DS.isFriendSpecified());
13488 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13489
13490 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013491 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013492
13493 // C++ [class.friend]p1
13494 // A friend of a class is a function or class....
13495 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013496 // It *doesn't* see through dependent types, which is correct
13497 // according to [temp.arg.type]p3:
13498 // If a declaration acquires a function type through a
13499 // type dependent on a template-parameter and this causes
13500 // a declaration that does not use the syntactic form of a
13501 // function declarator to have a function type, the program
13502 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013503 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013504 Diag(Loc, diag::err_unexpected_friend);
13505
13506 // It might be worthwhile to try to recover by creating an
13507 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013508 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013509 }
13510
13511 // C++ [namespace.memdef]p3
13512 // - If a friend declaration in a non-local class first declares a
13513 // class or function, the friend class or function is a member
13514 // of the innermost enclosing namespace.
13515 // - The name of the friend is not found by simple name lookup
13516 // until a matching declaration is provided in that namespace
13517 // scope (either before or after the class declaration granting
13518 // friendship).
13519 // - If a friend function is called, its name may be found by the
13520 // name lookup that considers functions from namespaces and
13521 // classes associated with the types of the function arguments.
13522 // - When looking for a prior declaration of a class or a function
13523 // declared as a friend, scopes outside the innermost enclosing
13524 // namespace scope are not considered.
13525
John McCallde3fd222010-10-12 23:13:28 +000013526 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013527 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13528 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013529 assert(Name);
13530
Douglas Gregor6c110f32010-12-16 01:14:37 +000013531 // Check for unexpanded parameter packs.
13532 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13533 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13534 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013535 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013536
John McCall07e91c02009-08-06 02:15:43 +000013537 // The context we found the declaration in, or in which we should
13538 // create the declaration.
13539 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013540 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013541 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013542 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013543
Richard Smith114394f2013-08-09 04:35:01 +000013544 // There are five cases here.
13545 // - There's no scope specifier and we're in a local class. Only look
13546 // for functions declared in the immediately-enclosing block scope.
13547 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013548 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013549 if ((SS.isInvalid() || !SS.isSet()) &&
13550 (FunctionContainingLocalClass =
13551 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13552 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013553 // If a friend declaration appears in a local class and the name
13554 // specified is an unqualified name, a prior declaration is
13555 // looked up without considering scopes that are outside the
13556 // innermost enclosing non-class scope. For a friend function
13557 // declaration, if there is no prior declaration, the program is
13558 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013559
13560 // Find the innermost enclosing non-class scope. This is the block
13561 // scope containing the local class definition (or for a nested class,
13562 // the outer local class).
13563 DCScope = S->getFnParent();
13564
13565 // Look up the function name in the scope.
13566 Previous.clear(LookupLocalFriendName);
13567 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13568
13569 if (!Previous.empty()) {
13570 // All possible previous declarations must have the same context:
13571 // either they were declared at block scope or they are members of
13572 // one of the enclosing local classes.
13573 DC = Previous.getRepresentativeDecl()->getDeclContext();
13574 } else {
13575 // This is ill-formed, but provide the context that we would have
13576 // declared the function in, if we were permitted to, for error recovery.
13577 DC = FunctionContainingLocalClass;
13578 }
Richard Smith541b38b2013-09-20 01:15:31 +000013579 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013580
13581 // C++ [class.friend]p6:
13582 // A function can be defined in a friend declaration of a class if and
13583 // only if the class is a non-local class (9.8), the function name is
13584 // unqualified, and the function has namespace scope.
13585 if (D.isFunctionDefinition()) {
13586 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13587 }
13588
13589 // - There's no scope specifier, in which case we just go to the
13590 // appropriate scope and look for a function or function template
13591 // there as appropriate.
13592 } else if (SS.isInvalid() || !SS.isSet()) {
13593 // C++11 [namespace.memdef]p3:
13594 // If the name in a friend declaration is neither qualified nor
13595 // a template-id and the declaration is a function or an
13596 // elaborated-type-specifier, the lookup to determine whether
13597 // the entity has been previously declared shall not consider
13598 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013599 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013600
John McCallf7cfb222010-10-13 05:45:15 +000013601 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013602 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013603
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013604 // Skip class contexts. If someone can cite chapter and verse
13605 // for this behavior, that would be nice --- it's what GCC and
13606 // EDG do, and it seems like a reasonable intent, but the spec
13607 // really only says that checks for unqualified existing
13608 // declarations should stop at the nearest enclosing namespace,
13609 // not that they should only consider the nearest enclosing
13610 // namespace.
13611 while (DC->isRecord())
13612 DC = DC->getParent();
13613
13614 DeclContext *LookupDC = DC;
13615 while (LookupDC->isTransparentContext())
13616 LookupDC = LookupDC->getParent();
13617
13618 while (true) {
13619 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013620
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013621 if (!Previous.empty()) {
13622 DC = LookupDC;
13623 break;
John McCallf4776592010-10-14 22:22:28 +000013624 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013625
13626 if (isTemplateId) {
13627 if (isa<TranslationUnitDecl>(LookupDC)) break;
13628 } else {
13629 if (LookupDC->isFileContext()) break;
13630 }
13631 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013632 }
13633
John McCallccbc0322010-10-13 06:22:15 +000013634 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013635
John McCallde3fd222010-10-12 23:13:28 +000013636 // - There's a non-dependent scope specifier, in which case we
13637 // compute it and do a previous lookup there for a function
13638 // or function template.
13639 } else if (!SS.getScopeRep()->isDependent()) {
13640 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013641 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013642
Craig Topperc3ec1492014-05-26 06:22:03 +000013643 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013644
13645 LookupQualifiedName(Previous, DC);
13646
13647 // Ignore things found implicitly in the wrong scope.
13648 // TODO: better diagnostics for this case. Suggesting the right
13649 // qualified scope would be nice...
13650 LookupResult::Filter F = Previous.makeFilter();
13651 while (F.hasNext()) {
13652 NamedDecl *D = F.next();
13653 if (!DC->InEnclosingNamespaceSetOf(
13654 D->getDeclContext()->getRedeclContext()))
13655 F.erase();
13656 }
13657 F.done();
13658
13659 if (Previous.empty()) {
13660 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013661 Diag(Loc, diag::err_qualified_friend_not_found)
13662 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013663 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013664 }
13665
13666 // C++ [class.friend]p1: A friend of a class is a function or
13667 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013668 if (DC->Equals(CurContext))
13669 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013670 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013671 diag::warn_cxx98_compat_friend_is_member :
13672 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013673
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013674 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013675 // C++ [class.friend]p6:
13676 // A function can be defined in a friend declaration of a class if and
13677 // only if the class is a non-local class (9.8), the function name is
13678 // unqualified, and the function has namespace scope.
13679 SemaDiagnosticBuilder DB
13680 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13681
13682 DB << SS.getScopeRep();
13683 if (DC->isFileContext())
13684 DB << FixItHint::CreateRemoval(SS.getRange());
13685 SS.clear();
13686 }
John McCallde3fd222010-10-12 23:13:28 +000013687
13688 // - There's a scope specifier that does not match any template
13689 // parameter lists, in which case we use some arbitrary context,
13690 // create a method or method template, and wait for instantiation.
13691 // - There's a scope specifier that does match some template
13692 // parameter lists, which we don't handle right now.
13693 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013694 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013695 // C++ [class.friend]p6:
13696 // A function can be defined in a friend declaration of a class if and
13697 // only if the class is a non-local class (9.8), the function name is
13698 // unqualified, and the function has namespace scope.
13699 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13700 << SS.getScopeRep();
13701 }
13702
John McCallde3fd222010-10-12 23:13:28 +000013703 DC = CurContext;
13704 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013705 }
David Majnemere14d5302015-09-30 22:07:43 +000013706
John McCallf7cfb222010-10-13 05:45:15 +000013707 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013708 int DiagArg = -1;
13709 switch (D.getName().getKind()) {
13710 case UnqualifiedId::IK_ConstructorTemplateId:
13711 case UnqualifiedId::IK_ConstructorName:
13712 DiagArg = 0;
13713 break;
13714 case UnqualifiedId::IK_DestructorName:
13715 DiagArg = 1;
13716 break;
13717 case UnqualifiedId::IK_ConversionFunctionId:
13718 DiagArg = 2;
13719 break;
13720 case UnqualifiedId::IK_Identifier:
13721 case UnqualifiedId::IK_ImplicitSelfParam:
13722 case UnqualifiedId::IK_LiteralOperatorId:
13723 case UnqualifiedId::IK_OperatorFunctionId:
13724 case UnqualifiedId::IK_TemplateId:
13725 break;
David Majnemere14d5302015-09-30 22:07:43 +000013726 }
John McCall07e91c02009-08-06 02:15:43 +000013727 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013728 if (DiagArg >= 0) {
13729 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013730 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013731 }
John McCall07e91c02009-08-06 02:15:43 +000013732 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013733
Douglas Gregordd847ba2011-11-03 16:37:14 +000013734 // FIXME: This is an egregious hack to cope with cases where the scope stack
13735 // does not contain the declaration context, i.e., in an out-of-line
13736 // definition of a class.
13737 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13738 if (!DCScope) {
13739 FakeDCScope.setEntity(DC);
13740 DCScope = &FakeDCScope;
13741 }
Richard Smith114394f2013-08-09 04:35:01 +000013742
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013743 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013744 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013745 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013746 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013747
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013748 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013749
Richard Smith114394f2013-08-09 04:35:01 +000013750 // If we performed typo correction, we might have added a scope specifier
13751 // and changed the decl context.
13752 DC = ND->getDeclContext();
13753
John McCall759e32b2009-08-31 22:39:49 +000013754 // Add the function declaration to the appropriate lookup tables,
13755 // adjusting the redeclarations list as necessary. We don't
13756 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013757 //
John McCall759e32b2009-08-31 22:39:49 +000013758 // Also update the scope-based lookup if the target context's
13759 // lookup context is in lexical scope.
13760 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013761 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013762 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013763 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013764 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013765 }
John McCallaa74a0c2009-08-28 07:59:38 +000013766
13767 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013768 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013769 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013770 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013771 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013772
John McCalla0a96892012-08-10 03:15:35 +000013773 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013774 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013775 } else {
13776 if (DC->isRecord()) CheckFriendAccess(ND);
13777
John McCall2c2eb122010-10-16 06:59:13 +000013778 FunctionDecl *FD;
13779 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13780 FD = FTD->getTemplatedDecl();
13781 else
13782 FD = cast<FunctionDecl>(ND);
13783
David Majnemer502b0ed2013-06-25 23:09:30 +000013784 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13785 // default argument expression, that declaration shall be a definition
13786 // and shall be the only declaration of the function or function
13787 // template in the translation unit.
13788 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013789 // We can't look at FD->getPreviousDecl() because it may not have been set
13790 // if we're in a dependent context. If we get this far with a non-empty
13791 // Previous set, we must have a valid previous declaration of this
13792 // function.
13793 if (!Previous.empty()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013794 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013795 Diag(Previous.getRepresentativeDecl()->getLocation(),
13796 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013797 } else if (!D.isFunctionDefinition())
13798 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13799 }
13800
John McCall2c2eb122010-10-16 06:59:13 +000013801 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013802 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13803 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13804 << SS.getScopeRep() << SS.getRange()
13805 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013806 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013807 }
John McCall2c2eb122010-10-16 06:59:13 +000013808 }
John McCallde3fd222010-10-12 23:13:28 +000013809
John McCall48871652010-08-21 09:40:31 +000013810 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013811}
13812
John McCall48871652010-08-21 09:40:31 +000013813void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13814 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013815
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013816 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013817 if (!Fn) {
13818 Diag(DelLoc, diag::err_deleted_non_function);
13819 return;
13820 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013821
Douglas Gregorec9fd132012-01-14 16:38:05 +000013822 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013823 // Don't consider the implicit declaration we generate for explicit
13824 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013825 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13826 Prev->getPreviousDecl()) &&
13827 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013828 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013829 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13830 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13831 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013832 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013833 // If the declaration wasn't the first, we delete the function anyway for
13834 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013835 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013836 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013837
Nico Rieck9de0a572014-05-29 16:51:19 +000013838 // dllimport/dllexport cannot be deleted.
13839 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13840 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13841 Fn->setInvalidDecl();
13842 }
13843
Richard Smithb4d2a152013-04-02 19:38:47 +000013844 if (Fn->isDeleted())
13845 return;
13846
13847 // See if we're deleting a function which is already known to override a
13848 // non-deleted virtual function.
13849 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13850 bool IssuedDiagnostic = false;
13851 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13852 E = MD->end_overridden_methods();
13853 I != E; ++I) {
13854 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13855 if (!IssuedDiagnostic) {
13856 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13857 IssuedDiagnostic = true;
13858 }
13859 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13860 }
13861 }
13862 }
13863
Richard Smithb63b6ee2014-01-22 01:43:19 +000013864 // C++11 [basic.start.main]p3:
13865 // A program that defines main as deleted [...] is ill-formed.
13866 if (Fn->isMain())
13867 Diag(DelLoc, diag::err_deleted_main);
13868
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013869 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013870}
Sebastian Redl4c018662009-04-27 21:33:24 +000013871
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013872void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013873 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013874
13875 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013876 if (MD->getParent()->isDependentType()) {
13877 MD->setDefaulted();
13878 MD->setExplicitlyDefaulted();
13879 return;
13880 }
13881
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013882 CXXSpecialMember Member = getSpecialMember(MD);
13883 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013884 if (!MD->isInvalidDecl())
13885 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013886 return;
13887 }
13888
13889 MD->setDefaulted();
13890 MD->setExplicitlyDefaulted();
13891
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013892 // If this definition appears within the record, do the checking when
13893 // the record is complete.
13894 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013895 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013896 // Ask the template instantiation pattern that actually had the
13897 // '= default' on it.
13898 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013899
Richard Smith3901dfe2013-03-27 00:22:47 +000013900 // If the method was defaulted on its first declaration, we will have
13901 // already performed the checking in CheckCompletedCXXClass. Such a
13902 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013903 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013904 return;
13905
Richard Smithd3b5c9082012-07-27 04:22:15 +000013906 CheckExplicitlyDefaultedSpecialMember(MD);
13907
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013908 if (!MD->isInvalidDecl())
13909 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013910 } else {
13911 Diag(DefaultLoc, diag::err_default_special_members);
13912 }
13913}
13914
Sebastian Redl4c018662009-04-27 21:33:24 +000013915static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013916 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013917 if (!SubStmt)
13918 continue;
13919 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013920 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000013921 diag::err_return_in_constructor_handler);
13922 if (!isa<Expr>(SubStmt))
13923 SearchForReturnInStmt(Self, SubStmt);
13924 }
13925}
13926
13927void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13928 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13929 CXXCatchStmt *Handler = TryBlock->getHandler(I);
13930 SearchForReturnInStmt(*this, Handler);
13931 }
13932}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013933
David Blaikie68f71a32013-01-18 23:03:15 +000013934bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000013935 const CXXMethodDecl *Old) {
13936 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13937 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13938
13939 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13940
13941 // If the calling conventions match, everything is fine
13942 if (NewCC == OldCC)
13943 return false;
13944
Hans Wennborg2545efe2013-12-11 17:42:11 +000013945 // If the calling conventions mismatch because the new function is static,
13946 // suppress the calling convention mismatch error; the error about static
13947 // function override (err_static_overrides_virtual from
13948 // Sema::CheckFunctionDeclaration) is more clear.
13949 if (New->getStorageClass() == SC_Static)
13950 return false;
13951
Reid Kleckner78af0702013-08-27 23:08:25 +000013952 Diag(New->getLocation(),
13953 diag::err_conflicting_overriding_cc_attributes)
13954 << New->getDeclName() << New->getType() << Old->getType();
13955 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13956 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000013957}
13958
Mike Stump11289f42009-09-09 15:08:12 +000013959bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013960 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000013961 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13962 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013963
Chandler Carruth284bb2e2010-02-15 11:53:20 +000013964 if (Context.hasSameType(NewTy, OldTy) ||
13965 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013966 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013967
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013968 // Check if the return types are covariant
13969 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000013970
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013971 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013972 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13973 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013974 NewClassTy = NewPT->getPointeeType();
13975 OldClassTy = OldPT->getPointeeType();
13976 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013977 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13978 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13979 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13980 NewClassTy = NewRT->getPointeeType();
13981 OldClassTy = OldRT->getPointeeType();
13982 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013983 }
13984 }
Mike Stump11289f42009-09-09 15:08:12 +000013985
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013986 // The return types aren't either both pointers or references to a class type.
13987 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000013988 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013989 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013990 << New->getDeclName() << NewTy << OldTy
13991 << New->getReturnTypeSourceRange();
13992 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13993 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000013994
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013995 return true;
13996 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013997
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000013998 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000013999 // C++14 [class.virtual]p8:
14000 // If the class type in the covariant return type of D::f differs from
14001 // that of B::f, the class type in the return type of D::f shall be
14002 // complete at the point of declaration of D::f or shall be the class
14003 // type D.
14004 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14005 if (!RT->isBeingDefined() &&
14006 RequireCompleteType(New->getLocation(), NewClassTy,
14007 diag::err_covariant_return_incomplete,
14008 New->getDeclName()))
14009 return true;
14010 }
14011
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014012 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014013 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014014 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14015 << New->getDeclName() << NewTy << OldTy
14016 << New->getReturnTypeSourceRange();
14017 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14018 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014019 return true;
14020 }
Mike Stump11289f42009-09-09 15:08:12 +000014021
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014022 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014023 if (CheckDerivedToBaseConversion(
14024 NewClassTy, OldClassTy,
14025 diag::err_covariant_return_inaccessible_base,
14026 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14027 New->getLocation(), New->getReturnTypeSourceRange(),
14028 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014029 // FIXME: this note won't trigger for delayed access control
14030 // diagnostics, and it's impossible to get an undelayed error
14031 // here from access control during the original parse because
14032 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014033 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14034 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014035 return true;
14036 }
14037 }
Mike Stump11289f42009-09-09 15:08:12 +000014038
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014039 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014040 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014041 Diag(New->getLocation(),
14042 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014043 << New->getDeclName() << NewTy << OldTy
14044 << New->getReturnTypeSourceRange();
14045 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14046 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014047 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014048 }
Mike Stump11289f42009-09-09 15:08:12 +000014049
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014050
14051 // The new class type must have the same or less qualifiers as the old type.
14052 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14053 Diag(New->getLocation(),
14054 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014055 << New->getDeclName() << NewTy << OldTy
14056 << New->getReturnTypeSourceRange();
14057 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14058 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014059 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014060 }
Mike Stump11289f42009-09-09 15:08:12 +000014061
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014062 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014063}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014064
Douglas Gregor21920e372009-12-01 17:24:26 +000014065/// \brief Mark the given method pure.
14066///
14067/// \param Method the method to be marked pure.
14068///
14069/// \param InitRange the source range that covers the "0" initializer.
14070bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014071 SourceLocation EndLoc = InitRange.getEnd();
14072 if (EndLoc.isValid())
14073 Method->setRangeEnd(EndLoc);
14074
Douglas Gregor21920e372009-12-01 17:24:26 +000014075 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14076 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014077 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014078 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014079
14080 if (!Method->isInvalidDecl())
14081 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14082 << Method->getDeclName() << InitRange;
14083 return true;
14084}
14085
Richard Smith9ba0fec2015-06-30 01:28:56 +000014086void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14087 if (D->getFriendObjectKind())
14088 Diag(D->getLocation(), diag::err_pure_friend);
14089 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14090 CheckPureMethod(M, ZeroLoc);
14091 else
14092 Diag(D->getLocation(), diag::err_illegal_initializer);
14093}
14094
Douglas Gregor926410d2012-02-21 02:22:07 +000014095/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014096static bool isStaticDataMember(const Decl *D) {
14097 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14098 return Var->isStaticDataMember();
14099
14100 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014101}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014102
John McCall1f4ee7b2009-12-19 09:28:58 +000014103/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14104/// an initializer for the out-of-line declaration 'Dcl'. The scope
14105/// is a fresh scope pushed for just this purpose.
14106///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014107/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14108/// static data member of class X, names should be looked up in the scope of
14109/// class X.
John McCall48871652010-08-21 09:40:31 +000014110void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014111 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014112 if (!D || D->isInvalidDecl())
14113 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014114
Richard Smitha2302242013-12-05 07:51:02 +000014115 // We will always have a nested name specifier here, but this declaration
14116 // might not be out of line if the specifier names the current namespace:
14117 // extern int n;
14118 // int ::n = 0;
14119 if (D->isOutOfLine())
14120 EnterDeclaratorContext(S, D->getDeclContext());
14121
Douglas Gregor926410d2012-02-21 02:22:07 +000014122 // If we are parsing the initializer for a static data member, push a
14123 // new expression evaluation context that is associated with this static
14124 // data member.
14125 if (isStaticDataMember(D))
14126 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014127}
14128
14129/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014130/// initializer for the out-of-line declaration 'D'.
14131void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014132 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014133 if (!D || D->isInvalidDecl())
14134 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014135
Douglas Gregor926410d2012-02-21 02:22:07 +000014136 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014137 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014138
Richard Smitha2302242013-12-05 07:51:02 +000014139 if (D->isOutOfLine())
14140 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014141}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014142
14143/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14144/// C++ if/switch/while/for statement.
14145/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014146DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014147 // C++ 6.4p2:
14148 // The declarator shall not specify a function or an array.
14149 // The type-specifier-seq shall not contain typedef and shall not declare a
14150 // new class or enumeration.
14151 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14152 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014153
14154 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014155 if (!Dcl)
14156 return true;
14157
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014158 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14159 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014160 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014161 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014162 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014163
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014164 return Dcl;
14165}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014166
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014167void Sema::LoadExternalVTableUses() {
14168 if (!ExternalSource)
14169 return;
14170
14171 SmallVector<ExternalVTableUse, 4> VTables;
14172 ExternalSource->ReadUsedVTables(VTables);
14173 SmallVector<VTableUse, 4> NewUses;
14174 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14175 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14176 = VTablesUsed.find(VTables[I].Record);
14177 // Even if a definition wasn't required before, it may be required now.
14178 if (Pos != VTablesUsed.end()) {
14179 if (!Pos->second && VTables[I].DefinitionRequired)
14180 Pos->second = true;
14181 continue;
14182 }
14183
14184 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14185 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14186 }
14187
14188 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14189}
14190
Douglas Gregor88d292c2010-05-13 16:44:06 +000014191void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14192 bool DefinitionRequired) {
14193 // Ignore any vtable uses in unevaluated operands or for classes that do
14194 // not have a vtable.
14195 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014196 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014197 return;
14198
Douglas Gregor88d292c2010-05-13 16:44:06 +000014199 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014200 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014201 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14202 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14203 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14204 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014205 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014206 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014207 // list, since we may have already processed the first entry.
14208 if (DefinitionRequired && !Pos.first->second) {
14209 Pos.first->second = true;
14210 } else {
14211 // Otherwise, we can early exit.
14212 return;
14213 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014214 } else {
14215 // The Microsoft ABI requires that we perform the destructor body
14216 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14217 // the deleting destructor is emitted with the vtable, not with the
14218 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014219 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014220 CXXDestructorDecl *DD = Class->getDestructor();
14221 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14222 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14223 // If this is an out-of-line declaration, marking it referenced will
14224 // not do anything. Manually call CheckDestructor to look up operator
14225 // delete().
14226 ContextRAII SavedContext(*this, DD);
14227 CheckDestructor(DD);
14228 } else {
14229 MarkFunctionReferenced(Loc, Class->getDestructor());
14230 }
Hans Wennborg34804352016-04-13 20:21:15 +000014231 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014232 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014233 }
14234
14235 // Local classes need to have their virtual members marked
14236 // immediately. For all other classes, we mark their virtual members
14237 // at the end of the translation unit.
14238 if (Class->isLocalClass())
14239 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014240 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014241 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014242}
14243
Douglas Gregor88d292c2010-05-13 16:44:06 +000014244bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014245 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014246 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014247 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014248
Douglas Gregor88d292c2010-05-13 16:44:06 +000014249 // Note: The VTableUses vector could grow as a result of marking
14250 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014251 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014252 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014253 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014254 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014255 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014256 if (!Class)
14257 continue;
14258
14259 SourceLocation Loc = VTableUses[I].second;
14260
Richard Smithd3b5c9082012-07-27 04:22:15 +000014261 bool DefineVTable = true;
14262
Douglas Gregor88d292c2010-05-13 16:44:06 +000014263 // If this class has a key function, but that key function is
14264 // defined in another translation unit, we don't need to emit the
14265 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014266 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014267 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014268 // The key function is in another translation unit.
14269 DefineVTable = false;
14270 TemplateSpecializationKind TSK =
14271 KeyFunction->getTemplateSpecializationKind();
14272 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14273 TSK != TSK_ImplicitInstantiation &&
14274 "Instantiations don't have key functions");
14275 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014276 } else if (!KeyFunction) {
14277 // If we have a class with no key function that is the subject
14278 // of an explicit instantiation declaration, suppress the
14279 // vtable; it will live with the explicit instantiation
14280 // definition.
14281 bool IsExplicitInstantiationDeclaration
14282 = Class->getTemplateSpecializationKind()
14283 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014284 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014285 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014286 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014287 if (TSK == TSK_ExplicitInstantiationDeclaration)
14288 IsExplicitInstantiationDeclaration = true;
14289 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14290 IsExplicitInstantiationDeclaration = false;
14291 break;
14292 }
14293 }
14294
14295 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014296 DefineVTable = false;
14297 }
14298
14299 // The exception specifications for all virtual members may be needed even
14300 // if we are not providing an authoritative form of the vtable in this TU.
14301 // We may choose to emit it available_externally anyway.
14302 if (!DefineVTable) {
14303 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14304 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014305 }
14306
14307 // Mark all of the virtual members of this class as referenced, so
14308 // that we can build a vtable. Then, tell the AST consumer that a
14309 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014310 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014311 MarkVirtualMembersReferenced(Loc, Class);
14312 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014313 if (VTablesUsed[Canonical])
14314 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014315
14316 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000014317 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000014318 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014319 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000014320 if (!KeyFunction ||
14321 (KeyFunction->hasBody(KeyFunctionDef) &&
14322 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000014323 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14324 TSK_ExplicitInstantiationDefinition
14325 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14326 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014327 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014328 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014329 VTableUses.clear();
14330
Douglas Gregor97509692011-04-22 22:25:37 +000014331 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014332}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014333
Richard Smithd3b5c9082012-07-27 04:22:15 +000014334void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14335 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014336 for (const auto *I : RD->methods())
14337 if (I->isVirtual() && !I->isPure())
14338 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014339}
14340
Rafael Espindola5b334082010-03-26 00:36:59 +000014341void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14342 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014343 // Mark all functions which will appear in RD's vtable as used.
14344 CXXFinalOverriderMap FinalOverriders;
14345 RD->getFinalOverriders(FinalOverriders);
14346 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14347 E = FinalOverriders.end();
14348 I != E; ++I) {
14349 for (OverridingMethods::const_iterator OI = I->second.begin(),
14350 OE = I->second.end();
14351 OI != OE; ++OI) {
14352 assert(OI->second.size() > 0 && "no final overrider");
14353 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014354
Richard Smith4ff9ff92012-07-07 06:59:51 +000014355 // C++ [basic.def.odr]p2:
14356 // [...] A virtual member function is used if it is not pure. [...]
14357 if (!Overrider->isPure())
14358 MarkFunctionReferenced(Loc, Overrider);
14359 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014360 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014361
14362 // Only classes that have virtual bases need a VTT.
14363 if (RD->getNumVBases() == 0)
14364 return;
14365
Aaron Ballman574705e2014-03-13 15:41:46 +000014366 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014367 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014368 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014369 if (Base->getNumVBases() == 0)
14370 continue;
14371 MarkVirtualMembersReferenced(Loc, Base);
14372 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014373}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014374
14375/// SetIvarInitializers - This routine builds initialization ASTs for the
14376/// Objective-C implementation whose ivars need be initialized.
14377void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014378 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014379 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014380 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014381 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014382 CollectIvarsToConstructOrDestruct(OID, ivars);
14383 if (ivars.empty())
14384 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014385 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014386 for (unsigned i = 0; i < ivars.size(); i++) {
14387 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014388 if (Field->isInvalidDecl())
14389 continue;
14390
Alexis Hunt1d792652011-01-08 20:30:50 +000014391 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014392 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14393 InitializationKind InitKind =
14394 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014395
14396 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14397 ExprResult MemberInit =
14398 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014399 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014400 // Note, MemberInit could actually come back empty if no initialization
14401 // is required (e.g., because it would call a trivial default constructor)
14402 if (!MemberInit.get() || MemberInit.isInvalid())
14403 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014404
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014405 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014406 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14407 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014408 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014409 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014410 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014411
14412 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014413 if (const RecordType *RecordTy =
14414 Context.getBaseElementType(Field->getType())
14415 ->getAs<RecordType>()) {
14416 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014417 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014418 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014419 CheckDestructorAccess(Field->getLocation(), Destructor,
14420 PDiag(diag::err_access_dtor_ivar)
14421 << Context.getBaseElementType(Field->getType()));
14422 }
14423 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014424 }
14425 ObjCImplementation->setIvarInitializers(Context,
14426 AllToInit.data(), AllToInit.size());
14427 }
14428}
Alexis Hunt6118d662011-05-04 05:57:24 +000014429
Alexis Hunt27a761d2011-05-04 23:29:54 +000014430static
14431void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14432 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14433 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14434 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14435 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014436 if (Ctor->isInvalidDecl())
14437 return;
14438
Richard Smith802c4b72012-08-23 06:16:52 +000014439 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14440
14441 // Target may not be determinable yet, for instance if this is a dependent
14442 // call in an uninstantiated template.
14443 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014444 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014445 (void)Target->hasBody(FNTarget);
14446 Target = const_cast<CXXConstructorDecl*>(
14447 cast_or_null<CXXConstructorDecl>(FNTarget));
14448 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014449
14450 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14451 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014452 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014453
David Blaikie82e95a32014-11-19 07:49:47 +000014454 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014455 return;
14456
14457 // We know that beyond here, we aren't chaining into a cycle.
14458 if (!Target || !Target->isDelegatingConstructor() ||
14459 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014460 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014461 Current.clear();
14462 // We've hit a cycle.
14463 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14464 Current.count(TCanonical)) {
14465 // If we haven't diagnosed this cycle yet, do so now.
14466 if (!Invalid.count(TCanonical)) {
14467 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014468 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014469 << Ctor;
14470
Richard Smith802c4b72012-08-23 06:16:52 +000014471 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014472 if (TCanonical != Canonical)
14473 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14474
14475 CXXConstructorDecl *C = Target;
14476 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014477 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014478 (void)C->getTargetConstructor()->hasBody(FNTarget);
14479 assert(FNTarget && "Ctor cycle through bodiless function");
14480
Richard Smith802c4b72012-08-23 06:16:52 +000014481 C = const_cast<CXXConstructorDecl*>(
14482 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014483 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14484 }
14485 }
14486
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014487 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014488 Current.clear();
14489 } else {
14490 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14491 }
14492}
14493
14494
Alexis Hunt6118d662011-05-04 05:57:24 +000014495void Sema::CheckDelegatingCtorCycles() {
14496 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14497
Douglas Gregorbae31202011-07-27 21:57:17 +000014498 for (DelegatingCtorDeclsType::iterator
14499 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014500 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014501 I != E; ++I)
14502 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014503
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014504 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14505 CE = Invalid.end();
14506 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014507 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014508}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014509
Douglas Gregor3024f072012-04-16 07:05:22 +000014510namespace {
14511 /// \brief AST visitor that finds references to the 'this' expression.
14512 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14513 Sema &S;
14514
14515 public:
14516 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14517
14518 bool VisitCXXThisExpr(CXXThisExpr *E) {
14519 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14520 << E->isImplicit();
14521 return false;
14522 }
14523 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014524}
Douglas Gregor3024f072012-04-16 07:05:22 +000014525
14526bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14527 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14528 if (!TSInfo)
14529 return false;
14530
14531 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014532 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014533 if (!ProtoTL)
14534 return false;
14535
14536 // C++11 [expr.prim.general]p3:
14537 // [The expression this] shall not appear before the optional
14538 // cv-qualifier-seq and it shall not appear within the declaration of a
14539 // static member function (although its type and value category are defined
14540 // within a static member function as they are within a non-static member
14541 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014542 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014543 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014544 FindCXXThisExpr Finder(*this);
14545
14546 // If the return type came after the cv-qualifier-seq, check it now.
14547 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014548 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014549 return true;
14550
14551 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014552 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14553 return true;
14554
14555 return checkThisInStaticMemberFunctionAttributes(Method);
14556}
14557
14558bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14559 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14560 if (!TSInfo)
14561 return false;
14562
14563 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014564 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014565 if (!ProtoTL)
14566 return false;
14567
David Blaikie6adc78e2013-02-18 22:06:02 +000014568 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014569 FindCXXThisExpr Finder(*this);
14570
Douglas Gregor3024f072012-04-16 07:05:22 +000014571 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014572 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014573 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014574 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014575 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014576 case EST_DynamicNone:
14577 case EST_MSAny:
14578 case EST_None:
14579 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014580
Douglas Gregor3024f072012-04-16 07:05:22 +000014581 case EST_ComputedNoexcept:
14582 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14583 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014584
Douglas Gregor3024f072012-04-16 07:05:22 +000014585 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014586 for (const auto &E : Proto->exceptions()) {
14587 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014588 return true;
14589 }
14590 break;
14591 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014592
14593 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014594}
14595
14596bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14597 FindCXXThisExpr Finder(*this);
14598
14599 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014600 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014601 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014602 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014603 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014604 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014605 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014606 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014607 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014608 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014609 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014610 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014611 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014612 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014613 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014614 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014615 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014616 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014617 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014618 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014619 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014620 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014621 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014622 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014623 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014624 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014625 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014626 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014627 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014628 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014629 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014630
14631 if (Arg && !Finder.TraverseStmt(Arg))
14632 return true;
14633
14634 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14635 if (!Finder.TraverseStmt(Args[I]))
14636 return true;
14637 }
14638 }
14639
14640 return false;
14641}
14642
Richard Smith2e321552014-11-12 02:00:47 +000014643void Sema::checkExceptionSpecification(
14644 bool IsTopLevel, ExceptionSpecificationType EST,
14645 ArrayRef<ParsedType> DynamicExceptions,
14646 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14647 SmallVectorImpl<QualType> &Exceptions,
14648 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014649 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014650 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014651 if (EST == EST_Dynamic) {
14652 Exceptions.reserve(DynamicExceptions.size());
14653 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14654 // FIXME: Preserve type source info.
14655 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14656
Richard Smith2e321552014-11-12 02:00:47 +000014657 if (IsTopLevel) {
14658 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14659 collectUnexpandedParameterPacks(ET, Unexpanded);
14660 if (!Unexpanded.empty()) {
14661 DiagnoseUnexpandedParameterPacks(
14662 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14663 Unexpanded);
14664 continue;
14665 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014666 }
14667
14668 // Check that the type is valid for an exception spec, and
14669 // drop it if not.
14670 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14671 Exceptions.push_back(ET);
14672 }
Richard Smith8acb4282014-07-31 21:57:55 +000014673 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014674 return;
14675 }
Richard Smith8acb4282014-07-31 21:57:55 +000014676
Douglas Gregor433e0532012-04-16 18:27:27 +000014677 if (EST == EST_ComputedNoexcept) {
14678 // If an error occurred, there's no expression here.
14679 if (NoexceptExpr) {
14680 assert((NoexceptExpr->isTypeDependent() ||
14681 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14682 Context.BoolTy) &&
14683 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014684 if (IsTopLevel && NoexceptExpr &&
14685 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014686 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014687 return;
14688 }
Richard Smith8acb4282014-07-31 21:57:55 +000014689
Douglas Gregor433e0532012-04-16 18:27:27 +000014690 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014691 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014692 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014693 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014694 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014695 }
14696 return;
14697 }
14698}
14699
Richard Smith0b3a4622014-11-13 20:01:57 +000014700void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14701 ExceptionSpecificationType EST,
14702 SourceRange SpecificationRange,
14703 ArrayRef<ParsedType> DynamicExceptions,
14704 ArrayRef<SourceRange> DynamicExceptionRanges,
14705 Expr *NoexceptExpr) {
14706 if (!MethodD)
14707 return;
14708
14709 // Dig out the method we're referring to.
14710 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14711 MethodD = FunTmpl->getTemplatedDecl();
14712
14713 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14714 if (!Method)
14715 return;
14716
14717 // Check the exception specification.
14718 llvm::SmallVector<QualType, 4> Exceptions;
14719 FunctionProtoType::ExceptionSpecInfo ESI;
14720 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14721 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14722 ESI);
14723
14724 // Update the exception specification on the function type.
14725 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14726
14727 if (Method->isStatic())
14728 checkThisInStaticMemberFunctionExceptionSpec(Method);
14729
14730 if (Method->isVirtual()) {
14731 // Check overrides, which we previously had to delay.
14732 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14733 OEnd = Method->end_overridden_methods();
14734 O != OEnd; ++O)
14735 CheckOverridingFunctionExceptionSpec(Method, *O);
14736 }
14737}
14738
John McCall5e77d762013-04-16 07:28:30 +000014739/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14740///
14741MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14742 SourceLocation DeclStart,
14743 Declarator &D, Expr *BitWidth,
14744 InClassInitStyle InitStyle,
14745 AccessSpecifier AS,
14746 AttributeList *MSPropertyAttr) {
14747 IdentifierInfo *II = D.getIdentifier();
14748 if (!II) {
14749 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014750 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014751 }
14752 SourceLocation Loc = D.getIdentifierLoc();
14753
14754 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14755 QualType T = TInfo->getType();
14756 if (getLangOpts().CPlusPlus) {
14757 CheckExtraCXXDefaultArguments(D);
14758
14759 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14760 UPPC_DataMemberType)) {
14761 D.setInvalidType();
14762 T = Context.IntTy;
14763 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14764 }
14765 }
14766
14767 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14768
Richard Smith62f19e72016-06-25 00:15:56 +000014769 if (D.getDeclSpec().isInlineSpecified())
14770 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14771 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014772 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14773 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14774 diag::err_invalid_thread)
14775 << DeclSpec::getSpecifierName(TSCS);
14776
14777 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014778 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014779 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14780 LookupName(Previous, S);
14781 switch (Previous.getResultKind()) {
14782 case LookupResult::Found:
14783 case LookupResult::FoundUnresolvedValue:
14784 PrevDecl = Previous.getAsSingle<NamedDecl>();
14785 break;
14786
14787 case LookupResult::FoundOverloaded:
14788 PrevDecl = Previous.getRepresentativeDecl();
14789 break;
14790
14791 case LookupResult::NotFound:
14792 case LookupResult::NotFoundInCurrentInstantiation:
14793 case LookupResult::Ambiguous:
14794 break;
14795 }
14796
14797 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14798 // Maybe we will complain about the shadowed template parameter.
14799 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14800 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014801 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014802 }
14803
14804 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014805 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014806
14807 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014808 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014809 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14810 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014811 ProcessDeclAttributes(TUScope, NewPD, D);
14812 NewPD->setAccess(AS);
14813
14814 if (NewPD->isInvalidDecl())
14815 Record->setInvalidDecl();
14816
14817 if (D.getDeclSpec().isModulePrivateSpecified())
14818 NewPD->setModulePrivate();
14819
14820 if (NewPD->isInvalidDecl() && PrevDecl) {
14821 // Don't introduce NewFD into scope; there's already something
14822 // with the same name in the same scope.
14823 } else if (II) {
14824 PushOnScopeChains(NewPD, S);
14825 } else
14826 Record->addDecl(NewPD);
14827
14828 return NewPD;
14829}