blob: 6ccb3c5216bfee89d1674cd327f37e9fa77326d9 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000015#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000016#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000028#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000029#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000038#include "clang/Sema/SemaInternal.h"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Richard Smith7873de02016-08-11 22:25:46 +000042#include "llvm/ADT/StringExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000043#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000044#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000045
46using namespace clang;
47
Chris Lattner58258242008-04-10 02:22:51 +000048//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
Chris Lattnerb0d38442008-04-12 23:52:44 +000052namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000058 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000059 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 Expr *DefaultArg;
61 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 public:
Mike Stump11289f42009-09-09 15:08:12 +000064 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000066
Chris Lattnerb0d38442008-04-12 23:52:44 +000067 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000069 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000070 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000071 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 };
Chris Lattner58258242008-04-10 02:22:51 +000073
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
Benjamin Kramer642f1732015-07-02 21:03:14 +000077 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000080 }
81
Chris Lattnerb0d38442008-04-12 23:52:44 +000082 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000096 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000098 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000099 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +0000100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000103 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000104 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108
Douglas Gregor8e12c382008-11-04 13:41:56 +0000109 return false;
110 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111
Douglas Gregor97a9c812008-11-04 14:32:21 +0000112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000117 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000120 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000121
John McCall7353c862013-04-09 01:56:28 +0000122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?");
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
Douglas Gregorf0d49512012-02-10 23:30:22 +0000139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getLocStart(),
147 diag::err_lambda_capture_default_arg);
148 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000149}
Chris Lattner58258242008-04-10 02:22:51 +0000150
Richard Smithb7151b92013-04-10 06:11:48 +0000151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
Davide Italiano1a7f6482015-07-16 22:37:54 +0000170 switch(EST) {
171 // If this function can throw any exceptions, make a note of that.
172 case EST_MSAny:
173 case EST_None:
174 ClearExceptions();
175 ComputedEST = EST;
176 return;
177 // FIXME: If the call to this decl is using any of its default arguments, we
178 // need to search them for potentially-throwing calls.
179 // If this function has a basic noexcept, it doesn't affect the outcome.
180 case EST_BasicNoexcept:
181 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000184 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000188 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000189 case EST_ComputedNoexcept:
190 {
Richard Smithf623c962012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000198 // noexcept(false) -> no spec on the new function
199 if (NR == FunctionProtoType::NR_Throw) {
200 ClearExceptions();
201 ComputedEST = EST_None;
202 }
203 // noexcept(true) won't change anything either.
204 return;
205 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000206 default:
207 break;
208 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000318 }
319
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
322 // parameter pack.
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
326 return;
327 }
328
Anders Carlssonf1c26952009-08-25 01:02:06 +0000329 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000332 Param->setInvalidDecl();
333 return;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
John McCallb268a282010-08-23 23:25:46 +0000336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000337}
338
Douglas Gregor58354032008-12-24 00:01:03 +0000339/// ActOnParamUnparsedDefaultArgument - We've seen a default
340/// argument for a function parameter, but we can't parse it yet
341/// because we're inside a class definition. Note that this default
342/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000343void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000346 if (!param)
347 return;
Mike Stump11289f42009-09-09 15:08:12 +0000348
John McCall48871652010-08-21 09:40:31 +0000349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000350 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000351 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000352}
353
Douglas Gregor4d87df52008-12-16 21:30:33 +0000354/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000356void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000358 if (!param)
359 return;
Mike Stump11289f42009-09-09 15:08:12 +0000360
John McCall48871652010-08-21 09:40:31 +0000361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000362 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000363 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000364 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
367 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000368}
369
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000370/// CheckExtraCXXDefaultArguments - Check for any extra default
371/// arguments in the declarator, which is not a function declaration
372/// or definition and therefore is not permitted to have default
373/// arguments. This routine should be invoked for every declarator
374/// that is not a function declaration or definition.
375void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000383 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
390 // arguments.
391 MightBeFunction = false;
392 continue;
393 }
Alp Tokerc5350722014-02-26 22:27:52 +0000394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ++argIdx) {
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000397 if (Param->hasUnparsedDefaultArg()) {
Malcolm Parsonsca9d8342016-11-17 21:00:09 +0000398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
David Majnemerb3c6d522015-01-13 07:42:33 +0000400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000407 << SR;
Douglas Gregor58354032008-12-24 00:01:03 +0000408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000411 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000412 }
413 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000416 }
417 }
418}
419
David Majnemer502b0ed2013-06-25 23:09:30 +0000420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
Craig Toppere4794282012-09-21 04:33:26 +0000431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 bool Invalid = false;
438
Richard Smithc7d48d12015-05-20 17:50:35 +0000439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
Nico Webera6916892016-06-10 18:53:04 +0000474 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
David Majnemer502b0ed2013-06-25 23:09:30 +0000650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000651 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // the only declaration of the function or function template in the
653 // translation unit.
654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655 functionDeclHasDefaultArgument(Old)) {
656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 }
660
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000661 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000662}
663
Richard Smith7873de02016-08-11 22:25:46 +0000664NamedDecl *
665Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
666 MultiTemplateParamsArg TemplateParamLists) {
667 assert(D.isDecompositionDeclarator());
668 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
669
670 // The syntax only allows a decomposition declarator as a simple-declaration
671 // or a for-range-declaration, but we parse it in more cases than that.
672 if (!D.mayHaveDecompositionDeclarator()) {
673 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
674 << Decomp.getSourceRange();
675 return nullptr;
676 }
677
678 if (!TemplateParamLists.empty()) {
679 // FIXME: There's no rule against this, but there are also no rules that
680 // would actually make it usable, so we reject it for now.
681 Diag(TemplateParamLists.front()->getTemplateLoc(),
682 diag::err_decomp_decl_template);
683 return nullptr;
684 }
685
686 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
687 ? diag::warn_cxx14_compat_decomp_decl
688 : diag::ext_decomp_decl)
689 << Decomp.getSourceRange();
690
691 // The semantic context is always just the current context.
692 DeclContext *const DC = CurContext;
693
694 // C++1z [dcl.dcl]/8:
695 // The decl-specifier-seq shall contain only the type-specifier auto
696 // and cv-qualifiers.
697 auto &DS = D.getDeclSpec();
698 {
699 SmallVector<StringRef, 8> BadSpecifiers;
700 SmallVector<SourceLocation, 8> BadSpecifierLocs;
701 if (auto SCS = DS.getStorageClassSpec()) {
702 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
703 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
704 }
705 if (auto TSCS = DS.getThreadStorageClassSpec()) {
706 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
707 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
708 }
709 if (DS.isConstexprSpecified()) {
710 BadSpecifiers.push_back("constexpr");
711 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
712 }
713 if (DS.isInlineSpecified()) {
714 BadSpecifiers.push_back("inline");
715 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
716 }
717 if (!BadSpecifiers.empty()) {
718 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
719 Err << (int)BadSpecifiers.size()
720 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
721 // Don't add FixItHints to remove the specifiers; we do still respect
722 // them when building the underlying variable.
723 for (auto Loc : BadSpecifierLocs)
724 Err << SourceRange(Loc, Loc);
725 }
726 // We can't recover from it being declared as a typedef.
727 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
728 return nullptr;
729 }
730
731 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
732 QualType R = TInfo->getType();
733
734 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
735 UPPC_DeclarationType))
736 D.setInvalidType();
737
738 // The syntax only allows a single ref-qualifier prior to the decomposition
739 // declarator. No other declarator chunks are permitted. Also check the type
740 // specifier here.
741 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
742 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
743 (D.getNumTypeObjects() == 1 &&
744 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
745 Diag(Decomp.getLSquareLoc(),
746 (D.hasGroupingParens() ||
747 (D.getNumTypeObjects() &&
748 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
749 ? diag::err_decomp_decl_parens
750 : diag::err_decomp_decl_type)
751 << R;
752
753 // In most cases, there's no actual problem with an explicitly-specified
754 // type, but a function type won't work here, and ActOnVariableDeclarator
755 // shouldn't be called for such a type.
756 if (R->isFunctionType())
757 D.setInvalidType();
758 }
759
760 // Build the BindingDecls.
761 SmallVector<BindingDecl*, 8> Bindings;
762
763 // Build the BindingDecls.
764 for (auto &B : D.getDecompositionDeclarator().bindings()) {
765 // Check for name conflicts.
766 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
768 ForRedeclaration);
769 LookupName(Previous, S,
770 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
771
772 // It's not permitted to shadow a template parameter name.
773 if (Previous.isSingleResult() &&
774 Previous.getFoundDecl()->isTemplateParameter()) {
775 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
776 Previous.getFoundDecl());
777 Previous.clear();
778 }
779
780 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
781 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
782 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
783 /*AllowInlineNamespace*/false);
784 if (!Previous.empty()) {
785 auto *Old = Previous.getRepresentativeDecl();
786 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
787 Diag(Old->getLocation(), diag::note_previous_definition);
788 }
789
Richard Smith32cb8c92016-08-12 00:53:41 +0000790 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000791 PushOnScopeChains(BD, S, true);
792 Bindings.push_back(BD);
793 ParsingInitForAutoVars.insert(BD);
794 }
795
796 // There are no prior lookup results for the variable itself, because it
797 // is unnamed.
798 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
799 Decomp.getLSquareLoc());
800 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
801
802 // Build the variable that holds the non-decomposed object.
803 bool AddToScope = true;
804 NamedDecl *New =
805 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
806 MultiTemplateParamsArg(), AddToScope, Bindings);
807 CurContext->addHiddenDecl(New);
808
809 if (isInOpenMPDeclareTargetContext())
810 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
811
812 return New;
813}
814
815static bool checkSimpleDecomposition(
816 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000817 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000818 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
819 if ((int64_t)Bindings.size() != NumElems) {
820 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
821 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
822 << (NumElems < Bindings.size());
823 return true;
824 }
825
826 unsigned I = 0;
827 for (auto *B : Bindings) {
828 SourceLocation Loc = B->getLocation();
829 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
830 if (E.isInvalid())
831 return true;
832 E = GetInit(Loc, E.get(), I++);
833 if (E.isInvalid())
834 return true;
835 B->setBinding(ElemType, E.get());
836 }
837
838 return false;
839}
840
841static bool checkArrayLikeDecomposition(Sema &S,
842 ArrayRef<BindingDecl *> Bindings,
843 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000844 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000845 QualType ElemType) {
846 return checkSimpleDecomposition(
847 S, Bindings, Src, DecompType, NumElems, ElemType,
848 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
849 ExprResult E = S.ActOnIntegerConstant(Loc, I);
850 if (E.isInvalid())
851 return ExprError();
852 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
853 });
854}
855
856static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
857 ValueDecl *Src, QualType DecompType,
858 const ConstantArrayType *CAT) {
859 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
860 llvm::APSInt(CAT->getSize()),
861 CAT->getElementType());
862}
863
864static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
865 ValueDecl *Src, QualType DecompType,
866 const VectorType *VT) {
867 return checkArrayLikeDecomposition(
868 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
869 S.Context.getQualifiedType(VT->getElementType(),
870 DecompType.getQualifiers()));
871}
872
873static bool checkComplexDecomposition(Sema &S,
874 ArrayRef<BindingDecl *> Bindings,
875 ValueDecl *Src, QualType DecompType,
876 const ComplexType *CT) {
877 return checkSimpleDecomposition(
878 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
879 S.Context.getQualifiedType(CT->getElementType(),
880 DecompType.getQualifiers()),
881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
883 });
884}
885
886static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
887 TemplateArgumentListInfo &Args) {
888 SmallString<128> SS;
889 llvm::raw_svector_ostream OS(SS);
890 bool First = true;
891 for (auto &Arg : Args.arguments()) {
892 if (!First)
893 OS << ", ";
894 Arg.getArgument().print(PrintingPolicy, OS);
895 First = false;
896 }
897 return OS.str();
898}
899
900static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
901 SourceLocation Loc, StringRef Trait,
902 TemplateArgumentListInfo &Args,
903 unsigned DiagID) {
904 auto DiagnoseMissing = [&] {
905 if (DiagID)
906 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
907 Args);
908 return true;
909 };
910
911 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
912 NamespaceDecl *Std = S.getStdNamespace();
913 if (!Std)
914 return DiagnoseMissing();
915
916 // Look up the trait itself, within namespace std. We can diagnose various
917 // problems with this lookup even if we've been asked to not diagnose a
918 // missing specialization, because this can only fail if the user has been
919 // declaring their own names in namespace std or we don't support the
920 // standard library implementation in use.
921 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
922 Loc, Sema::LookupOrdinaryName);
923 if (!S.LookupQualifiedName(Result, Std))
924 return DiagnoseMissing();
925 if (Result.isAmbiguous())
926 return true;
927
928 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
929 if (!TraitTD) {
930 Result.suppressDiagnostics();
931 NamedDecl *Found = *Result.begin();
932 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
933 S.Diag(Found->getLocation(), diag::note_declared_at);
934 return true;
935 }
936
937 // Build the template-id.
938 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
939 if (TraitTy.isNull())
940 return true;
941 if (!S.isCompleteType(Loc, TraitTy)) {
942 if (DiagID)
943 S.RequireCompleteType(
944 Loc, TraitTy, DiagID,
945 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
946 return true;
947 }
948
949 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
950 assert(RD && "specialization of class template is not a class?");
951
952 // Look up the member of the trait type.
953 S.LookupQualifiedName(TraitMemberLookup, RD);
954 return TraitMemberLookup.isAmbiguous();
955}
956
957static TemplateArgumentLoc
958getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
959 uint64_t I) {
960 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
961 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
962}
963
964static TemplateArgumentLoc
965getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
966 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
967}
968
969namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
970
971static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
972 llvm::APSInt &Size) {
973 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
974
975 DeclarationName Value = S.PP.getIdentifierInfo("value");
976 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
977
978 // Form template argument list for tuple_size<T>.
979 TemplateArgumentListInfo Args(Loc, Loc);
980 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
981
982 // If there's no tuple_size specialization, it's not tuple-like.
983 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
984 return IsTupleLike::NotTupleLike;
985
986 // FIXME: According to the standard, we're not supposed to diagnose if any
987 // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
988 // results in an error), but this is subject to a pending CWG issue / NB
989 // comment, which says we do diagnose if tuple_size<T> is complete but
990 // tuple_size<T>::value is not an ICE.
991
992 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
993 LookupResult &R;
994 TemplateArgumentListInfo &Args;
995 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
996 : R(R), Args(Args) {}
997 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
998 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
999 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1000 }
1001 } Diagnoser(R, Args);
1002
1003 if (R.empty()) {
1004 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1005 return IsTupleLike::Error;
1006 }
1007
1008 ExprResult E =
1009 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1010 if (E.isInvalid())
1011 return IsTupleLike::Error;
1012
1013 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1014 if (E.isInvalid())
1015 return IsTupleLike::Error;
1016
1017 return IsTupleLike::TupleLike;
1018}
1019
1020/// \return std::tuple_element<I, T>::type.
1021static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1022 unsigned I, QualType T) {
1023 // Form template argument list for tuple_element<I, T>.
1024 TemplateArgumentListInfo Args(Loc, Loc);
1025 Args.addArgument(
1026 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1027 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1028
1029 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1030 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1031 if (lookupStdTypeTraitMember(
1032 S, R, Loc, "tuple_element", Args,
1033 diag::err_decomp_decl_std_tuple_element_not_specialized))
1034 return QualType();
1035
1036 auto *TD = R.getAsSingle<TypeDecl>();
1037 if (!TD) {
1038 R.suppressDiagnostics();
1039 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1040 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1041 if (!R.empty())
1042 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1043 return QualType();
1044 }
1045
1046 return S.Context.getTypeDeclType(TD);
1047}
1048
1049namespace {
1050struct BindingDiagnosticTrap {
1051 Sema &S;
1052 DiagnosticErrorTrap Trap;
1053 BindingDecl *BD;
1054
1055 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1056 : S(S), Trap(S.Diags), BD(BD) {}
1057 ~BindingDiagnosticTrap() {
1058 if (Trap.hasErrorOccurred())
1059 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1060 }
1061};
1062}
1063
Richard Smith3997b1b2016-08-12 01:55:21 +00001064static bool checkTupleLikeDecomposition(Sema &S,
1065 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001066 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001067 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001068 if ((int64_t)Bindings.size() != TupleSize) {
1069 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1070 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1071 << (TupleSize < Bindings.size());
1072 return true;
1073 }
1074
1075 if (Bindings.empty())
1076 return false;
1077
1078 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1079
1080 // [dcl.decomp]p3:
1081 // The unqualified-id get is looked up in the scope of E by class member
1082 // access lookup
1083 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1084 bool UseMemberGet = false;
1085 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1086 if (auto *RD = DecompType->getAsCXXRecordDecl())
1087 S.LookupQualifiedName(MemberGet, RD);
1088 if (MemberGet.isAmbiguous())
1089 return true;
1090 UseMemberGet = !MemberGet.empty();
1091 S.FilterAcceptableTemplateNames(MemberGet);
1092 }
1093
1094 unsigned I = 0;
1095 for (auto *B : Bindings) {
1096 BindingDiagnosticTrap Trap(S, B);
1097 SourceLocation Loc = B->getLocation();
1098
1099 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1100 if (E.isInvalid())
1101 return true;
1102
1103 // e is an lvalue if the type of the entity is an lvalue reference and
1104 // an xvalue otherwise
1105 if (!Src->getType()->isLValueReferenceType())
1106 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1107 E.get(), nullptr, VK_XValue);
1108
1109 TemplateArgumentListInfo Args(Loc, Loc);
1110 Args.addArgument(
1111 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1112
1113 if (UseMemberGet) {
1114 // if [lookup of member get] finds at least one declaration, the
1115 // initializer is e.get<i-1>().
1116 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1117 CXXScopeSpec(), SourceLocation(), nullptr,
1118 MemberGet, &Args, nullptr);
1119 if (E.isInvalid())
1120 return true;
1121
1122 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1123 } else {
1124 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1125 // in the associated namespaces.
1126 Expr *Get = UnresolvedLookupExpr::Create(
1127 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1128 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1129 UnresolvedSetIterator(), UnresolvedSetIterator());
1130
1131 Expr *Arg = E.get();
1132 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1133 }
1134 if (E.isInvalid())
1135 return true;
1136 Expr *Init = E.get();
1137
1138 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1139 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1140 if (T.isNull())
1141 return true;
1142
1143 // each vi is a variable of type "reference to T" initialized with the
1144 // initializer, where the reference is an lvalue reference if the
1145 // initializer is an lvalue and an rvalue reference otherwise
1146 QualType RefType =
1147 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1148 if (RefType.isNull())
1149 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001150 auto *RefVD = VarDecl::Create(
1151 S.Context, Src->getDeclContext(), Loc, Loc,
1152 B->getDeclName().getAsIdentifierInfo(), RefType,
1153 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1154 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1155 RefVD->setTSCSpec(Src->getTSCSpec());
1156 RefVD->setImplicit();
1157 if (Src->isInlineSpecified())
1158 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001159 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001160
Richard Smith97fcf4b2016-08-14 23:15:52 +00001161 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001162 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1163 InitializationSequence Seq(S, Entity, Kind, Init);
1164 E = Seq.Perform(S, Entity, Kind, Init);
1165 if (E.isInvalid())
1166 return true;
Richard Smithda383632016-08-15 01:33:41 +00001167 E = S.ActOnFinishFullExpr(E.get(), Loc);
1168 if (E.isInvalid())
1169 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001170 RefVD->setInit(E.get());
1171 RefVD->checkInitIsICE();
1172
Richard Smith97fcf4b2016-08-14 23:15:52 +00001173 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1174 DeclarationNameInfo(B->getDeclName(), Loc),
1175 RefVD);
1176 if (E.isInvalid())
1177 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001178
1179 B->setBinding(T, E.get());
1180 I++;
1181 }
1182
1183 return false;
1184}
1185
1186/// Find the base class to decompose in a built-in decomposition of a class type.
1187/// This base class search is, unfortunately, not quite like any other that we
1188/// perform anywhere else in C++.
1189static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1190 SourceLocation Loc,
1191 const CXXRecordDecl *RD,
1192 CXXCastPath &BasePath) {
1193 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1194 CXXBasePath &Path) {
1195 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1196 };
1197
1198 const CXXRecordDecl *ClassWithFields = nullptr;
1199 if (RD->hasDirectFields())
1200 // [dcl.decomp]p4:
1201 // Otherwise, all of E's non-static data members shall be public direct
1202 // members of E ...
1203 ClassWithFields = RD;
1204 else {
1205 // ... or of ...
1206 CXXBasePaths Paths;
1207 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1208 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1209 // If no classes have fields, just decompose RD itself. (This will work
1210 // if and only if zero bindings were provided.)
1211 return RD;
1212 }
1213
1214 CXXBasePath *BestPath = nullptr;
1215 for (auto &P : Paths) {
1216 if (!BestPath)
1217 BestPath = &P;
1218 else if (!S.Context.hasSameType(P.back().Base->getType(),
1219 BestPath->back().Base->getType())) {
1220 // ... the same ...
1221 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1222 << false << RD << BestPath->back().Base->getType()
1223 << P.back().Base->getType();
1224 return nullptr;
1225 } else if (P.Access < BestPath->Access) {
1226 BestPath = &P;
1227 }
1228 }
1229
1230 // ... unambiguous ...
1231 QualType BaseType = BestPath->back().Base->getType();
1232 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1233 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1234 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1235 return nullptr;
1236 }
1237
1238 // ... public base class of E.
1239 if (BestPath->Access != AS_public) {
1240 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1241 << RD << BaseType;
1242 for (auto &BS : *BestPath) {
1243 if (BS.Base->getAccessSpecifier() != AS_public) {
1244 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1245 << (BS.Base->getAccessSpecifier() == AS_protected)
1246 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1247 break;
1248 }
1249 }
1250 return nullptr;
1251 }
1252
1253 ClassWithFields = BaseType->getAsCXXRecordDecl();
1254 S.BuildBasePathArray(Paths, BasePath);
1255 }
1256
1257 // The above search did not check whether the selected class itself has base
1258 // classes with fields, so check that now.
1259 CXXBasePaths Paths;
1260 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1261 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1262 << (ClassWithFields == RD) << RD << ClassWithFields
1263 << Paths.front().back().Base->getType();
1264 return nullptr;
1265 }
1266
1267 return ClassWithFields;
1268}
1269
1270static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1271 ValueDecl *Src, QualType DecompType,
1272 const CXXRecordDecl *RD) {
1273 CXXCastPath BasePath;
1274 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1275 if (!RD)
1276 return true;
1277 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1278 DecompType.getQualifiers());
1279
1280 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001281 unsigned NumFields =
1282 std::count_if(RD->field_begin(), RD->field_end(),
1283 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001284 assert(Bindings.size() != NumFields);
1285 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1286 << DecompType << (unsigned)Bindings.size() << NumFields
1287 << (NumFields < Bindings.size());
1288 return true;
1289 };
1290
1291 // all of E's non-static data members shall be public [...] members,
1292 // E shall not have an anonymous union member, ...
1293 unsigned I = 0;
1294 for (auto *FD : RD->fields()) {
1295 if (FD->isUnnamedBitfield())
1296 continue;
1297
1298 if (FD->isAnonymousStructOrUnion()) {
1299 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1300 << DecompType << FD->getType()->isUnionType();
1301 S.Diag(FD->getLocation(), diag::note_declared_at);
1302 return true;
1303 }
1304
1305 // We have a real field to bind.
1306 if (I >= Bindings.size())
1307 return DiagnoseBadNumberOfBindings();
1308 auto *B = Bindings[I++];
1309
1310 SourceLocation Loc = B->getLocation();
1311 if (FD->getAccess() != AS_public) {
1312 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1313
1314 // Determine whether the access specifier was explicit.
1315 bool Implicit = true;
1316 for (const auto *D : RD->decls()) {
1317 if (declaresSameEntity(D, FD))
1318 break;
1319 if (isa<AccessSpecDecl>(D)) {
1320 Implicit = false;
1321 break;
1322 }
1323 }
1324
1325 S.Diag(FD->getLocation(), diag::note_access_natural)
1326 << (FD->getAccess() == AS_protected) << Implicit;
1327 return true;
1328 }
1329
1330 // Initialize the binding to Src.FD.
1331 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1332 if (E.isInvalid())
1333 return true;
1334 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1335 VK_LValue, &BasePath);
1336 if (E.isInvalid())
1337 return true;
1338 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1339 CXXScopeSpec(), FD,
1340 DeclAccessPair::make(FD, FD->getAccess()),
1341 DeclarationNameInfo(FD->getDeclName(), Loc));
1342 if (E.isInvalid())
1343 return true;
1344
1345 // If the type of the member is T, the referenced type is cv T, where cv is
1346 // the cv-qualification of the decomposition expression.
1347 //
1348 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1349 // 'const' to the type of the field.
1350 Qualifiers Q = DecompType.getQualifiers();
1351 if (FD->isMutable())
1352 Q.removeConst();
1353 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1354 }
1355
1356 if (I != Bindings.size())
1357 return DiagnoseBadNumberOfBindings();
1358
1359 return false;
1360}
1361
Richard Smith3997b1b2016-08-12 01:55:21 +00001362void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001363 QualType DecompType = DD->getType();
1364
1365 // If the type of the decomposition is dependent, then so is the type of
1366 // each binding.
1367 if (DecompType->isDependentType()) {
1368 for (auto *B : DD->bindings())
1369 B->setType(Context.DependentTy);
1370 return;
1371 }
1372
1373 DecompType = DecompType.getNonReferenceType();
1374 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1375
1376 // C++1z [dcl.decomp]/2:
1377 // If E is an array type [...]
1378 // As an extension, we also support decomposition of built-in complex and
1379 // vector types.
1380 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1381 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1382 DD->setInvalidDecl();
1383 return;
1384 }
1385 if (auto *VT = DecompType->getAs<VectorType>()) {
1386 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1387 DD->setInvalidDecl();
1388 return;
1389 }
1390 if (auto *CT = DecompType->getAs<ComplexType>()) {
1391 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1392 DD->setInvalidDecl();
1393 return;
1394 }
1395
1396 // C++1z [dcl.decomp]/3:
1397 // if the expression std::tuple_size<E>::value is a well-formed integral
1398 // constant expression, [...]
1399 llvm::APSInt TupleSize(32);
1400 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1401 case IsTupleLike::Error:
1402 DD->setInvalidDecl();
1403 return;
1404
1405 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001406 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001407 DD->setInvalidDecl();
1408 return;
1409
1410 case IsTupleLike::NotTupleLike:
1411 break;
1412 }
1413
1414 // C++1z [dcl.dcl]/8:
1415 // [E shall be of array or non-union class type]
1416 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1417 if (!RD || RD->isUnion()) {
1418 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1419 << DD << !RD << DecompType;
1420 DD->setInvalidDecl();
1421 return;
1422 }
1423
1424 // C++1z [dcl.decomp]/4:
1425 // all of E's non-static data members shall be [...] direct members of
1426 // E or of the same unambiguous public base class of E, ...
1427 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1428 DD->setInvalidDecl();
1429}
1430
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001431/// \brief Merge the exception specifications of two variable declarations.
1432///
1433/// This is called when there's a redeclaration of a VarDecl. The function
1434/// checks if the redeclaration might have an exception specification and
1435/// validates compatibility and merges the specs if necessary.
1436void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1437 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001438 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001439 return;
1440
1441 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1442 "Should only be called if types are otherwise the same.");
1443
1444 QualType NewType = New->getType();
1445 QualType OldType = Old->getType();
1446
1447 // We're only interested in pointers and references to functions, as well
1448 // as pointers to member functions.
1449 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1450 NewType = R->getPointeeType();
1451 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1452 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1453 NewType = P->getPointeeType();
1454 OldType = OldType->getAs<PointerType>()->getPointeeType();
1455 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1456 NewType = M->getPointeeType();
1457 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1458 }
1459
1460 if (!NewType->isFunctionProtoType())
1461 return;
1462
1463 // There's lots of special cases for functions. For function pointers, system
1464 // libraries are hopefully not as broken so that we don't need these
1465 // workarounds.
1466 if (CheckEquivalentExceptionSpec(
1467 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1468 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1469 New->setInvalidDecl();
1470 }
1471}
1472
Chris Lattner199abbc2008-04-08 05:04:30 +00001473/// CheckCXXDefaultArguments - Verify that the default arguments for a
1474/// function declaration are well-formed according to C++
1475/// [dcl.fct.default].
1476void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1477 unsigned NumParams = FD->getNumParams();
1478 unsigned p;
1479
1480 // Find first parameter with a default argument
1481 for (p = 0; p < NumParams; ++p) {
1482 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001483 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001484 break;
1485 }
1486
Benjamin Kramerfe257592015-03-27 13:58:41 +00001487 // C++11 [dcl.fct.default]p4:
1488 // In a given function declaration, each parameter subsequent to a parameter
1489 // with a default argument shall have a default argument supplied in this or
1490 // a previous declaration or shall be a function parameter pack. A default
1491 // argument shall not be redefined by a later declaration (not even to the
1492 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001493 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001494 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001495 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001496 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001497 if (Param->isInvalidDecl())
1498 /* We already complained about this parameter. */;
1499 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001500 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001501 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001502 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001503 else
Mike Stump11289f42009-09-09 15:08:12 +00001504 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001505 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Chris Lattner199abbc2008-04-08 05:04:30 +00001507 LastMissingDefaultArg = p;
1508 }
1509 }
1510
1511 if (LastMissingDefaultArg > 0) {
1512 // Some default arguments were missing. Clear out all of the
1513 // default arguments up to (and including) the last missing
1514 // default argument, so that we leave the function parameters
1515 // in a semantically valid state.
1516 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1517 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001518 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001519 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001520 }
1521 }
1522 }
1523}
Douglas Gregor556877c2008-04-13 21:30:24 +00001524
Richard Smitheb3c10c2011-10-01 02:31:28 +00001525// CheckConstexprParameterTypes - Check whether a function's parameter types
1526// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001527// diagnostic and return false.
1528static bool CheckConstexprParameterTypes(Sema &SemaRef,
1529 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001530 unsigned ArgIndex = 0;
1531 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001532 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1533 e = FT->param_type_end();
1534 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001535 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1536 SourceLocation ParamLoc = PD->getLocation();
1537 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001538 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001539 diag::err_constexpr_non_literal_param,
1540 ArgIndex+1, PD->getSourceRange(),
1541 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001542 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001543 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001544 return true;
1545}
1546
1547/// \brief Get diagnostic %select index for tag kind for
1548/// record diagnostic message.
1549/// WARNING: Indexes apply to particular diagnostics only!
1550///
1551/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001552static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001553 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001554 case TTK_Struct: return 0;
1555 case TTK_Interface: return 1;
1556 case TTK_Class: return 2;
1557 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001558 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001559}
1560
1561// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1562// the requirements of a constexpr function definition or a constexpr
1563// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001564// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001565//
Richard Smith3607ffe2012-02-13 03:54:03 +00001566// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1567bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001568 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1569 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001570 // C++11 [dcl.constexpr]p4:
1571 // The definition of a constexpr constructor shall satisfy the following
1572 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001573 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001574 const CXXRecordDecl *RD = MD->getParent();
1575 if (RD->getNumVBases()) {
1576 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1577 << isa<CXXConstructorDecl>(NewFD)
1578 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001579 for (const auto &I : RD->vbases())
1580 Diag(I.getLocStart(),
1581 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001582 return false;
1583 }
Richard Smith7971b692012-01-13 04:54:00 +00001584 }
1585
1586 if (!isa<CXXConstructorDecl>(NewFD)) {
1587 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001588 // The definition of a constexpr function shall satisfy the following
1589 // constraints:
1590 // - it shall not be virtual;
1591 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1592 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001593 Method = Method->getCanonicalDecl();
1594 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001595
Richard Smith3607ffe2012-02-13 03:54:03 +00001596 // If it's not obvious why this function is virtual, find an overridden
1597 // function which uses the 'virtual' keyword.
1598 const CXXMethodDecl *WrittenVirtual = Method;
1599 while (!WrittenVirtual->isVirtualAsWritten())
1600 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1601 if (WrittenVirtual != Method)
1602 Diag(WrittenVirtual->getLocation(),
1603 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001604 return false;
1605 }
1606
1607 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001608 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001609 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001610 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001611 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001612 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001613 }
1614
Richard Smith7971b692012-01-13 04:54:00 +00001615 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001616 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001617 return false;
1618
Richard Smitheb3c10c2011-10-01 02:31:28 +00001619 return true;
1620}
1621
1622/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001623/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001624///
Richard Smithd9f663b2013-04-22 15:31:51 +00001625/// \return true if the body is OK (maybe only as an extension), false if we
1626/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001627static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001628 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1629 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001630 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1631 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001632 for (const auto *DclIt : DS->decls()) {
1633 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001634 case Decl::StaticAssert:
1635 case Decl::Using:
1636 case Decl::UsingShadow:
1637 case Decl::UsingDirective:
1638 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001639 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001640 // - static_assert-declarations
1641 // - using-declarations,
1642 // - using-directives,
1643 continue;
1644
1645 case Decl::Typedef:
1646 case Decl::TypeAlias: {
1647 // - typedef declarations and alias-declarations that do not define
1648 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001649 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001650 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1651 // Don't allow variably-modified types in constexpr functions.
1652 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1653 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1654 << TL.getSourceRange() << TL.getType()
1655 << isa<CXXConstructorDecl>(Dcl);
1656 return false;
1657 }
1658 continue;
1659 }
1660
1661 case Decl::Enum:
1662 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001663 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001664 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001665 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001666 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001667 ? diag::warn_cxx11_compat_constexpr_type_definition
1668 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001669 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001670 continue;
1671
Richard Smithd9f663b2013-04-22 15:31:51 +00001672 case Decl::EnumConstant:
1673 case Decl::IndirectField:
1674 case Decl::ParmVar:
1675 // These can only appear with other declarations which are banned in
1676 // C++11 and permitted in C++1y, so ignore them.
1677 continue;
1678
Richard Smithdca60b42016-08-12 00:39:32 +00001679 case Decl::Var:
1680 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001681 // C++1y [dcl.constexpr]p3 allows anything except:
1682 // a definition of a variable of non-literal type or of static or
1683 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001684 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001685 if (VD->isThisDeclarationADefinition()) {
1686 if (VD->isStaticLocal()) {
1687 SemaRef.Diag(VD->getLocation(),
1688 diag::err_constexpr_local_var_static)
1689 << isa<CXXConstructorDecl>(Dcl)
1690 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1691 return false;
1692 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001693 if (!VD->getType()->isDependentType() &&
1694 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001695 VD->getLocation(), VD->getType(),
1696 diag::err_constexpr_local_var_non_literal_type,
1697 isa<CXXConstructorDecl>(Dcl)))
1698 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001699 if (!VD->getType()->isDependentType() &&
1700 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001701 SemaRef.Diag(VD->getLocation(),
1702 diag::err_constexpr_local_var_no_init)
1703 << isa<CXXConstructorDecl>(Dcl);
1704 return false;
1705 }
1706 }
1707 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001708 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001709 ? diag::warn_cxx11_compat_constexpr_local_var
1710 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001711 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001712 continue;
1713 }
1714
1715 case Decl::NamespaceAlias:
1716 case Decl::Function:
1717 // These are disallowed in C++11 and permitted in C++1y. Allow them
1718 // everywhere as an extension.
1719 if (!Cxx1yLoc.isValid())
1720 Cxx1yLoc = DS->getLocStart();
1721 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001722
1723 default:
1724 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1725 << isa<CXXConstructorDecl>(Dcl);
1726 return false;
1727 }
1728 }
1729
1730 return true;
1731}
1732
1733/// Check that the given field is initialized within a constexpr constructor.
1734///
1735/// \param Dcl The constexpr constructor being checked.
1736/// \param Field The field being checked. This may be a member of an anonymous
1737/// struct or union nested within the class being checked.
1738/// \param Inits All declarations, including anonymous struct/union members and
1739/// indirect members, for which any initialization was provided.
1740/// \param Diagnosed Set to true if an error is produced.
1741static void CheckConstexprCtorInitializer(Sema &SemaRef,
1742 const FunctionDecl *Dcl,
1743 FieldDecl *Field,
1744 llvm::SmallSet<Decl*, 16> &Inits,
1745 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001746 if (Field->isInvalidDecl())
1747 return;
1748
Douglas Gregor556e5862011-10-10 17:22:13 +00001749 if (Field->isUnnamedBitfield())
1750 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001751
Richard Smithab44d5b2013-12-10 08:25:00 +00001752 // Anonymous unions with no variant members and empty anonymous structs do not
1753 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1754 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001755 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001756 (Field->getType()->isUnionType()
1757 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1758 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001759 return;
1760
Richard Smitheb3c10c2011-10-01 02:31:28 +00001761 if (!Inits.count(Field)) {
1762 if (!Diagnosed) {
1763 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1764 Diagnosed = true;
1765 }
1766 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1767 } else if (Field->isAnonymousStructOrUnion()) {
1768 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001769 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001770 // If an anonymous union contains an anonymous struct of which any member
1771 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001772 if (!RD->isUnion() || Inits.count(I))
1773 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001774 }
1775}
1776
Richard Smithd9f663b2013-04-22 15:31:51 +00001777/// Check the provided statement is allowed in a constexpr function
1778/// definition.
1779static bool
1780CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001781 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001782 SourceLocation &Cxx1yLoc) {
1783 // - its function-body shall be [...] a compound-statement that contains only
1784 switch (S->getStmtClass()) {
1785 case Stmt::NullStmtClass:
1786 // - null statements,
1787 return true;
1788
1789 case Stmt::DeclStmtClass:
1790 // - static_assert-declarations
1791 // - using-declarations,
1792 // - using-directives,
1793 // - typedef declarations and alias-declarations that do not define
1794 // classes or enumerations,
1795 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1796 return false;
1797 return true;
1798
1799 case Stmt::ReturnStmtClass:
1800 // - and exactly one return statement;
1801 if (isa<CXXConstructorDecl>(Dcl)) {
1802 // C++1y allows return statements in constexpr constructors.
1803 if (!Cxx1yLoc.isValid())
1804 Cxx1yLoc = S->getLocStart();
1805 return true;
1806 }
1807
1808 ReturnStmts.push_back(S->getLocStart());
1809 return true;
1810
1811 case Stmt::CompoundStmtClass: {
1812 // C++1y allows compound-statements.
1813 if (!Cxx1yLoc.isValid())
1814 Cxx1yLoc = S->getLocStart();
1815
1816 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001817 for (auto *BodyIt : CompStmt->body()) {
1818 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001819 Cxx1yLoc))
1820 return false;
1821 }
1822 return true;
1823 }
1824
1825 case Stmt::AttributedStmtClass:
1826 if (!Cxx1yLoc.isValid())
1827 Cxx1yLoc = S->getLocStart();
1828 return true;
1829
1830 case Stmt::IfStmtClass: {
1831 // C++1y allows if-statements.
1832 if (!Cxx1yLoc.isValid())
1833 Cxx1yLoc = S->getLocStart();
1834
1835 IfStmt *If = cast<IfStmt>(S);
1836 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1837 Cxx1yLoc))
1838 return false;
1839 if (If->getElse() &&
1840 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1841 Cxx1yLoc))
1842 return false;
1843 return true;
1844 }
1845
1846 case Stmt::WhileStmtClass:
1847 case Stmt::DoStmtClass:
1848 case Stmt::ForStmtClass:
1849 case Stmt::CXXForRangeStmtClass:
1850 case Stmt::ContinueStmtClass:
1851 // C++1y allows all of these. We don't allow them as extensions in C++11,
1852 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001853 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001854 break;
1855 if (!Cxx1yLoc.isValid())
1856 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001857 for (Stmt *SubStmt : S->children())
1858 if (SubStmt &&
1859 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001860 Cxx1yLoc))
1861 return false;
1862 return true;
1863
1864 case Stmt::SwitchStmtClass:
1865 case Stmt::CaseStmtClass:
1866 case Stmt::DefaultStmtClass:
1867 case Stmt::BreakStmtClass:
1868 // C++1y allows switch-statements, and since they don't need variable
1869 // mutation, we can reasonably allow them in C++11 as an extension.
1870 if (!Cxx1yLoc.isValid())
1871 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001872 for (Stmt *SubStmt : S->children())
1873 if (SubStmt &&
1874 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001875 Cxx1yLoc))
1876 return false;
1877 return true;
1878
1879 default:
1880 if (!isa<Expr>(S))
1881 break;
1882
1883 // C++1y allows expression-statements.
1884 if (!Cxx1yLoc.isValid())
1885 Cxx1yLoc = S->getLocStart();
1886 return true;
1887 }
1888
1889 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1890 << isa<CXXConstructorDecl>(Dcl);
1891 return false;
1892}
1893
Richard Smitheb3c10c2011-10-01 02:31:28 +00001894/// Check the body for the given constexpr function declaration only contains
1895/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1896///
1897/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001898bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001899 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001900 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001901 // The definition of a constexpr function shall satisfy the following
1902 // constraints: [...]
1903 // - its function-body shall be = delete, = default, or a
1904 // compound-statement
1905 //
Richard Smith74388b42012-02-04 00:33:54 +00001906 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001907 // In the definition of a constexpr constructor, [...]
1908 // - its function-body shall not be a function-try-block;
1909 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1910 << isa<CXXConstructorDecl>(Dcl);
1911 return false;
1912 }
1913
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001914 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001915
1916 // - its function-body shall be [...] a compound-statement that contains only
1917 // [... list of cases ...]
1918 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1919 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001920 for (auto *BodyIt : CompBody->body()) {
1921 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001922 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001923 }
1924
Richard Smithd9f663b2013-04-22 15:31:51 +00001925 if (Cxx1yLoc.isValid())
1926 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001927 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001928 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1929 : diag::ext_constexpr_body_invalid_stmt)
1930 << isa<CXXConstructorDecl>(Dcl);
1931
Richard Smitheb3c10c2011-10-01 02:31:28 +00001932 if (const CXXConstructorDecl *Constructor
1933 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1934 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001935 // DR1359:
1936 // - every non-variant non-static data member and base class sub-object
1937 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001938 // DR1460:
1939 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001940 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001941 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001942 if (Constructor->getNumCtorInitializers() == 0 &&
1943 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001944 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1945 return false;
1946 }
Richard Smithf368fb42011-10-10 16:38:04 +00001947 } else if (!Constructor->isDependentContext() &&
1948 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001949 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1950
1951 // Skip detailed checking if we have enough initializers, and we would
1952 // allow at most one initializer per member.
1953 bool AnyAnonStructUnionMembers = false;
1954 unsigned Fields = 0;
1955 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1956 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001957 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001958 AnyAnonStructUnionMembers = true;
1959 break;
1960 }
1961 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001962 // DR1460:
1963 // - if the class is a union-like class, but is not a union, for each of
1964 // its anonymous union members having variant members, exactly one of
1965 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001966 if (AnyAnonStructUnionMembers ||
1967 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1968 // Check initialization of non-static data members. Base classes are
1969 // always initialized so do not need to be checked. Dependent bases
1970 // might not have initializers in the member initializer list.
1971 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001972 for (const auto *I: Constructor->inits()) {
1973 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001974 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001975 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001976 Inits.insert(ID->chain_begin(), ID->chain_end());
1977 }
1978
1979 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001980 for (auto *I : RD->fields())
1981 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001982 if (Diagnosed)
1983 return false;
1984 }
1985 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001986 } else {
1987 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001988 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001989 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001990 // otherwise if there's no return statement, the function cannot
1991 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001992 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001993 (Dcl->getReturnType()->isVoidType() ||
1994 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001995 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001996 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1997 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00001998 if (!OK)
1999 return false;
2000 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002001 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002002 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002003 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2004 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002005 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2006 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002007 }
2008 }
2009
Richard Smith74388b42012-02-04 00:33:54 +00002010 // C++11 [dcl.constexpr]p5:
2011 // if no function argument values exist such that the function invocation
2012 // substitution would produce a constant expression, the program is
2013 // ill-formed; no diagnostic required.
2014 // C++11 [dcl.constexpr]p3:
2015 // - every constructor call and implicit conversion used in initializing the
2016 // return value shall be one of those allowed in a constant expression.
2017 // C++11 [dcl.constexpr]p4:
2018 // - every constructor involved in initializing non-static data members and
2019 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002020 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002021 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002022 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002023 << isa<CXXConstructorDecl>(Dcl);
2024 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2025 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002026 // Don't return false here: we allow this for compatibility in
2027 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002028 }
2029
Richard Smitheb3c10c2011-10-01 02:31:28 +00002030 return true;
2031}
2032
Douglas Gregor61956c42008-10-31 09:07:45 +00002033/// isCurrentClassName - Determine whether the identifier II is the
2034/// name of the class type currently being defined. In the case of
2035/// nested classes, this will only return true if II is the name of
2036/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002037bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2038 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002039 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002040
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002041 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002042 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002043 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002044 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2045 } else
2046 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2047
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002048 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002049 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002050 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002051}
2052
Richard Smithfb8b7b92013-10-15 00:00:26 +00002053/// \brief Determine whether the identifier II is a typo for the name of
2054/// the class type currently being defined. If so, update it to the identifier
2055/// that should have been used.
2056bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2057 assert(getLangOpts().CPlusPlus && "No class names in C!");
2058
2059 if (!getLangOpts().SpellChecking)
2060 return false;
2061
2062 CXXRecordDecl *CurDecl;
2063 if (SS && SS->isSet() && !SS->isInvalid()) {
2064 DeclContext *DC = computeDeclContext(*SS, true);
2065 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2066 } else
2067 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2068
2069 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2070 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2071 < II->getLength()) {
2072 II = CurDecl->getIdentifier();
2073 return true;
2074 }
2075
2076 return false;
2077}
2078
Douglas Gregordc974572012-11-10 07:24:09 +00002079/// \brief Determine whether the given class is a base class of the given
2080/// class, including looking at dependent bases.
2081static bool findCircularInheritance(const CXXRecordDecl *Class,
2082 const CXXRecordDecl *Current) {
2083 SmallVector<const CXXRecordDecl*, 8> Queue;
2084
2085 Class = Class->getCanonicalDecl();
2086 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002087 for (const auto &I : Current->bases()) {
2088 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002089 if (!Base)
2090 continue;
2091
2092 Base = Base->getDefinition();
2093 if (!Base)
2094 continue;
2095
2096 if (Base->getCanonicalDecl() == Class)
2097 return true;
2098
2099 Queue.push_back(Base);
2100 }
2101
2102 if (Queue.empty())
2103 return false;
2104
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002105 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002106 }
2107
2108 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002109}
2110
Mike Stump11289f42009-09-09 15:08:12 +00002111/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002112///
2113/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2114/// and returns NULL otherwise.
2115CXXBaseSpecifier *
2116Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2117 SourceRange SpecifierRange,
2118 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002119 TypeSourceInfo *TInfo,
2120 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002121 QualType BaseType = TInfo->getType();
2122
Douglas Gregor463421d2009-03-03 04:44:36 +00002123 // C++ [class.union]p1:
2124 // A union shall not have base classes.
2125 if (Class->isUnion()) {
2126 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2127 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002128 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002129 }
2130
Douglas Gregor752a5952011-01-03 22:36:02 +00002131 if (EllipsisLoc.isValid() &&
2132 !TInfo->getType()->containsUnexpandedParameterPack()) {
2133 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2134 << TInfo->getTypeLoc().getSourceRange();
2135 EllipsisLoc = SourceLocation();
2136 }
Douglas Gregor62004702012-11-10 01:18:17 +00002137
2138 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2139
2140 if (BaseType->isDependentType()) {
2141 // Make sure that we don't have circular inheritance among our dependent
2142 // bases. For non-dependent bases, the check for completeness below handles
2143 // this.
2144 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2145 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2146 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002147 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002148 Diag(BaseLoc, diag::err_circular_inheritance)
2149 << BaseType << Context.getTypeDeclType(Class);
2150
2151 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2152 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2153 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002154
2155 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002156 }
2157 }
2158
Mike Stump11289f42009-09-09 15:08:12 +00002159 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002160 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002161 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002162 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002163
2164 // Base specifiers must be record types.
2165 if (!BaseType->isRecordType()) {
2166 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002167 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002168 }
2169
2170 // C++ [class.union]p1:
2171 // A union shall not be used as a base class.
2172 if (BaseType->isUnionType()) {
2173 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002174 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002175 }
2176
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002177 // For the MS ABI, propagate DLL attributes to base class templates.
2178 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2179 if (Attr *ClassAttr = getDLLAttr(Class)) {
2180 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2181 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002182 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2183 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002184 }
2185 }
2186 }
2187
Douglas Gregor463421d2009-03-03 04:44:36 +00002188 // C++ [class.derived]p2:
2189 // The class-name in a base-specifier shall not be an incompletely
2190 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002191 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002192 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002193 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002194 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002195 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002196
Eli Friedmanc96d4962009-08-15 21:55:26 +00002197 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002198 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002199 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002200 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002201 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002202 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002203 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002204
David Majnemer9b1754d2013-11-02 12:00:36 +00002205 // A class which contains a flexible array member is not suitable for use as a
2206 // base class:
2207 // - If the layout determines that a base comes before another base,
2208 // the flexible array member would index into the subsequent base.
2209 // - If the layout determines that base comes before the derived class,
2210 // the flexible array member would index into the derived class.
2211 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2212 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2213 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002214 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002215 }
2216
Anders Carlsson65c76d32011-03-25 14:55:14 +00002217 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002218 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002219 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002220 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002221 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002222 << CXXBaseDecl->getDeclName()
2223 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002224 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2225 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002226 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002227 }
2228
John McCall3696dcb2010-08-17 07:23:57 +00002229 if (BaseDecl->isInvalidDecl())
2230 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002231
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002232 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002233 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002234 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002235 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002236}
2237
Douglas Gregor556877c2008-04-13 21:30:24 +00002238/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2239/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002240/// example:
2241/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002242/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002243BaseResult
John McCall48871652010-08-21 09:40:31 +00002244Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002245 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002246 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002247 ParsedType basetype, SourceLocation BaseLoc,
2248 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002249 if (!classdecl)
2250 return true;
2251
Douglas Gregorc40290e2009-03-09 23:48:35 +00002252 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002253 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002254 if (!Class)
2255 return true;
2256
David Majnemer5ef4fe72014-06-13 06:43:46 +00002257 // We haven't yet attached the base specifiers.
2258 Class->setIsParsingBaseSpecifiers();
2259
Richard Smith4c96e992013-02-19 23:47:15 +00002260 // We do not support any C++11 attributes on base-specifiers yet.
2261 // Diagnose any attributes we see.
2262 if (!Attributes.empty()) {
2263 for (AttributeList *Attr = Attributes.getList(); Attr;
2264 Attr = Attr->getNext()) {
2265 if (Attr->isInvalid() ||
2266 Attr->getKind() == AttributeList::IgnoredAttribute)
2267 continue;
2268 Diag(Attr->getLoc(),
2269 Attr->getKind() == AttributeList::UnknownAttribute
2270 ? diag::warn_unknown_attribute_ignored
2271 : diag::err_base_specifier_attribute)
2272 << Attr->getName();
2273 }
2274 }
2275
Craig Topperc3ec1492014-05-26 06:22:03 +00002276 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002277 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002278
Douglas Gregor752a5952011-01-03 22:36:02 +00002279 if (EllipsisLoc.isInvalid() &&
2280 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002281 UPPC_BaseType))
2282 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002283
Douglas Gregor463421d2009-03-03 04:44:36 +00002284 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002285 Virtual, Access, TInfo,
2286 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002287 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002288 else
2289 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002290
Douglas Gregor463421d2009-03-03 04:44:36 +00002291 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002292}
Douglas Gregor556877c2008-04-13 21:30:24 +00002293
Nathan Sidwell44b21742015-01-19 01:44:02 +00002294/// Use small set to collect indirect bases. As this is only used
2295/// locally, there's no need to abstract the small size parameter.
2296typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2297
2298/// \brief Recursively add the bases of Type. Don't add Type itself.
2299static void
2300NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2301 const QualType &Type)
2302{
2303 // Even though the incoming type is a base, it might not be
2304 // a class -- it could be a template parm, for instance.
2305 if (auto Rec = Type->getAs<RecordType>()) {
2306 auto Decl = Rec->getAsCXXRecordDecl();
2307
2308 // Iterate over its bases.
2309 for (const auto &BaseSpec : Decl->bases()) {
2310 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2311 .getUnqualifiedType();
2312 if (Set.insert(Base).second)
2313 // If we've not already seen it, recurse.
2314 NoteIndirectBases(Context, Set, Base);
2315 }
2316 }
2317}
2318
Douglas Gregor463421d2009-03-03 04:44:36 +00002319/// \brief Performs the actual work of attaching the given base class
2320/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002321bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2322 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2323 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002324 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002325
2326 // Used to keep track of which base types we have already seen, so
2327 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002328 // that the key is always the unqualified canonical type of the base
2329 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002330 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2331
Nathan Sidwell44b21742015-01-19 01:44:02 +00002332 // Used to track indirect bases so we can see if a direct base is
2333 // ambiguous.
2334 IndirectBaseSet IndirectBaseTypes;
2335
Douglas Gregor29a92472008-10-22 17:49:05 +00002336 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002337 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002338 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002339 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002340 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002341 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002342 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002343
2344 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2345 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002346 // C++ [class.mi]p3:
2347 // A class shall not be specified as a direct base class of a
2348 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002349 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002350 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002351 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002352 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002353
2354 // Delete the duplicate base class specifier; we're going to
2355 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002356 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002357
2358 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002359 } else {
2360 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002361 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002362 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002363
2364 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002365 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002366 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2367
John McCalldb632ac2012-09-25 07:32:39 +00002368 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2369 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2370 if (Class->isInterface() &&
2371 (!RD->isInterface() ||
2372 KnownBase->getAccessSpecifier() != AS_public)) {
2373 // The Microsoft extension __interface does not permit bases that
2374 // are not themselves public interfaces.
2375 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2376 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2377 << RD->getSourceRange();
2378 Invalid = true;
2379 }
2380 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002381 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002382 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002383 }
2384 }
2385
2386 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002387 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002388
2389 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2390 // Check whether this direct base is inaccessible due to ambiguity.
2391 QualType BaseType = Bases[idx]->getType();
2392 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2393 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002394
Nathan Sidwell44b21742015-01-19 01:44:02 +00002395 if (IndirectBaseTypes.count(CanonicalBase)) {
2396 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2397 /*DetectVirtual=*/true);
2398 bool found
2399 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2400 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002401 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002402
2403 if (Paths.isAmbiguous(CanonicalBase))
2404 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2405 << BaseType << getAmbiguousPathsDisplayString(Paths)
2406 << Bases[idx]->getSourceRange();
2407 else
2408 assert(Bases[idx]->isVirtual());
2409 }
2410
2411 // Delete the base class specifier, since its data has been copied
2412 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002413 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002414 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002415
2416 return Invalid;
2417}
2418
2419/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2420/// class, after checking whether there are any duplicate base
2421/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002422void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2423 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2424 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002425 return;
2426
2427 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002428 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002429}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002430
Douglas Gregor36d1b142009-10-06 17:59:45 +00002431/// \brief Determine whether the type \p Derived is a C++ class that is
2432/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002433bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002434 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002435 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002436
Douglas Gregor45bb4832013-03-26 23:36:30 +00002437 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002438 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002439 return false;
2440
Douglas Gregor45bb4832013-03-26 23:36:30 +00002441 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002442 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002443 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002444
2445 // If either the base or the derived type is invalid, don't try to
2446 // check whether one is derived from the other.
2447 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2448 return false;
2449
Richard Smithdb0ac552015-12-18 22:40:25 +00002450 // FIXME: In a modules build, do we need the entire path to be visible for us
2451 // to be able to use the inheritance relationship?
2452 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2453 return false;
2454
Richard Smith0f59cb32015-12-18 21:45:41 +00002455 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002456}
2457
2458/// \brief Determine whether the type \p Derived is a C++ class that is
2459/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002460bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2461 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002462 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002463 return false;
2464
Douglas Gregor45bb4832013-03-26 23:36:30 +00002465 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002466 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002467 return false;
2468
Douglas Gregor45bb4832013-03-26 23:36:30 +00002469 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002470 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002471 return false;
2472
Richard Smithdb0ac552015-12-18 22:40:25 +00002473 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2474 return false;
2475
Douglas Gregor36d1b142009-10-06 17:59:45 +00002476 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2477}
2478
Anders Carlssona70cff62010-04-24 19:06:50 +00002479void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002480 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002481 assert(BasePathArray.empty() && "Base path array must be empty!");
2482 assert(Paths.isRecordingPaths() && "Must record paths!");
2483
2484 const CXXBasePath &Path = Paths.front();
2485
2486 // We first go backward and check if we have a virtual base.
2487 // FIXME: It would be better if CXXBasePath had the base specifier for
2488 // the nearest virtual base.
2489 unsigned Start = 0;
2490 for (unsigned I = Path.size(); I != 0; --I) {
2491 if (Path[I - 1].Base->isVirtual()) {
2492 Start = I - 1;
2493 break;
2494 }
2495 }
2496
2497 // Now add all bases.
2498 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002499 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002500}
2501
Douglas Gregor36d1b142009-10-06 17:59:45 +00002502/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2503/// conversion (where Derived and Base are class types) is
2504/// well-formed, meaning that the conversion is unambiguous (and
2505/// that all of the base classes are accessible). Returns true
2506/// and emits a diagnostic if the code is ill-formed, returns false
2507/// otherwise. Loc is the location where this routine should point to
2508/// if there is an error, and Range is the source range to highlight
2509/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002510///
2511/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2512/// diagnostic for the respective type of error will be suppressed, but the
2513/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002514bool
2515Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002516 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002517 unsigned AmbigiousBaseConvID,
2518 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002519 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002520 CXXCastPath *BasePath,
2521 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002522 // First, determine whether the path from Derived to Base is
2523 // ambiguous. This is slightly more expensive than checking whether
2524 // the Derived to Base conversion exists, because here we need to
2525 // explore multiple paths to determine if there is an ambiguity.
2526 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2527 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002528 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002529 assert(DerivationOkay &&
2530 "Can only be used with a derived-to-base conversion");
2531 (void)DerivationOkay;
2532
2533 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002534 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002535 // Check that the base class can be accessed.
2536 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2537 InaccessibleBaseID)) {
2538 case AR_inaccessible:
2539 return true;
2540 case AR_accessible:
2541 case AR_dependent:
2542 case AR_delayed:
2543 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002544 }
John McCall5b0829a2010-02-10 09:31:12 +00002545 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002546
2547 // Build a base path if necessary.
2548 if (BasePath)
2549 BuildBasePathArray(Paths, *BasePath);
2550 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002551 }
2552
David Majnemer626032f2013-06-22 06:43:58 +00002553 if (AmbigiousBaseConvID) {
2554 // We know that the derived-to-base conversion is ambiguous, and
2555 // we're going to produce a diagnostic. Perform the derived-to-base
2556 // search just one more time to compute all of the possible paths so
2557 // that we can print them out. This is more expensive than any of
2558 // the previous derived-to-base checks we've done, but at this point
2559 // performance isn't as much of an issue.
2560 Paths.clear();
2561 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002562 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002563 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2564 (void)StillOkay;
2565
2566 // Build up a textual representation of the ambiguous paths, e.g.,
2567 // D -> B -> A, that will be used to illustrate the ambiguous
2568 // conversions in the diagnostic. We only print one of the paths
2569 // to each base class subobject.
2570 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2571
2572 Diag(Loc, AmbigiousBaseConvID)
2573 << Derived << Base << PathDisplayStr << Range << Name;
2574 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002575 return true;
2576}
2577
2578bool
2579Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002580 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002581 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002582 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002583 return CheckDerivedToBaseConversion(
2584 Derived, Base, diag::err_upcast_to_inaccessible_base,
2585 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2586 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002587}
2588
2589
2590/// @brief Builds a string representing ambiguous paths from a
2591/// specific derived class to different subobjects of the same base
2592/// class.
2593///
2594/// This function builds a string that can be used in error messages
2595/// to show the different paths that one can take through the
2596/// inheritance hierarchy to go from the derived class to different
2597/// subobjects of a base class. The result looks something like this:
2598/// @code
2599/// struct D -> struct B -> struct A
2600/// struct D -> struct C -> struct A
2601/// @endcode
2602std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2603 std::string PathDisplayStr;
2604 std::set<unsigned> DisplayedPaths;
2605 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2606 Path != Paths.end(); ++Path) {
2607 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2608 // We haven't displayed a path to this particular base
2609 // class subobject yet.
2610 PathDisplayStr += "\n ";
2611 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2612 for (CXXBasePath::const_iterator Element = Path->begin();
2613 Element != Path->end(); ++Element)
2614 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2615 }
2616 }
2617
2618 return PathDisplayStr;
2619}
2620
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002621//===----------------------------------------------------------------------===//
2622// C++ class member Handling
2623//===----------------------------------------------------------------------===//
2624
Abramo Bagnarad7340582010-06-05 05:09:32 +00002625/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002626bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2627 SourceLocation ASLoc,
2628 SourceLocation ColonLoc,
2629 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002630 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002631 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002632 ASLoc, ColonLoc);
2633 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002634 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002635}
2636
Richard Smith18f07db2012-08-06 03:25:17 +00002637/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002638void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002639 if (D->isInvalidDecl())
2640 return;
2641
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002642 // We only care about "override" and "final" declarations.
2643 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2644 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002645
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002646 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002647
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002648 // We can't check dependent instance methods.
2649 if (MD && MD->isInstance() &&
2650 (MD->getParent()->hasAnyDependentBases() ||
2651 MD->getType()->isDependentType()))
2652 return;
2653
2654 if (MD && !MD->isVirtual()) {
2655 // If we have a non-virtual method, check if if hides a virtual method.
2656 // (In that case, it's most likely the method has the wrong type.)
2657 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2658 FindHiddenVirtualMethods(MD, OverloadedMethods);
2659
2660 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002661 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2662 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002663 diag::override_keyword_hides_virtual_member_function)
2664 << "override" << (OverloadedMethods.size() > 1);
2665 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002666 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002667 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002668 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2669 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002670 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002671 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2672 MD->setInvalidDecl();
2673 return;
2674 }
2675 // Fall through into the general case diagnostic.
2676 // FIXME: We might want to attempt typo correction here.
2677 }
2678
2679 if (!MD || !MD->isVirtual()) {
2680 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2681 Diag(OA->getLocation(),
2682 diag::override_keyword_only_allowed_on_virtual_member_functions)
2683 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2684 D->dropAttr<OverrideAttr>();
2685 }
2686 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2687 Diag(FA->getLocation(),
2688 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002689 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2690 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002691 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002692 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002693 return;
2694 }
Richard Smith18f07db2012-08-06 03:25:17 +00002695
Richard Smith18f07db2012-08-06 03:25:17 +00002696 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002697 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002698 // does not override a member function of a base class, the program is
2699 // ill-formed.
2700 bool HasOverriddenMethods =
2701 MD->begin_overridden_methods() != MD->end_overridden_methods();
2702 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2703 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2704 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002705}
2706
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002707void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2708 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2709 return;
2710 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2711 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2712 isa<CXXDestructorDecl>(MD))
2713 return;
2714
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002715 SourceLocation Loc = MD->getLocation();
2716 SourceLocation SpellingLoc = Loc;
2717 if (getSourceManager().isMacroArgExpansion(Loc))
2718 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2719 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2720 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002721 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002722
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002723 if (MD->size_overridden_methods() > 0) {
2724 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2725 << MD->getDeclName();
2726 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2727 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2728 }
2729}
2730
Richard Smith18f07db2012-08-06 03:25:17 +00002731/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002732/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002733/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002734bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2735 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002736 FinalAttr *FA = Old->getAttr<FinalAttr>();
2737 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002738 return false;
2739
2740 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002741 << New->getDeclName()
2742 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002743 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2744 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002745}
2746
Daniel Jasper0baec5492012-06-06 08:32:04 +00002747static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002748 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2749 // FIXME: Destruction of ObjC lifetime types has side-effects.
2750 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2751 return !RD->isCompleteDefinition() ||
2752 !RD->hasTrivialDefaultConstructor() ||
2753 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002754 return false;
2755}
2756
John McCall5e77d762013-04-16 07:28:30 +00002757static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002759 if (it->isDeclspecPropertyAttribute())
2760 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002761 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002762}
2763
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002764/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2765/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002766/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002767/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2768/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002769NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002770Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002771 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002772 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002773 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002774 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002775 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2776 DeclarationName Name = NameInfo.getName();
2777 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002778
2779 // For anonymous bitfields, the location should point to the type.
2780 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002781 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002782
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002783 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002784
John McCallb1cd7da2010-06-04 08:34:12 +00002785 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002786 assert(!DS.isFriendSpecified());
2787
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002788 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002789
John McCalldb632ac2012-09-25 07:32:39 +00002790 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2791 // The Microsoft extension __interface only permits public member functions
2792 // and prohibits constructors, destructors, operators, non-public member
2793 // functions, static methods and data members.
2794 unsigned InvalidDecl;
2795 bool ShowDeclName = true;
2796 if (!isFunc)
2797 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2798 else if (AS != AS_public)
2799 InvalidDecl = 2;
2800 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2801 InvalidDecl = 3;
2802 else switch (Name.getNameKind()) {
2803 case DeclarationName::CXXConstructorName:
2804 InvalidDecl = 4;
2805 ShowDeclName = false;
2806 break;
2807
2808 case DeclarationName::CXXDestructorName:
2809 InvalidDecl = 5;
2810 ShowDeclName = false;
2811 break;
2812
2813 case DeclarationName::CXXOperatorName:
2814 case DeclarationName::CXXConversionFunctionName:
2815 InvalidDecl = 6;
2816 break;
2817
2818 default:
2819 InvalidDecl = 0;
2820 break;
2821 }
2822
2823 if (InvalidDecl) {
2824 if (ShowDeclName)
2825 Diag(Loc, diag::err_invalid_member_in_interface)
2826 << (InvalidDecl-1) << Name;
2827 else
2828 Diag(Loc, diag::err_invalid_member_in_interface)
2829 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002831 }
2832 }
2833
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002834 // C++ 9.2p6: A member shall not be declared to have automatic storage
2835 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002836 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2837 // data members and cannot be applied to names declared const or static,
2838 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002839 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002840 case DeclSpec::SCS_unspecified:
2841 case DeclSpec::SCS_typedef:
2842 case DeclSpec::SCS_static:
2843 break;
2844 case DeclSpec::SCS_mutable:
2845 if (isFunc) {
2846 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002847
Richard Smithb4a9e862013-04-12 22:46:28 +00002848 // FIXME: It would be nicer if the keyword was ignored only for this
2849 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002850 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002851 }
2852 break;
2853 default:
2854 Diag(DS.getStorageClassSpecLoc(),
2855 diag::err_storageclass_invalid_for_member);
2856 D.getMutableDeclSpec().ClearStorageClassSpecs();
2857 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002858 }
2859
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002860 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2861 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002862 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002863
David Blaikie35506f82013-01-30 01:22:18 +00002864 if (DS.isConstexprSpecified() && isInstField) {
2865 SemaDiagnosticBuilder B =
2866 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2867 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2868 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002869 B << 0 << 0;
2870 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2871 B << FixItHint::CreateRemoval(ConstexprLoc);
2872 else {
2873 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2874 D.getMutableDeclSpec().ClearConstexprSpec();
2875 const char *PrevSpec;
2876 unsigned DiagID;
2877 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2878 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2879 (void)Failed;
2880 assert(!Failed && "Making a constexpr member const shouldn't fail");
2881 }
David Blaikie35506f82013-01-30 01:22:18 +00002882 } else {
2883 B << 1;
2884 const char *PrevSpec;
2885 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002886 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002887 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2888 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002889 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002890 "This is the only DeclSpec that should fail to be applied");
2891 B << 1;
2892 } else {
2893 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2894 isInstField = false;
2895 }
2896 }
2897 }
2898
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002899 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002900 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002901 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002902
2903 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002904 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002905 Diag(Loc, diag::err_bad_variable_name)
2906 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002907 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002908 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002909
Benjamin Kramer365082d2012-05-19 16:34:46 +00002910 IdentifierInfo *II = Name.getAsIdentifierInfo();
2911
Douglas Gregor7c26c042011-09-21 14:40:46 +00002912 // Member field could not be with "template" keyword.
2913 // So TemplateParameterLists should be empty in this case.
2914 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002915 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002916 if (TemplateParams->size()) {
2917 // There is no such thing as a member field template.
2918 Diag(D.getIdentifierLoc(), diag::err_template_member)
2919 << II
2920 << SourceRange(TemplateParams->getTemplateLoc(),
2921 TemplateParams->getRAngleLoc());
2922 } else {
2923 // There is an extraneous 'template<>' for this member.
2924 Diag(TemplateParams->getTemplateLoc(),
2925 diag::err_template_member_noparams)
2926 << II
2927 << SourceRange(TemplateParams->getTemplateLoc(),
2928 TemplateParams->getRAngleLoc());
2929 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002930 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002931 }
2932
Douglas Gregora007d362010-10-13 22:19:53 +00002933 if (SS.isSet() && !SS.isInvalid()) {
2934 // The user provided a superfluous scope specifier inside a class
2935 // definition:
2936 //
2937 // class X {
2938 // int X::member;
2939 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002940 if (DeclContext *DC = computeDeclContext(SS, false))
2941 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002942 else
2943 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2944 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002945
Douglas Gregora007d362010-10-13 22:19:53 +00002946 SS.clear();
2947 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002948
John McCall5e77d762013-04-16 07:28:30 +00002949 AttributeList *MSPropertyAttr =
2950 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002951 if (MSPropertyAttr) {
2952 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2953 BitWidth, InitStyle, AS, MSPropertyAttr);
2954 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002955 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002956 isInstField = false;
2957 } else {
2958 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2959 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00002960 if (!Member)
2961 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002962 }
2963 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002964 Member = HandleDeclarator(S, D, TemplateParameterLists);
2965 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002966 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002967
2968 // Non-instance-fields can't have a bitfield.
2969 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002970 if (Member->isInvalidDecl()) {
2971 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002972 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002973 // C++ 9.6p3: A bit-field shall not be a static member.
2974 // "static member 'A' cannot be a bit-field"
2975 Diag(Loc, diag::err_static_not_bitfield)
2976 << Name << BitWidth->getSourceRange();
2977 } else if (isa<TypedefDecl>(Member)) {
2978 // "typedef member 'x' cannot be a bit-field"
2979 Diag(Loc, diag::err_typedef_not_bitfield)
2980 << Name << BitWidth->getSourceRange();
2981 } else {
2982 // A function typedef ("typedef int f(); f a;").
2983 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2984 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002985 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002986 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988
Craig Topperc3ec1492014-05-26 06:22:03 +00002989 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002990 Member->setInvalidDecl();
2991 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002992
2993 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002994
Larisse Voufo39a1e502013-08-06 01:03:05 +00002995 // If we have declared a member function template or static data member
2996 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002997 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2998 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002999 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3000 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003001 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003002
Richard Smith18f07db2012-08-06 03:25:17 +00003003 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003004 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003005 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003006 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3007 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003008
Douglas Gregorf2f08062011-03-08 17:10:18 +00003009 if (VS.getLastLocation().isValid()) {
3010 // Update the end location of a method that has a virt-specifiers.
3011 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3012 MD->setRangeEnd(VS.getLastLocation());
3013 }
Richard Smith18f07db2012-08-06 03:25:17 +00003014
Anders Carlssonc87f8612011-01-20 06:29:02 +00003015 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003016
Douglas Gregor92751d42008-11-17 22:58:34 +00003017 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003018
Daniel Jasper0baec5492012-06-06 08:32:04 +00003019 if (isInstField) {
3020 FieldDecl *FD = cast<FieldDecl>(Member);
3021 FieldCollector->Add(FD);
3022
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003023 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003024 // Remember all explicit private FieldDecls that have a name, no side
3025 // effects and are not part of a dependent type declaration.
3026 if (!FD->isImplicit() && FD->getDeclName() &&
3027 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003028 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003029 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003030 !InitializationHasSideEffects(*FD))
3031 UnusedPrivateFields.insert(FD);
3032 }
3033 }
3034
John McCall48871652010-08-21 09:40:31 +00003035 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003036}
3037
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003038namespace {
3039 class UninitializedFieldVisitor
3040 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3041 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003042 // List of Decls to generate a warning on. Also remove Decls that become
3043 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003044 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003045 // List of base classes of the record. Classes are removed after their
3046 // initializers.
3047 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003048 // Vector of decls to be removed from the Decl set prior to visiting the
3049 // nodes. These Decls may have been initialized in the prior initializer.
3050 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003051 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003052 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003053 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003054 // InitList is true, special case initialization of FieldDecls matching
3055 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003056 bool InitList;
3057 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003058 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3059
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003060 public:
3061 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003062 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003063 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3064 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3065 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3066 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003067
Richard Trieufa1d0a72014-10-17 20:56:10 +00003068 // Returns true if the use of ME is not an uninitialized use.
3069 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3070 bool CheckReferenceOnly) {
3071 llvm::SmallVector<FieldDecl*, 4> Fields;
3072 bool ReferenceField = false;
3073 while (ME) {
3074 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3075 if (!FD)
3076 return false;
3077 Fields.push_back(FD);
3078 if (FD->getType()->isReferenceType())
3079 ReferenceField = true;
3080 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3081 }
3082
3083 // Binding a reference to an unintialized field is not an
3084 // uninitialized use.
3085 if (CheckReferenceOnly && !ReferenceField)
3086 return true;
3087
3088 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3089 // Discard the first field since it is the field decl that is being
3090 // initialized.
3091 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3092 UsedFieldIndex.push_back((*I)->getFieldIndex());
3093 }
3094
3095 for (auto UsedIter = UsedFieldIndex.begin(),
3096 UsedEnd = UsedFieldIndex.end(),
3097 OrigIter = InitFieldIndex.begin(),
3098 OrigEnd = InitFieldIndex.end();
3099 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3100 if (*UsedIter < *OrigIter)
3101 return true;
3102 if (*UsedIter > *OrigIter)
3103 break;
3104 }
3105
3106 return false;
3107 }
3108
Richard Trieu2d779b92014-10-01 03:44:58 +00003109 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3110 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003111 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3112 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003113
Richard Trieu1bc22c12013-09-13 03:20:53 +00003114 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3115 // or union.
3116 MemberExpr *FieldME = ME;
3117
Richard Trieu2d779b92014-10-01 03:44:58 +00003118 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3119
Richard Trieu1bc22c12013-09-13 03:20:53 +00003120 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003121 while (MemberExpr *SubME =
3122 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003123
Richard Trieufa1d0a72014-10-17 20:56:10 +00003124 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003125 return;
3126
Richard Trieufa1d0a72014-10-17 20:56:10 +00003127 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003128 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003129 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003130
Richard Trieu2d779b92014-10-01 03:44:58 +00003131 if (!FieldME->getType().isPODType(S.Context))
3132 AllPODFields = false;
3133
Richard Trieu3630c392014-11-21 03:10:30 +00003134 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003135 }
3136
Richard Trieu3630c392014-11-21 03:10:30 +00003137 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003138 return;
3139
Richard Trieu2d779b92014-10-01 03:44:58 +00003140 if (AddressOf && AllPODFields)
3141 return;
3142
Richard Trieu406e65c2013-09-20 03:03:06 +00003143 ValueDecl* FoundVD = FieldME->getMemberDecl();
3144
Richard Trieu3630c392014-11-21 03:10:30 +00003145 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3146 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3147 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3148 }
3149
3150 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3151 QualType T = BaseCast->getType();
3152 if (T->isPointerType() &&
3153 BaseClasses.count(T->getPointeeType())) {
3154 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3155 << T->getPointeeType() << FoundVD;
3156 }
3157 }
3158 }
3159
Richard Trieuef64e942013-10-25 00:56:00 +00003160 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003161 return;
3162
Richard Trieuef64e942013-10-25 00:56:00 +00003163 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003164
Richard Trieufa1d0a72014-10-17 20:56:10 +00003165 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3166 // Special checking for initializer lists.
3167 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3168 return;
3169 }
3170 } else {
3171 // Prevent double warnings on use of unbounded references.
3172 if (CheckReferenceOnly && !IsReference)
3173 return;
3174 }
Richard Trieuef64e942013-10-25 00:56:00 +00003175
3176 unsigned diag = IsReference
3177 ? diag::warn_reference_field_is_uninit
3178 : diag::warn_field_is_uninit;
3179 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3180 if (Constructor)
3181 S.Diag(Constructor->getLocation(),
3182 diag::note_uninit_in_this_constructor)
3183 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3184
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003185 }
3186
Richard Trieu2d779b92014-10-01 03:44:58 +00003187 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003188 E = E->IgnoreParens();
3189
3190 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003191 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3192 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003193 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003194 }
3195
3196 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003197 Visit(CO->getCond());
3198 HandleValue(CO->getTrueExpr(), AddressOf);
3199 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003200 return;
3201 }
3202
3203 if (BinaryConditionalOperator *BCO =
3204 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003205 Visit(BCO->getCond());
3206 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003207 return;
3208 }
3209
Richard Trieuabf6ec42014-08-27 22:15:10 +00003210 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003211 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003212 return;
3213 }
3214
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3216 switch (BO->getOpcode()) {
3217 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003218 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003219 case(BO_PtrMemD):
3220 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003221 HandleValue(BO->getLHS(), AddressOf);
3222 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003223 return;
3224 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003225 Visit(BO->getLHS());
3226 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003227 return;
3228 }
3229 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003230
3231 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003232 }
3233
Richard Trieufa1d0a72014-10-17 20:56:10 +00003234 void CheckInitListExpr(InitListExpr *ILE) {
3235 InitFieldIndex.push_back(0);
3236 for (auto Child : ILE->children()) {
3237 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3238 CheckInitListExpr(SubList);
3239 } else {
3240 Visit(Child);
3241 }
3242 ++InitFieldIndex.back();
3243 }
3244 InitFieldIndex.pop_back();
3245 }
3246
Richard Trieu8d08a272014-08-28 03:23:47 +00003247 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003248 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003249 // Remove Decls that may have been initialized in the previous
3250 // initializer.
3251 for (ValueDecl* VD : DeclsToRemove)
3252 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003253 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003254
Richard Trieu8d08a272014-08-28 03:23:47 +00003255 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003256 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3257
3258 if (ILE && Field) {
3259 InitList = true;
3260 InitListFieldDecl = Field;
3261 InitFieldIndex.clear();
3262 CheckInitListExpr(ILE);
3263 } else {
3264 InitList = false;
3265 Visit(E);
3266 }
3267
Richard Trieu8d08a272014-08-28 03:23:47 +00003268 if (Field)
3269 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003270 if (BaseClass)
3271 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003272 }
3273
Richard Trieu1bc22c12013-09-13 03:20:53 +00003274 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003275 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003276 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003277 }
3278
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003279 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003280 if (E->getCastKind() == CK_LValueToRValue) {
3281 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3282 return;
3283 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003284
3285 Inherited::VisitImplicitCastExpr(E);
3286 }
3287
Richard Trieu1bc22c12013-09-13 03:20:53 +00003288 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003289 if (E->getConstructor()->isCopyConstructor()) {
3290 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003291 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3292 if (ILE->getNumInits() == 1)
3293 ArgExpr = ILE->getInit(0);
3294 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3295 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003296 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003297 HandleValue(ArgExpr, false /*AddressOf*/);
3298 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003299 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003300 Inherited::VisitCXXConstructExpr(E);
3301 }
3302
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003303 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3304 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003305 if (isa<MemberExpr>(Callee)) {
3306 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003307 for (auto Arg : E->arguments())
3308 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003309 return;
3310 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003311
3312 Inherited::VisitCXXMemberCallExpr(E);
3313 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003314
Richard Trieu11fd0792014-08-26 04:30:55 +00003315 void VisitCallExpr(CallExpr *E) {
3316 // Treat std::move as a use.
3317 if (E->getNumArgs() == 1) {
3318 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003319 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3320 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003321 HandleValue(E->getArg(0), false /*AddressOf*/);
3322 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003323 }
3324 }
3325 }
3326
3327 Inherited::VisitCallExpr(E);
3328 }
3329
Richard Trieud4a01362014-10-31 21:10:22 +00003330 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3331 Expr *Callee = E->getCallee();
3332
3333 if (isa<UnresolvedLookupExpr>(Callee))
3334 return Inherited::VisitCXXOperatorCallExpr(E);
3335
3336 Visit(Callee);
3337 for (auto Arg : E->arguments())
3338 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3339 }
3340
Richard Trieu406e65c2013-09-20 03:03:06 +00003341 void VisitBinaryOperator(BinaryOperator *E) {
3342 // If a field assignment is detected, remove the field from the
3343 // uninitiailized field set.
3344 if (E->getOpcode() == BO_Assign)
3345 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3346 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003347 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003348 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003349
Richard Trieu52b8b602014-09-25 01:15:40 +00003350 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003351 HandleValue(E->getLHS(), false /*AddressOf*/);
3352 Visit(E->getRHS());
3353 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003354 }
3355
Richard Trieu406e65c2013-09-20 03:03:06 +00003356 Inherited::VisitBinaryOperator(E);
3357 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003358
3359 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003360 if (E->isIncrementDecrementOp()) {
3361 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3362 return;
3363 }
3364 if (E->getOpcode() == UO_AddrOf) {
3365 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3366 HandleValue(ME->getBase(), true /*AddressOf*/);
3367 return;
3368 }
3369 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003370
3371 Inherited::VisitUnaryOperator(E);
3372 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003373 };
Richard Trieuef64e942013-10-25 00:56:00 +00003374
3375 // Diagnose value-uses of fields to initialize themselves, e.g.
3376 // foo(foo)
3377 // where foo is not also a parameter to the constructor.
3378 // Also diagnose across field uninitialized use such as
3379 // x(y), y(x)
3380 // TODO: implement -Wuninitialized and fold this into that framework.
3381 static void DiagnoseUninitializedFields(
3382 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3383
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003384 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3385 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003386 return;
3387 }
3388
3389 if (Constructor->isInvalidDecl())
3390 return;
3391
3392 const CXXRecordDecl *RD = Constructor->getParent();
3393
Richard Trieu353a4b42014-10-22 05:21:59 +00003394 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003395 return;
3396
Richard Trieuef64e942013-10-25 00:56:00 +00003397 // Holds fields that are uninitialized.
3398 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3399
3400 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003401 for (auto *I : RD->decls()) {
3402 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003403 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003404 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003405 UninitializedFields.insert(IFD->getAnonField());
3406 }
3407 }
3408
Richard Trieu3630c392014-11-21 03:10:30 +00003409 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3410 for (auto I : RD->bases())
3411 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3412
3413 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003414 return;
3415
3416 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003417 UninitializedFields,
3418 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003419
Aaron Ballman0ad78302014-03-13 17:34:31 +00003420 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003421 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003422 break;
3423
Aaron Ballman0ad78302014-03-13 17:34:31 +00003424 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003425 if (!InitExpr)
3426 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003427
Richard Trieu8d08a272014-08-28 03:23:47 +00003428 if (CXXDefaultInitExpr *Default =
3429 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3430 InitExpr = Default->getExpr();
3431 if (!InitExpr)
3432 continue;
3433 // In class initializers will point to the constructor.
3434 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003435 FieldInit->getAnyMember(),
3436 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003437 } else {
3438 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003439 FieldInit->getAnyMember(),
3440 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003441 }
Richard Trieuef64e942013-10-25 00:56:00 +00003442 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003443 }
3444} // namespace
3445
Richard Smith74108172014-01-17 03:11:34 +00003446/// \brief Enter a new C++ default initializer scope. After calling this, the
3447/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3448/// parsing or instantiating the initializer failed.
3449void Sema::ActOnStartCXXInClassMemberInitializer() {
3450 // Create a synthetic function scope to represent the call to the constructor
3451 // that notionally surrounds a use of this initializer.
3452 PushFunctionScope();
3453}
3454
3455/// \brief This is invoked after parsing an in-class initializer for a
3456/// non-static C++ class member, and after instantiating an in-class initializer
3457/// in a class template. Such actions are deferred until the class is complete.
3458void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3459 SourceLocation InitLoc,
3460 Expr *InitExpr) {
3461 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003462 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003463
David Majnemer87ff66c2014-12-13 11:34:16 +00003464 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3465 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003466 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003467
3468 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003469 D->setInvalidDecl();
3470 if (FD)
3471 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003472 return;
3473 }
3474
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003475 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3476 FD->setInvalidDecl();
3477 FD->removeInClassInitializer();
3478 return;
3479 }
3480
Richard Smith938f40b2011-06-11 17:19:42 +00003481 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003482 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003483 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003484 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003485 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003486 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003487 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3488 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003489 if (Init.isInvalid()) {
3490 FD->setInvalidDecl();
3491 return;
3492 }
Richard Smith938f40b2011-06-11 17:19:42 +00003493 }
3494
Richard Smith945f8d32013-01-14 22:39:08 +00003495 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003496 // The initialization of each base and member constitutes a
3497 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003498 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003499 if (Init.isInvalid()) {
3500 FD->setInvalidDecl();
3501 return;
3502 }
3503
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003504 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003505
3506 FD->setInClassInitializer(InitExpr);
3507}
3508
Douglas Gregor15e77a22009-12-31 09:10:24 +00003509/// \brief Find the direct and/or virtual base specifiers that
3510/// correspond to the given base type, for use in base initialization
3511/// within a constructor.
3512static bool FindBaseInitializer(Sema &SemaRef,
3513 CXXRecordDecl *ClassDecl,
3514 QualType BaseType,
3515 const CXXBaseSpecifier *&DirectBaseSpec,
3516 const CXXBaseSpecifier *&VirtualBaseSpec) {
3517 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003518 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003519 for (const auto &Base : ClassDecl->bases()) {
3520 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003521 // We found a direct base of this type. That's what we're
3522 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003523 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003524 break;
3525 }
3526 }
3527
3528 // Check for a virtual base class.
3529 // FIXME: We might be able to short-circuit this if we know in advance that
3530 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003531 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003532 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3533 // We haven't found a base yet; search the class hierarchy for a
3534 // virtual base class.
3535 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3536 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003537 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3538 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003539 BaseType, Paths)) {
3540 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3541 Path != Paths.end(); ++Path) {
3542 if (Path->back().Base->isVirtual()) {
3543 VirtualBaseSpec = Path->back().Base;
3544 break;
3545 }
3546 }
3547 }
3548 }
3549
3550 return DirectBaseSpec || VirtualBaseSpec;
3551}
3552
Sebastian Redla74948d2011-09-24 17:48:25 +00003553/// \brief Handle a C++ member initializer using braced-init-list syntax.
3554MemInitResult
3555Sema::ActOnMemInitializer(Decl *ConstructorD,
3556 Scope *S,
3557 CXXScopeSpec &SS,
3558 IdentifierInfo *MemberOrBase,
3559 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003560 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003561 SourceLocation IdLoc,
3562 Expr *InitList,
3563 SourceLocation EllipsisLoc) {
3564 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003565 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003566 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003567}
3568
3569/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003570MemInitResult
John McCall48871652010-08-21 09:40:31 +00003571Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003572 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003573 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003574 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003575 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003576 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003577 SourceLocation IdLoc,
3578 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003579 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003580 SourceLocation RParenLoc,
3581 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003582 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003583 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003584 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003585 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003586}
3587
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003588namespace {
3589
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003590// Callback to only accept typo corrections that can be a valid C++ member
3591// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003592class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003593public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003594 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3595 : ClassDecl(ClassDecl) {}
3596
Craig Toppera798a9d2014-03-02 09:32:10 +00003597 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003598 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3599 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3600 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003601 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003602 }
3603 return false;
3604 }
3605
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003606private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003607 CXXRecordDecl *ClassDecl;
3608};
3609
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003610}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003611
Sebastian Redla74948d2011-09-24 17:48:25 +00003612/// \brief Handle a C++ member initializer.
3613MemInitResult
3614Sema::BuildMemInitializer(Decl *ConstructorD,
3615 Scope *S,
3616 CXXScopeSpec &SS,
3617 IdentifierInfo *MemberOrBase,
3618 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003619 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003620 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003621 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003622 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003623 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3624 if (!Res.isUsable())
3625 return true;
3626 Init = Res.get();
3627
Douglas Gregor71a57182009-06-22 23:20:33 +00003628 if (!ConstructorD)
3629 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003630
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003631 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003632
3633 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003634 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003635 if (!Constructor) {
3636 // The user wrote a constructor initializer on a function that is
3637 // not a C++ constructor. Ignore the error for now, because we may
3638 // have more member initializers coming; we'll diagnose it just
3639 // once in ActOnMemInitializers.
3640 return true;
3641 }
3642
3643 CXXRecordDecl *ClassDecl = Constructor->getParent();
3644
3645 // C++ [class.base.init]p2:
3646 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003647 // constructor's class and, if not found in that scope, are looked
3648 // up in the scope containing the constructor's definition.
3649 // [Note: if the constructor's class contains a member with the
3650 // same name as a direct or virtual base class of the class, a
3651 // mem-initializer-id naming the member or base class and composed
3652 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003653 // mem-initializer-id for the hidden base class may be specified
3654 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003655 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003656 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003657 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003658 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003659 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003660 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3661 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003662 if (EllipsisLoc.isValid())
3663 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003664 << MemberOrBase
3665 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003666
Sebastian Redla9351792012-02-11 23:51:47 +00003667 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003668 }
Francois Pichetd583da02010-12-04 09:14:42 +00003669 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003670 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003671 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003672 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003673 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003674
3675 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003676 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003677 } else if (DS.getTypeSpecType() == TST_decltype) {
3678 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00003679 } else {
3680 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3681 LookupParsedName(R, S, &SS);
3682
3683 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3684 if (!TyD) {
3685 if (R.isAmbiguous()) return true;
3686
John McCallda6841b2010-04-09 19:01:14 +00003687 // We don't want access-control diagnostics here.
3688 R.suppressDiagnostics();
3689
Douglas Gregora3b624a2010-01-19 06:46:48 +00003690 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3691 bool NotUnknownSpecialization = false;
3692 DeclContext *DC = computeDeclContext(SS, false);
3693 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3694 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3695
3696 if (!NotUnknownSpecialization) {
3697 // When the scope specifier can refer to a member of an unknown
3698 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003699 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3700 SS.getWithLocInContext(Context),
3701 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003702 if (BaseType.isNull())
3703 return true;
3704
Douglas Gregora3b624a2010-01-19 06:46:48 +00003705 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003706 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003707 }
3708 }
3709
Douglas Gregor15e77a22009-12-31 09:10:24 +00003710 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003711 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003712 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003713 (Corr = CorrectTypo(
3714 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3715 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3716 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003717 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003718 // We have found a non-static data member with a similar
3719 // name to what was typed; complain and initialize that
3720 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003721 diagnoseTypo(Corr,
3722 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3723 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003724 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003725 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003726 const CXXBaseSpecifier *DirectBaseSpec;
3727 const CXXBaseSpecifier *VirtualBaseSpec;
3728 if (FindBaseInitializer(*this, ClassDecl,
3729 Context.getTypeDeclType(Type),
3730 DirectBaseSpec, VirtualBaseSpec)) {
3731 // We have found a direct or virtual base class with a
3732 // similar name to what was typed; complain and initialize
3733 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003734 diagnoseTypo(Corr,
3735 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3736 << MemberOrBase << false,
3737 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003738
Richard Smithf9b15102013-08-17 00:46:16 +00003739 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3740 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003741 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003742 diag::note_base_class_specified_here)
3743 << BaseSpec->getType()
3744 << BaseSpec->getSourceRange();
3745
Douglas Gregor15e77a22009-12-31 09:10:24 +00003746 TyD = Type;
3747 }
3748 }
3749 }
3750
Douglas Gregora3b624a2010-01-19 06:46:48 +00003751 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003752 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003753 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003754 return true;
3755 }
John McCallb5a0d312009-12-21 10:41:20 +00003756 }
3757
Douglas Gregora3b624a2010-01-19 06:46:48 +00003758 if (BaseType.isNull()) {
3759 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003760 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003761 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003762 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3763 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003764 TInfo = Context.CreateTypeSourceInfo(BaseType);
3765 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3766 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3767 TL.setElaboratedKeywordLoc(SourceLocation());
3768 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3769 }
John McCallb5a0d312009-12-21 10:41:20 +00003770 }
3771 }
Mike Stump11289f42009-09-09 15:08:12 +00003772
John McCallbcd03502009-12-07 02:54:59 +00003773 if (!TInfo)
3774 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003775
Sebastian Redla9351792012-02-11 23:51:47 +00003776 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003777}
3778
Chandler Carruth599deef2011-09-03 01:14:15 +00003779/// Checks a member initializer expression for cases where reference (or
3780/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003781static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3782 Expr *Init,
3783 SourceLocation IdLoc) {
3784 QualType MemberTy = Member->getType();
3785
3786 // We only handle pointers and references currently.
3787 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3788 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3789 return;
3790
3791 const bool IsPointer = MemberTy->isPointerType();
3792 if (IsPointer) {
3793 if (const UnaryOperator *Op
3794 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3795 // The only case we're worried about with pointers requires taking the
3796 // address.
3797 if (Op->getOpcode() != UO_AddrOf)
3798 return;
3799
3800 Init = Op->getSubExpr();
3801 } else {
3802 // We only handle address-of expression initializers for pointers.
3803 return;
3804 }
3805 }
3806
Richard Smithe3b28bc2013-06-12 21:51:50 +00003807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003808 // We only warn when referring to a non-reference parameter declaration.
3809 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3810 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003811 return;
3812
3813 S.Diag(Init->getExprLoc(),
3814 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3815 : diag::warn_bind_ref_member_to_parameter)
3816 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003817 } else {
3818 // Other initializers are fine.
3819 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003820 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003821
3822 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3823 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003824}
3825
John McCallfaf5fb42010-08-26 23:41:50 +00003826MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003827Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003828 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003829 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3830 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3831 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003832 "Member must be a FieldDecl or IndirectFieldDecl");
3833
Sebastian Redla9351792012-02-11 23:51:47 +00003834 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003835 return true;
3836
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003837 if (Member->isInvalidDecl())
3838 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003839
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003840 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003841 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003842 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003843 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003844 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003845 } else {
3846 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003847 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003848 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003849
Sebastian Redla9351792012-02-11 23:51:47 +00003850 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003851
Sebastian Redla9351792012-02-11 23:51:47 +00003852 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003853 // Can't check initialization for a member of dependent type or when
3854 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003855 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003856 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003857 bool InitList = false;
3858 if (isa<InitListExpr>(Init)) {
3859 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003860 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003861 }
3862
Chandler Carruthd44c3102010-12-06 09:23:57 +00003863 // Initialize the member.
3864 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003865 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3866 : InitializedEntity::InitializeMember(IndirectMember,
3867 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003868 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003869 InitList ? InitializationKind::CreateDirectList(IdLoc)
3870 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3871 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003872
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003873 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003874 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3875 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003876 if (MemberInit.isInvalid())
3877 return true;
3878
Richard Smith736a9472013-06-12 20:42:33 +00003879 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3880
Richard Smith945f8d32013-01-14 22:39:08 +00003881 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003882 // The initialization of each base and member constitutes a
3883 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003884 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003885 if (MemberInit.isInvalid())
3886 return true;
3887
Richard Smithd59b8322012-12-19 01:39:02 +00003888 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003889 }
3890
Chandler Carruthd44c3102010-12-06 09:23:57 +00003891 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003892 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3893 InitRange.getBegin(), Init,
3894 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003895 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003896 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3897 InitRange.getBegin(), Init,
3898 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003899 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003900}
3901
John McCallfaf5fb42010-08-26 23:41:50 +00003902MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003903Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003904 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003905 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003906 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003907 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003908 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003909 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003910
Sebastian Redl0501c632012-02-12 16:37:36 +00003911 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003912 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003913 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3914 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003915 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003916 }
3917
Sebastian Redla9351792012-02-11 23:51:47 +00003918 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003919 // Initialize the object.
3920 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3921 QualType(ClassDecl->getTypeForDecl(), 0));
3922 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003923 InitList ? InitializationKind::CreateDirectList(NameLoc)
3924 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3925 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003926 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003927 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003928 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003929 if (DelegationInit.isInvalid())
3930 return true;
3931
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003932 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3933 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003934
Richard Smith945f8d32013-01-14 22:39:08 +00003935 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003936 // The initialization of each base and member constitutes a
3937 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003938 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3939 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003940 if (DelegationInit.isInvalid())
3941 return true;
3942
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003943 // If we are in a dependent context, template instantiation will
3944 // perform this type-checking again. Just save the arguments that we
3945 // received in a ParenListExpr.
3946 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3947 // of the information that we have about the base
3948 // initializer. However, deconstructing the ASTs is a dicey process,
3949 // and this approach is far more likely to get the corner cases right.
3950 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003951 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003952
Sebastian Redla9351792012-02-11 23:51:47 +00003953 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003954 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003955 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003956}
3957
3958MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003959Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003960 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003961 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003962 SourceLocation BaseLoc
3963 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003964
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003965 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3966 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3967 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3968
3969 // C++ [class.base.init]p2:
3970 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003971 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003972 // of that class, the mem-initializer is ill-formed. A
3973 // mem-initializer-list can initialize a base class using any
3974 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003975 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003976
Sebastian Redla9351792012-02-11 23:51:47 +00003977 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003978 if (EllipsisLoc.isValid()) {
3979 // This is a pack expansion.
3980 if (!BaseType->containsUnexpandedParameterPack()) {
3981 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003982 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003983
Douglas Gregor44e7df62011-01-04 00:32:56 +00003984 EllipsisLoc = SourceLocation();
3985 }
3986 } else {
3987 // Check for any unexpanded parameter packs.
3988 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3989 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003990
Sebastian Redla9351792012-02-11 23:51:47 +00003991 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003992 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003993 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003994
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003995 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003996 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3997 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003998 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003999 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4000 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004001 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004002
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004003 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4004 VirtualBaseSpec);
4005
4006 // C++ [base.class.init]p2:
4007 // Unless the mem-initializer-id names a nonstatic data member of the
4008 // constructor's class or a direct or virtual base of that class, the
4009 // mem-initializer is ill-formed.
4010 if (!DirectBaseSpec && !VirtualBaseSpec) {
4011 // If the class has any dependent bases, then it's possible that
4012 // one of those types will resolve to the same type as
4013 // BaseType. Therefore, just treat this as a dependent base
4014 // class initialization. FIXME: Should we try to check the
4015 // initialization anyway? It seems odd.
4016 if (ClassDecl->hasAnyDependentBases())
4017 Dependent = true;
4018 else
4019 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4020 << BaseType << Context.getTypeDeclType(ClassDecl)
4021 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4022 }
4023 }
4024
4025 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004026 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004027
Sebastian Redla74948d2011-09-24 17:48:25 +00004028 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4029 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004030 InitRange.getBegin(), Init,
4031 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004032 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004033
4034 // C++ [base.class.init]p2:
4035 // If a mem-initializer-id is ambiguous because it designates both
4036 // a direct non-virtual base class and an inherited virtual base
4037 // class, the mem-initializer is ill-formed.
4038 if (DirectBaseSpec && VirtualBaseSpec)
4039 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004040 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004041
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004042 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004043 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004044 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004045
4046 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004047 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004048 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004049 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004050 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004051 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004052 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004053
4054 InitializedEntity BaseEntity =
4055 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4056 InitializationKind Kind =
4057 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4058 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4059 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004060 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004061 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004062 if (BaseInit.isInvalid())
4063 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004064
Richard Smith945f8d32013-01-14 22:39:08 +00004065 // C++11 [class.base.init]p7:
4066 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004067 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004068 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004069 if (BaseInit.isInvalid())
4070 return true;
4071
4072 // If we are in a dependent context, template instantiation will
4073 // perform this type-checking again. Just save the arguments that we
4074 // received in a ParenListExpr.
4075 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4076 // of the information that we have about the base
4077 // initializer. However, deconstructing the ASTs is a dicey process,
4078 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004079 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004080 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004081
Alexis Hunt1d792652011-01-08 20:30:50 +00004082 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004083 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004084 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004085 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004086 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004087}
4088
Sebastian Redl22653ba2011-08-30 19:58:05 +00004089// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004090static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4091 if (T.isNull()) T = E->getType();
4092 QualType TargetType = SemaRef.BuildReferenceType(
4093 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004094 SourceLocation ExprLoc = E->getLocStart();
4095 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4096 TargetType, ExprLoc);
4097
4098 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4099 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004100 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004101}
4102
Anders Carlsson1b00e242010-04-23 03:10:23 +00004103/// ImplicitInitializerKind - How an implicit base or member initializer should
4104/// initialize its base or member.
4105enum ImplicitInitializerKind {
4106 IIK_Default,
4107 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004108 IIK_Move,
4109 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004110};
4111
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004112static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004113BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004114 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004115 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004116 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004117 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004118 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004119 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4120 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004121
John McCalldadc5752010-08-24 06:29:42 +00004122 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004123
4124 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004125 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004126 case IIK_Default: {
4127 InitializationKind InitKind
4128 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004129 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4130 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004131 break;
4132 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004133
Sebastian Redl22653ba2011-08-30 19:58:05 +00004134 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004135 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004136 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004137 ParmVarDecl *Param = Constructor->getParamDecl(0);
4138 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004139
Anders Carlsson1b00e242010-04-23 03:10:23 +00004140 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004141 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004142 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004143 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004144 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004145
Eli Friedmanfa0df832012-02-02 03:46:19 +00004146 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4147
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004148 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004149 QualType ArgTy =
4150 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4151 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004152
Sebastian Redl22653ba2011-08-30 19:58:05 +00004153 if (Moving) {
4154 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4155 }
4156
John McCallcf142162010-08-07 06:22:56 +00004157 CXXCastPath BasePath;
4158 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004159 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4160 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004161 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004162 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004163
Anders Carlsson1b00e242010-04-23 03:10:23 +00004164 InitializationKind InitKind
4165 = InitializationKind::CreateDirect(Constructor->getLocation(),
4166 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004167 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4168 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004169 break;
4170 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004171 }
John McCallb268a282010-08-23 23:25:46 +00004172
Douglas Gregora40433a2010-12-07 00:41:46 +00004173 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004174 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004175 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004176
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004177 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004178 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004179 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4180 SourceLocation()),
4181 BaseSpec->isVirtual(),
4182 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004183 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004184 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004185 SourceLocation());
4186
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004187 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004188}
4189
Sebastian Redl22653ba2011-08-30 19:58:05 +00004190static bool RefersToRValueRef(Expr *MemRef) {
4191 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4192 return Referenced->getType()->isRValueReferenceType();
4193}
4194
Anders Carlsson3c1db572010-04-23 02:15:47 +00004195static bool
4196BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004197 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004198 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004199 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004200 if (Field->isInvalidDecl())
4201 return true;
4202
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004203 SourceLocation Loc = Constructor->getLocation();
4204
Sebastian Redl22653ba2011-08-30 19:58:05 +00004205 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4206 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004207 ParmVarDecl *Param = Constructor->getParamDecl(0);
4208 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004209
4210 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004211 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4212 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004213
Anders Carlsson423f5d82010-04-23 16:04:08 +00004214 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004215 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004216 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004217 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004218
Eli Friedmanfa0df832012-02-02 03:46:19 +00004219 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4220
Sebastian Redl22653ba2011-08-30 19:58:05 +00004221 if (Moving) {
4222 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4223 }
4224
Douglas Gregor94f9a482010-05-05 05:51:00 +00004225 // Build a reference to this field within the parameter.
4226 CXXScopeSpec SS;
4227 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4228 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004229 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4230 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004231 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004232 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004233 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004234 ParamType, Loc,
4235 /*IsArrow=*/false,
4236 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004237 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004238 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004239 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004240 /*TemplateArgs=*/nullptr,
4241 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004242 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004243 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004244
4245 // C++11 [class.copy]p15:
4246 // - if a member m has rvalue reference type T&&, it is direct-initialized
4247 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004248 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004249 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004250 }
4251
Douglas Gregor94f9a482010-05-05 05:51:00 +00004252 // When the field we are copying is an array, create index variables for
4253 // each dimension of the array. We use these index variables to subscript
4254 // the source array, and other clients (e.g., CodeGen) will perform the
4255 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004256 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004257 QualType BaseType = Field->getType();
4258 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004259 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004260 while (const ConstantArrayType *Array
4261 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004262 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004263 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00004264 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004265 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004266 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004267 llvm::raw_svector_ostream OS(Str);
4268 OS << "__i" << IndexVariables.size();
4269 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4270 }
4271 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00004272 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004273 IterationVarName, SizeType,
4274 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004275 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004276 IndexVariables.push_back(IterationVar);
4277
4278 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00004279 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00004280 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004281 assert(!IterationVarRef.isInvalid() &&
4282 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004283 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00004284 assert(!IterationVarRef.isInvalid() &&
4285 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00004286
Douglas Gregor94f9a482010-05-05 05:51:00 +00004287 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004288 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4289 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00004290 Loc);
4291 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00004292 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004293
Douglas Gregor94f9a482010-05-05 05:51:00 +00004294 BaseType = Array->getElementType();
4295 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004296
4297 // The array subscript expression is an lvalue, which is wrong for moving.
4298 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004299 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004300
Douglas Gregor94f9a482010-05-05 05:51:00 +00004301 // Construct the entity that we will be initializing. For an array, this
4302 // will be first element in the array, which may require several levels
4303 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004304 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00004305 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00004306 if (Indirect)
4307 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4308 else
4309 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00004310 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4311 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4312 0,
4313 Entities.back()));
4314
4315 // Direct-initialize to use the copy constructor.
4316 InitializationKind InitKind =
4317 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4318
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004319 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00004320 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4321 CtorArgE);
4322
John McCalldadc5752010-08-24 06:29:42 +00004323 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00004324 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004325 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004326 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004327 if (MemberInit.isInvalid())
4328 return true;
4329
Douglas Gregor493627b2011-08-10 15:22:55 +00004330 if (Indirect) {
4331 assert(IndexVariables.size() == 0 &&
4332 "Indirect field improperly initialized");
4333 CXXMemberInit
4334 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4335 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004336 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004337 Loc);
4338 } else
4339 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004340 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00004341 Loc,
4342 IndexVariables.data(),
4343 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00004344 return false;
4345 }
4346
Richard Smithc2bc61b2013-03-18 21:12:30 +00004347 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4348 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004349
Anders Carlsson3c1db572010-04-23 02:15:47 +00004350 QualType FieldBaseElementType =
4351 SemaRef.Context.getBaseElementType(Field->getType());
4352
Anders Carlsson3c1db572010-04-23 02:15:47 +00004353 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004354 InitializedEntity InitEntity
4355 = Indirect? InitializedEntity::InitializeMember(Indirect)
4356 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004357 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004358 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004359
4360 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4361 ExprResult MemberInit =
4362 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004363
Douglas Gregora40433a2010-12-07 00:41:46 +00004364 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004365 if (MemberInit.isInvalid())
4366 return true;
4367
Douglas Gregor493627b2011-08-10 15:22:55 +00004368 if (Indirect)
4369 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4370 Indirect, Loc,
4371 Loc,
4372 MemberInit.get(),
4373 Loc);
4374 else
4375 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4376 Field, Loc, Loc,
4377 MemberInit.get(),
4378 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004379 return false;
4380 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004381
Alexis Hunt8b455182011-05-17 00:19:05 +00004382 if (!Field->getParent()->isUnion()) {
4383 if (FieldBaseElementType->isReferenceType()) {
4384 SemaRef.Diag(Constructor->getLocation(),
4385 diag::err_uninitialized_member_in_ctor)
4386 << (int)Constructor->isImplicit()
4387 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4388 << 0 << Field->getDeclName();
4389 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4390 return true;
4391 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004392
Alexis Hunt8b455182011-05-17 00:19:05 +00004393 if (FieldBaseElementType.isConstQualified()) {
4394 SemaRef.Diag(Constructor->getLocation(),
4395 diag::err_uninitialized_member_in_ctor)
4396 << (int)Constructor->isImplicit()
4397 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4398 << 1 << Field->getDeclName();
4399 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4400 return true;
4401 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004402 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004403
David Blaikiebbafb8a2012-03-11 07:00:24 +00004404 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004405 FieldBaseElementType->isObjCRetainableType() &&
4406 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4407 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004408 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004409 // Default-initialize Objective-C pointers to NULL.
4410 CXXMemberInit
4411 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4412 Loc, Loc,
4413 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4414 Loc);
4415 return false;
4416 }
4417
Anders Carlsson3c1db572010-04-23 02:15:47 +00004418 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004419 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004420 return false;
4421}
John McCallbc83b3f2010-05-20 23:23:51 +00004422
4423namespace {
4424struct BaseAndFieldInfo {
4425 Sema &S;
4426 CXXConstructorDecl *Ctor;
4427 bool AnyErrorsInInits;
4428 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004429 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004430 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004431 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004432
4433 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4434 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004435 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004436 if (Ctor->getInheritedConstructor())
4437 IIK = IIK_Inherit;
4438 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004439 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004440 else if (Generated && Ctor->isMoveConstructor())
4441 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004442 else
4443 IIK = IIK_Default;
4444 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004445
4446 bool isImplicitCopyOrMove() const {
4447 switch (IIK) {
4448 case IIK_Copy:
4449 case IIK_Move:
4450 return true;
4451
4452 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004453 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004454 return false;
4455 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004456
4457 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004458 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004459
4460 bool addFieldInitializer(CXXCtorInitializer *Init) {
4461 AllToInit.push_back(Init);
4462
4463 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004464 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004465 S.UnusedPrivateFields.remove(Init->getAnyMember());
4466
4467 return false;
4468 }
John McCallbc83b3f2010-05-20 23:23:51 +00004469
Richard Smithab44d5b2013-12-10 08:25:00 +00004470 bool isInactiveUnionMember(FieldDecl *Field) {
4471 RecordDecl *Record = Field->getParent();
4472 if (!Record->isUnion())
4473 return false;
4474
Richard Smith8d183852013-12-10 20:56:03 +00004475 if (FieldDecl *Active =
4476 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004477 return Active != Field->getCanonicalDecl();
4478
4479 // In an implicit copy or move constructor, ignore any in-class initializer.
4480 if (isImplicitCopyOrMove())
4481 return true;
4482
4483 // If there's no explicit initialization, the field is active only if it
4484 // has an in-class initializer...
4485 if (Field->hasInClassInitializer())
4486 return false;
4487 // ... or it's an anonymous struct or union whose class has an in-class
4488 // initializer.
4489 if (!Field->isAnonymousStructOrUnion())
4490 return true;
4491 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4492 return !FieldRD->hasInClassInitializer();
4493 }
4494
4495 /// \brief Determine whether the given field is, or is within, a union member
4496 /// that is inactive (because there was an initializer given for a different
4497 /// member of the union, or because the union was not initialized at all).
4498 bool isWithinInactiveUnionMember(FieldDecl *Field,
4499 IndirectFieldDecl *Indirect) {
4500 if (!Indirect)
4501 return isInactiveUnionMember(Field);
4502
Aaron Ballman29c94602014-03-07 18:36:15 +00004503 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004504 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004505 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004506 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004507 }
4508 return false;
4509 }
4510};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004511}
Richard Smithc94ec842011-09-19 13:34:43 +00004512
Douglas Gregor10f939c2011-11-02 23:04:16 +00004513/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4514/// array type.
4515static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4516 if (T->isIncompleteArrayType())
4517 return true;
4518
4519 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4520 if (!ArrayT->getSize())
4521 return true;
4522
4523 T = ArrayT->getElementType();
4524 }
4525
4526 return false;
4527}
4528
Richard Smith938f40b2011-06-11 17:19:42 +00004529static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004530 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004531 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004532 if (Field->isInvalidDecl())
4533 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004534
Chandler Carruth139e9622010-06-30 02:59:29 +00004535 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004536 if (CXXCtorInitializer *Init =
4537 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004538 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004539
Richard Smithab44d5b2013-12-10 08:25:00 +00004540 // C++11 [class.base.init]p8:
4541 // if the entity is a non-static data member that has a
4542 // brace-or-equal-initializer and either
4543 // -- the constructor's class is a union and no other variant member of that
4544 // union is designated by a mem-initializer-id or
4545 // -- the constructor's class is not a union, and, if the entity is a member
4546 // of an anonymous union, no other member of that union is designated by
4547 // a mem-initializer-id,
4548 // the entity is initialized as specified in [dcl.init].
4549 //
4550 // We also apply the same rules to handle anonymous structs within anonymous
4551 // unions.
4552 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4553 return false;
4554
Douglas Gregor7db3e952011-11-28 20:03:15 +00004555 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004556 ExprResult DIE =
4557 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4558 if (DIE.isInvalid())
4559 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004560 CXXCtorInitializer *Init;
4561 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004562 Init = new (SemaRef.Context)
4563 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4564 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004565 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004566 Init = new (SemaRef.Context)
4567 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4568 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004569 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004570 }
4571
Douglas Gregor10f939c2011-11-02 23:04:16 +00004572 // Don't initialize incomplete or zero-length arrays.
4573 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4574 return false;
4575
John McCallbc83b3f2010-05-20 23:23:51 +00004576 // Don't try to build an implicit initializer if there were semantic
4577 // errors in any of the initializers (and therefore we might be
4578 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004579 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004580 return false;
4581
Craig Topperc3ec1492014-05-26 06:22:03 +00004582 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004583 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4584 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004585 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004586
Richard Smith0a8cfc72012-08-07 21:30:42 +00004587 if (!Init)
4588 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004589
Richard Smith0a8cfc72012-08-07 21:30:42 +00004590 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004591}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004592
4593bool
4594Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4595 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004596 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004597 Constructor->setNumCtorInitializers(1);
4598 CXXCtorInitializer **initializer =
4599 new (Context) CXXCtorInitializer*[1];
4600 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4601 Constructor->setCtorInitializers(initializer);
4602
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004603 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004604 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004605 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4606 }
4607
Alexis Hunte2622992011-05-05 00:05:47 +00004608 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004609
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004610 DiagnoseUninitializedFields(*this, Constructor);
4611
Alexis Hunt61bc1732011-05-01 07:04:31 +00004612 return false;
4613}
Douglas Gregor493627b2011-08-10 15:22:55 +00004614
David Blaikie3fc2f912013-01-17 05:26:25 +00004615bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4616 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004617 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004618 // Just store the initializers as written, they will be checked during
4619 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004620 if (!Initializers.empty()) {
4621 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004622 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004623 new (Context) CXXCtorInitializer*[Initializers.size()];
4624 memcpy(baseOrMemberInitializers, Initializers.data(),
4625 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004626 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004627 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004628
4629 // Let template instantiation know whether we had errors.
4630 if (AnyErrors)
4631 Constructor->setInvalidDecl();
4632
Anders Carlssondb0a9652010-04-02 06:26:44 +00004633 return false;
4634 }
4635
John McCallbc83b3f2010-05-20 23:23:51 +00004636 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004637
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004638 // We need to build the initializer AST according to order of construction
4639 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004640 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004641 if (!ClassDecl)
4642 return true;
4643
Eli Friedman9cf6b592009-11-09 19:20:36 +00004644 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004645
David Blaikie3fc2f912013-01-17 05:26:25 +00004646 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004647 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004648
Anders Carlssondb0a9652010-04-02 06:26:44 +00004649 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004650 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004651 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004652 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004653
4654 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004655 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004656 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004657 if (FD && FD->getParent()->isUnion())
4658 Info.ActiveUnionMember.insert(std::make_pair(
4659 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4660 }
4661 } else if (FieldDecl *FD = Member->getMember()) {
4662 if (FD->getParent()->isUnion())
4663 Info.ActiveUnionMember.insert(std::make_pair(
4664 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4665 }
4666 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004667 }
4668
Anders Carlsson43c64af2010-04-21 19:52:01 +00004669 // Keep track of the direct virtual bases.
4670 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004671 for (auto &I : ClassDecl->bases()) {
4672 if (I.isVirtual())
4673 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004674 }
4675
Anders Carlssondb0a9652010-04-02 06:26:44 +00004676 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004677 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004678 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004679 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004680 // [class.base.init]p7, per DR257:
4681 // A mem-initializer where the mem-initializer-id names a virtual base
4682 // class is ignored during execution of a constructor of any class that
4683 // is not the most derived class.
4684 if (ClassDecl->isAbstract()) {
4685 // FIXME: Provide a fixit to remove the base specifier. This requires
4686 // tracking the location of the associated comma for a base specifier.
4687 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004688 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004689 DiagnoseAbstractType(ClassDecl);
4690 }
4691
John McCallbc83b3f2010-05-20 23:23:51 +00004692 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004693 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4694 // [class.base.init]p8, per DR257:
4695 // If a given [...] base class is not named by a mem-initializer-id
4696 // [...] and the entity is not a virtual base class of an abstract
4697 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004698 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004699 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004700 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004701 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004702 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004703 HadError = true;
4704 continue;
4705 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004706
John McCallbc83b3f2010-05-20 23:23:51 +00004707 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004708 }
4709 }
Mike Stump11289f42009-09-09 15:08:12 +00004710
John McCallbc83b3f2010-05-20 23:23:51 +00004711 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004712 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004713 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004714 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004715 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Alexis Hunt1d792652011-01-08 20:30:50 +00004717 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004718 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004719 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004720 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004721 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004722 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004723 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004724 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004725 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004726 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004727 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004728
John McCallbc83b3f2010-05-20 23:23:51 +00004729 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004730 }
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
John McCallbc83b3f2010-05-20 23:23:51 +00004733 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004734 for (auto *Mem : ClassDecl->decls()) {
4735 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004736 // C++ [class.bit]p2:
4737 // A declaration for a bit-field that omits the identifier declares an
4738 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4739 // initialized.
4740 if (F->isUnnamedBitfield())
4741 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004742
Sebastian Redl22653ba2011-08-30 19:58:05 +00004743 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004744 // handle anonymous struct/union fields based on their individual
4745 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004746 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004747 continue;
4748
4749 if (CollectFieldInitializer(*this, Info, F))
4750 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004751 continue;
4752 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004753
4754 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004755 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004756 continue;
4757
Aaron Ballman629afae2014-03-07 19:56:05 +00004758 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004759 if (F->getType()->isIncompleteArrayType()) {
4760 assert(ClassDecl->hasFlexibleArrayMember() &&
4761 "Incomplete array type is not valid");
4762 continue;
4763 }
4764
Douglas Gregor493627b2011-08-10 15:22:55 +00004765 // Initialize each field of an anonymous struct individually.
4766 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4767 HadError = true;
4768
4769 continue;
4770 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004771 }
Mike Stump11289f42009-09-09 15:08:12 +00004772
David Blaikie3fc2f912013-01-17 05:26:25 +00004773 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004774 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004775 Constructor->setNumCtorInitializers(NumInitializers);
4776 CXXCtorInitializer **baseOrMemberInitializers =
4777 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004778 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004779 NumInitializers * sizeof(CXXCtorInitializer*));
4780 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004781
John McCalla6309952010-03-16 21:39:52 +00004782 // Constructors implicitly reference the base and member
4783 // destructors.
4784 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4785 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004786 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004787
4788 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004789}
4790
David Blaikieb61b8152013-01-17 08:49:22 +00004791static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004792 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004793 const RecordDecl *RD = RT->getDecl();
4794 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004795 for (auto *Field : RD->fields())
4796 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004797 return;
4798 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004799 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004800 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004801}
4802
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004803static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4804 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004805}
4806
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004807static const void *GetKeyForMember(ASTContext &Context,
4808 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004809 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004810 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004811
Richard Smithcd45dbc2014-04-19 03:48:30 +00004812 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004813}
4814
David Blaikie3fc2f912013-01-17 05:26:25 +00004815static void DiagnoseBaseOrMemInitializerOrder(
4816 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4817 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004818 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004819 return;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004821 // Don't check initializers order unless the warning is enabled at the
4822 // location of at least one initializer.
4823 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004824 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004825 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004826 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4827 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004828 ShouldCheckOrder = true;
4829 break;
4830 }
4831 }
4832 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004833 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004834
John McCallbb7b6582010-04-10 07:37:23 +00004835 // Build the list of bases and members in the order that they'll
4836 // actually be initialized. The explicit initializers should be in
4837 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004838 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004839
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004840 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4841
John McCallbb7b6582010-04-10 07:37:23 +00004842 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004843 for (const auto &VBase : ClassDecl->vbases())
4844 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004845
John McCallbb7b6582010-04-10 07:37:23 +00004846 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004847 for (const auto &Base : ClassDecl->bases()) {
4848 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004849 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004850 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004851 }
Mike Stump11289f42009-09-09 15:08:12 +00004852
John McCallbb7b6582010-04-10 07:37:23 +00004853 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004854 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004855 if (Field->isUnnamedBitfield())
4856 continue;
4857
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004858 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004859 }
4860
John McCallbb7b6582010-04-10 07:37:23 +00004861 unsigned NumIdealInits = IdealInitKeys.size();
4862 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004863
Craig Topperc3ec1492014-05-26 06:22:03 +00004864 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004865 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004866 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004867 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004868
4869 // Scan forward to try to find this initializer in the idealized
4870 // initializers list.
4871 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4872 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004873 break;
John McCallbb7b6582010-04-10 07:37:23 +00004874
4875 // If we didn't find this initializer, it must be because we
4876 // scanned past it on a previous iteration. That can only
4877 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004878 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004879 Sema::SemaDiagnosticBuilder D =
4880 SemaRef.Diag(PrevInit->getSourceLocation(),
4881 diag::warn_initializer_out_of_order);
4882
Francois Pichetd583da02010-12-04 09:14:42 +00004883 if (PrevInit->isAnyMemberInitializer())
4884 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004885 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004886 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004887
Francois Pichetd583da02010-12-04 09:14:42 +00004888 if (Init->isAnyMemberInitializer())
4889 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004890 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004891 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004892
4893 // Move back to the initializer's location in the ideal list.
4894 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4895 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004896 break;
John McCallbb7b6582010-04-10 07:37:23 +00004897
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004898 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004899 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004900 }
John McCallbb7b6582010-04-10 07:37:23 +00004901
4902 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004903 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004904}
4905
John McCall23eebd92010-04-10 09:28:51 +00004906namespace {
4907bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004908 CXXCtorInitializer *Init,
4909 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004910 if (!PrevInit) {
4911 PrevInit = Init;
4912 return false;
4913 }
4914
Douglas Gregorea306a12013-03-25 23:28:23 +00004915 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004916 S.Diag(Init->getSourceLocation(),
4917 diag::err_multiple_mem_initialization)
4918 << Field->getDeclName()
4919 << Init->getSourceRange();
4920 else {
John McCall424cec92011-01-19 06:33:43 +00004921 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004922 assert(BaseClass && "neither field nor base");
4923 S.Diag(Init->getSourceLocation(),
4924 diag::err_multiple_base_initialization)
4925 << QualType(BaseClass, 0)
4926 << Init->getSourceRange();
4927 }
4928 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4929 << 0 << PrevInit->getSourceRange();
4930
4931 return true;
4932}
4933
Alexis Hunt1d792652011-01-08 20:30:50 +00004934typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004935typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4936
4937bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004938 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004939 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004940 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004941 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004942 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004943
4944 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004945 if (Parent->isUnion()) {
4946 UnionEntry &En = Unions[Parent];
4947 if (En.first && En.first != Child) {
4948 S.Diag(Init->getSourceLocation(),
4949 diag::err_multiple_mem_union_initialization)
4950 << Field->getDeclName()
4951 << Init->getSourceRange();
4952 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4953 << 0 << En.second->getSourceRange();
4954 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004955 }
4956 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004957 En.first = Child;
4958 En.second = Init;
4959 }
David Blaikie0f65d592011-11-17 06:01:57 +00004960 if (!Parent->isAnonymousStructOrUnion())
4961 return false;
John McCall23eebd92010-04-10 09:28:51 +00004962 }
4963
4964 Child = Parent;
4965 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004966 }
John McCall23eebd92010-04-10 09:28:51 +00004967
4968 return false;
4969}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004970}
John McCall23eebd92010-04-10 09:28:51 +00004971
Anders Carlssone857b292010-04-02 03:37:03 +00004972/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004973void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004974 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004975 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004976 bool AnyErrors) {
4977 if (!ConstructorDecl)
4978 return;
4979
4980 AdjustDeclIfTemplate(ConstructorDecl);
4981
4982 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004983 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004984
4985 if (!Constructor) {
4986 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4987 return;
4988 }
4989
John McCall23eebd92010-04-10 09:28:51 +00004990 // Mapping for the duplicate initializers check.
4991 // For member initializers, this is keyed with a FieldDecl*.
4992 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004993 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004994
4995 // Mapping for the inconsistent anonymous-union initializers check.
4996 RedundantUnionMap MemberUnions;
4997
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004998 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004999 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00005000 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00005001
Abramo Bagnara341d7832010-05-26 18:09:23 +00005002 // Set the source order index.
5003 Init->setSourceOrder(i);
5004
Francois Pichetd583da02010-12-04 09:14:42 +00005005 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005006 const void *Key = GetKeyForMember(Context, Init);
5007 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005008 CheckRedundantUnionInit(*this, Init, MemberUnions))
5009 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005010 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005011 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005012 if (CheckRedundantInit(*this, Init, Members[Key]))
5013 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005014 } else {
5015 assert(Init->isDelegatingInitializer());
5016 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005017 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005018 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005019 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005020 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005021 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005022 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005023 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005024 // Return immediately as the initializer is set.
5025 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005026 }
Anders Carlssone857b292010-04-02 03:37:03 +00005027 }
5028
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005029 if (HadError)
5030 return;
5031
David Blaikie3fc2f912013-01-17 05:26:25 +00005032 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005033
David Blaikie3fc2f912013-01-17 05:26:25 +00005034 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005035
Richard Trieuef64e942013-10-25 00:56:00 +00005036 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005037}
5038
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005039void
John McCalla6309952010-03-16 21:39:52 +00005040Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5041 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005042 // Ignore dependent contexts. Also ignore unions, since their members never
5043 // have destructors implicitly called.
5044 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005045 return;
John McCall1064d7e2010-03-16 05:22:47 +00005046
5047 // FIXME: all the access-control diagnostics are positioned on the
5048 // field/base declaration. That's probably good; that said, the
5049 // user might reasonably want to know why the destructor is being
5050 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005051
Anders Carlssondee9a302009-11-17 04:44:12 +00005052 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005053 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005054 if (Field->isInvalidDecl())
5055 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005056
5057 // Don't destroy incomplete or zero-length arrays.
5058 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5059 continue;
5060
Anders Carlssondee9a302009-11-17 04:44:12 +00005061 QualType FieldType = Context.getBaseElementType(Field->getType());
5062
5063 const RecordType* RT = FieldType->getAs<RecordType>();
5064 if (!RT)
5065 continue;
5066
5067 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005068 if (FieldClassDecl->isInvalidDecl())
5069 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005070 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005071 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005072 // The destructor for an implicit anonymous union member is never invoked.
5073 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5074 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005075
Douglas Gregore71edda2010-07-01 22:47:18 +00005076 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005077 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005078 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005079 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005080 << Field->getDeclName()
5081 << FieldType);
5082
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005083 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005084 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005085 }
5086
John McCall1064d7e2010-03-16 05:22:47 +00005087 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5088
Anders Carlssondee9a302009-11-17 04:44:12 +00005089 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005090 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005091 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005092 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005093
5094 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005095 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00005096 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00005097
John McCall1064d7e2010-03-16 05:22:47 +00005098 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005099 // If our base class is invalid, we probably can't get its dtor anyway.
5100 if (BaseClassDecl->isInvalidDecl())
5101 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005102 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005103 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005104
Douglas Gregore71edda2010-07-01 22:47:18 +00005105 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005106 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005107
5108 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005109 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005110 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005111 << Base.getType()
5112 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005113 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005114
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005115 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005116 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005117 }
5118
5119 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005120 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005121 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005122 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005123
5124 // Ignore direct virtual bases.
5125 if (DirectVirtualBases.count(RT))
5126 continue;
5127
John McCall1064d7e2010-03-16 05:22:47 +00005128 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005129 // If our base class is invalid, we probably can't get its dtor anyway.
5130 if (BaseClassDecl->isInvalidDecl())
5131 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005132 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005133 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005134
Douglas Gregore71edda2010-07-01 22:47:18 +00005135 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005136 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005137 if (CheckDestructorAccess(
5138 ClassDecl->getLocation(), Dtor,
5139 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005140 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005141 Context.getTypeDeclType(ClassDecl)) ==
5142 AR_accessible) {
5143 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005144 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005145 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005146 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005147 }
John McCall1064d7e2010-03-16 05:22:47 +00005148
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005149 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005150 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005151 }
5152}
5153
John McCall48871652010-08-21 09:40:31 +00005154void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005155 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005156 return;
Mike Stump11289f42009-09-09 15:08:12 +00005157
Mike Stump11289f42009-09-09 15:08:12 +00005158 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005159 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005160 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005161 DiagnoseUninitializedFields(*this, Constructor);
5162 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005163}
5164
Richard Smithdb0ac552015-12-18 22:40:25 +00005165bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005166 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005167 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005168
Richard Smithdb0ac552015-12-18 22:40:25 +00005169 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5170 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005171 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005172
Richard Smithdb0ac552015-12-18 22:40:25 +00005173 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5174 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005175
John McCall02db245d2010-08-18 09:41:07 +00005176 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005177 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005178 // over all the declarations when we have a full definition.
5179 const CXXRecordDecl *Def = RD->getDefinition();
5180 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005181 return false;
5182
Richard Smithdb0ac552015-12-18 22:40:25 +00005183 return RD->isAbstract();
5184}
5185
5186bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5187 TypeDiagnoser &Diagnoser) {
5188 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005189 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005190
Richard Smithdb0ac552015-12-18 22:40:25 +00005191 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005192 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005193 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005194 return true;
5195}
5196
5197void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5198 // Check if we've already emitted the list of pure virtual functions
5199 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005200 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005201 return;
Mike Stump11289f42009-09-09 15:08:12 +00005202
Richard Smithbc46e432013-07-22 02:56:56 +00005203 // If the diagnostic is suppressed, don't emit the notes. We're only
5204 // going to emit them once, so try to attach them to a diagnostic we're
5205 // actually going to show.
5206 if (Diags.isLastDiagnosticIgnored())
5207 return;
5208
Douglas Gregor4165bd62010-03-23 23:47:56 +00005209 CXXFinalOverriderMap FinalOverriders;
5210 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005211
Anders Carlssona2f74f32010-06-03 01:00:02 +00005212 // Keep a set of seen pure methods so we won't diagnose the same method
5213 // more than once.
5214 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5215
Douglas Gregor4165bd62010-03-23 23:47:56 +00005216 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5217 MEnd = FinalOverriders.end();
5218 M != MEnd;
5219 ++M) {
5220 for (OverridingMethods::iterator SO = M->second.begin(),
5221 SOEnd = M->second.end();
5222 SO != SOEnd; ++SO) {
5223 // C++ [class.abstract]p4:
5224 // A class is abstract if it contains or inherits at least one
5225 // pure virtual function for which the final overrider is pure
5226 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005227
Douglas Gregor4165bd62010-03-23 23:47:56 +00005228 //
5229 if (SO->second.size() != 1)
5230 continue;
5231
5232 if (!SO->second.front().Method->isPure())
5233 continue;
5234
David Blaikie82e95a32014-11-19 07:49:47 +00005235 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005236 continue;
5237
Douglas Gregor4165bd62010-03-23 23:47:56 +00005238 Diag(SO->second.front().Method->getLocation(),
5239 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005240 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005241 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005242 }
5243
5244 if (!PureVirtualClassDiagSet)
5245 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5246 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005247}
5248
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005249namespace {
John McCall02db245d2010-08-18 09:41:07 +00005250struct AbstractUsageInfo {
5251 Sema &S;
5252 CXXRecordDecl *Record;
5253 CanQualType AbstractType;
5254 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005255
John McCall02db245d2010-08-18 09:41:07 +00005256 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5257 : S(S), Record(Record),
5258 AbstractType(S.Context.getCanonicalType(
5259 S.Context.getTypeDeclType(Record))),
5260 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005261
John McCall02db245d2010-08-18 09:41:07 +00005262 void DiagnoseAbstractType() {
5263 if (Invalid) return;
5264 S.DiagnoseAbstractType(Record);
5265 Invalid = true;
5266 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005267
John McCall02db245d2010-08-18 09:41:07 +00005268 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5269};
5270
5271struct CheckAbstractUsage {
5272 AbstractUsageInfo &Info;
5273 const NamedDecl *Ctx;
5274
5275 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5276 : Info(Info), Ctx(Ctx) {}
5277
5278 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5279 switch (TL.getTypeLocClass()) {
5280#define ABSTRACT_TYPELOC(CLASS, PARENT)
5281#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005282 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005283#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005284 }
John McCall02db245d2010-08-18 09:41:07 +00005285 }
Mike Stump11289f42009-09-09 15:08:12 +00005286
John McCall02db245d2010-08-18 09:41:07 +00005287 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005288 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005289 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5290 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005291 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005292
5293 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005294 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005295 }
John McCall02db245d2010-08-18 09:41:07 +00005296 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005297
John McCall02db245d2010-08-18 09:41:07 +00005298 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5299 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5300 }
Mike Stump11289f42009-09-09 15:08:12 +00005301
John McCall02db245d2010-08-18 09:41:07 +00005302 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5303 // Visit the type parameters from a permissive context.
5304 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5305 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5306 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5307 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5308 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5309 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005310 }
John McCall02db245d2010-08-18 09:41:07 +00005311 }
Mike Stump11289f42009-09-09 15:08:12 +00005312
John McCall02db245d2010-08-18 09:41:07 +00005313 // Visit pointee types from a permissive context.
5314#define CheckPolymorphic(Type) \
5315 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5316 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5317 }
5318 CheckPolymorphic(PointerTypeLoc)
5319 CheckPolymorphic(ReferenceTypeLoc)
5320 CheckPolymorphic(MemberPointerTypeLoc)
5321 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005322 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005323
John McCall02db245d2010-08-18 09:41:07 +00005324 /// Handle all the types we haven't given a more specific
5325 /// implementation for above.
5326 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5327 // Every other kind of type that we haven't called out already
5328 // that has an inner type is either (1) sugar or (2) contains that
5329 // inner type in some way as a subobject.
5330 if (TypeLoc Next = TL.getNextTypeLoc())
5331 return Visit(Next, Sel);
5332
5333 // If there's no inner type and we're in a permissive context,
5334 // don't diagnose.
5335 if (Sel == Sema::AbstractNone) return;
5336
5337 // Check whether the type matches the abstract type.
5338 QualType T = TL.getType();
5339 if (T->isArrayType()) {
5340 Sel = Sema::AbstractArrayType;
5341 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005342 }
John McCall02db245d2010-08-18 09:41:07 +00005343 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5344 if (CT != Info.AbstractType) return;
5345
5346 // It matched; do some magic.
5347 if (Sel == Sema::AbstractArrayType) {
5348 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5349 << T << TL.getSourceRange();
5350 } else {
5351 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5352 << Sel << T << TL.getSourceRange();
5353 }
5354 Info.DiagnoseAbstractType();
5355 }
5356};
5357
5358void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5359 Sema::AbstractDiagSelID Sel) {
5360 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5361}
5362
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005363}
John McCall02db245d2010-08-18 09:41:07 +00005364
5365/// Check for invalid uses of an abstract type in a method declaration.
5366static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5367 CXXMethodDecl *MD) {
5368 // No need to do the check on definitions, which require that
5369 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005370 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005371 return;
5372
5373 // For safety's sake, just ignore it if we don't have type source
5374 // information. This should never happen for non-implicit methods,
5375 // but...
5376 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5377 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5378}
5379
5380/// Check for invalid uses of an abstract type within a class definition.
5381static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5382 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005383 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005384 if (D->isImplicit()) continue;
5385
5386 // Methods and method templates.
5387 if (isa<CXXMethodDecl>(D)) {
5388 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5389 } else if (isa<FunctionTemplateDecl>(D)) {
5390 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5391 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5392
5393 // Fields and static variables.
5394 } else if (isa<FieldDecl>(D)) {
5395 FieldDecl *FD = cast<FieldDecl>(D);
5396 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5397 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5398 } else if (isa<VarDecl>(D)) {
5399 VarDecl *VD = cast<VarDecl>(D);
5400 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5401 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5402
5403 // Nested classes and class templates.
5404 } else if (isa<CXXRecordDecl>(D)) {
5405 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5406 } else if (isa<ClassTemplateDecl>(D)) {
5407 CheckAbstractClassUsage(Info,
5408 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5409 }
5410 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005411}
5412
Hans Wennborg99000c22015-08-15 01:18:16 +00005413static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5414 Attr *ClassAttr = getDLLAttr(Class);
5415 if (!ClassAttr)
5416 return;
5417
5418 assert(ClassAttr->getKind() == attr::DLLExport);
5419
5420 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5421
5422 if (TSK == TSK_ExplicitInstantiationDeclaration)
5423 // Don't go any further if this is just an explicit instantiation
5424 // declaration.
5425 return;
5426
5427 for (Decl *Member : Class->decls()) {
5428 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5429 if (!MD)
5430 continue;
5431
5432 if (Member->getAttr<DLLExportAttr>()) {
5433 if (MD->isUserProvided()) {
5434 // Instantiate non-default class member functions ...
5435
5436 // .. except for certain kinds of template specializations.
5437 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5438 continue;
5439
5440 S.MarkFunctionReferenced(Class->getLocation(), MD);
5441
5442 // The function will be passed to the consumer when its definition is
5443 // encountered.
5444 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5445 MD->isCopyAssignmentOperator() ||
5446 MD->isMoveAssignmentOperator()) {
5447 // Synthesize and instantiate non-trivial implicit methods, explicitly
5448 // defaulted methods, and the copy and move assignment operators. The
5449 // latter are exported even if they are trivial, because the address of
5450 // an operator can be taken and should compare equal accross libraries.
5451 DiagnosticErrorTrap Trap(S.Diags);
5452 S.MarkFunctionReferenced(Class->getLocation(), MD);
5453 if (Trap.hasErrorOccurred()) {
5454 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5455 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5456 break;
5457 }
5458
5459 // There is no later point when we will see the definition of this
5460 // function, so pass it to the consumer now.
5461 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5462 }
5463 }
5464 }
5465}
5466
Hans Wennborg853ae942014-05-30 16:59:42 +00005467/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005468void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005469 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005470
5471 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005472 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005473 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5474 if (Attr *TemplateAttr =
5475 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005476 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005477 A->setInherited(true);
5478 ClassAttr = A;
5479 }
5480 }
5481 }
5482
Hans Wennborg853ae942014-05-30 16:59:42 +00005483 if (!ClassAttr)
5484 return;
5485
Hans Wennborg8313c762014-11-03 16:09:16 +00005486 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005487 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005488 << Class << ClassAttr;
5489 return;
5490 }
5491
Hans Wennborg17f9b442015-05-27 00:06:45 +00005492 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005493 !ClassAttr->isInherited()) {
5494 // Diagnose dll attributes on members of class with dll attribute.
5495 for (Decl *Member : Class->decls()) {
5496 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5497 continue;
5498 InheritableAttr *MemberAttr = getDLLAttr(Member);
5499 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5500 continue;
5501
Hans Wennborg17f9b442015-05-27 00:06:45 +00005502 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005503 diag::err_attribute_dll_member_of_dll_class)
5504 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005505 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005506 Member->setInvalidDecl();
5507 }
5508 }
5509
5510 if (Class->getDescribedClassTemplate())
5511 // Don't inherit dll attribute until the template is instantiated.
5512 return;
5513
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005514 // The class is either imported or exported.
5515 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005516
Hans Wennborgfd76d912015-01-15 21:18:30 +00005517 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5518
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005519 // Ignore explicit dllexport on explicit class template instantiation declarations.
5520 if (ClassExported && !ClassAttr->isInherited() &&
5521 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005522 Class->dropAttr<DLLExportAttr>();
5523 return;
5524 }
5525
Hans Wennborg853ae942014-05-30 16:59:42 +00005526 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005527 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005528
5529 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5530 // seem to be true in practice?
5531
Hans Wennborg853ae942014-05-30 16:59:42 +00005532 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005533 VarDecl *VD = dyn_cast<VarDecl>(Member);
5534 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5535
5536 // Only methods and static fields inherit the attributes.
5537 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005538 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005539
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005540 if (MD) {
5541 // Don't process deleted methods.
5542 if (MD->isDeleted())
5543 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005544
David Majnemer30f058a2015-05-11 03:00:22 +00005545 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005546 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005547 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5548 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005549 continue;
5550
Dmitry Polukhin41581522016-05-13 09:03:56 +00005551 // MSVC versions before 2015 don't export the move assignment operators
5552 // and move constructor, so don't attempt to import/export them if
5553 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005554 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005555 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005556 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005557 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005558 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005559
5560 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5561 // operator is exported anyway.
5562 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5563 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5564 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005565 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005566 }
5567
Hans Wennborg287231c2015-04-22 04:05:17 +00005568 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5569 continue;
5570
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005571 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005572 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005573 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005574 NewAttr->setInherited(true);
5575 Member->addAttr(NewAttr);
5576 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005577 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005578
5579 if (ClassExported)
5580 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005581}
5582
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005583/// \brief Perform propagation of DLL attributes from a derived class to a
5584/// templated base class for MS compatibility.
5585void Sema::propagateDLLAttrToBaseClassTemplate(
5586 CXXRecordDecl *Class, Attr *ClassAttr,
5587 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5588 if (getDLLAttr(
5589 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5590 // If the base class template has a DLL attribute, don't try to change it.
5591 return;
5592 }
5593
5594 auto TSK = BaseTemplateSpec->getSpecializationKind();
5595 if (!getDLLAttr(BaseTemplateSpec) &&
5596 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5597 TSK == TSK_ImplicitInstantiation)) {
5598 // The template hasn't been instantiated yet (or it has, but only as an
5599 // explicit instantiation declaration or implicit instantiation, which means
5600 // we haven't codegenned any members yet), so propagate the attribute.
5601 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5602 NewAttr->setInherited(true);
5603 BaseTemplateSpec->addAttr(NewAttr);
5604
5605 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5606 // needs to be run again to work see the new attribute. Otherwise this will
5607 // get run whenever the template is instantiated.
5608 if (TSK != TSK_Undeclared)
5609 checkClassLevelDLLAttribute(BaseTemplateSpec);
5610
5611 return;
5612 }
5613
5614 if (getDLLAttr(BaseTemplateSpec)) {
5615 // The template has already been specialized or instantiated with an
5616 // attribute, explicitly or through propagation. We should not try to change
5617 // it.
5618 return;
5619 }
5620
5621 // The template was previously instantiated or explicitly specialized without
5622 // a dll attribute, It's too late for us to add an attribute, so warn that
5623 // this is unsupported.
5624 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5625 << BaseTemplateSpec->isExplicitSpecialization();
5626 Diag(ClassAttr->getLocation(), diag::note_attribute);
5627 if (BaseTemplateSpec->isExplicitSpecialization()) {
5628 Diag(BaseTemplateSpec->getLocation(),
5629 diag::note_template_class_explicit_specialization_was_here)
5630 << BaseTemplateSpec;
5631 } else {
5632 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5633 diag::note_template_class_instantiation_was_here)
5634 << BaseTemplateSpec;
5635 }
5636}
5637
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005638static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5639 SourceLocation DefaultLoc) {
5640 switch (S.getSpecialMember(MD)) {
5641 case Sema::CXXDefaultConstructor:
5642 S.DefineImplicitDefaultConstructor(DefaultLoc,
5643 cast<CXXConstructorDecl>(MD));
5644 break;
5645 case Sema::CXXCopyConstructor:
5646 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5647 break;
5648 case Sema::CXXCopyAssignment:
5649 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5650 break;
5651 case Sema::CXXDestructor:
5652 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5653 break;
5654 case Sema::CXXMoveConstructor:
5655 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5656 break;
5657 case Sema::CXXMoveAssignment:
5658 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5659 break;
5660 case Sema::CXXInvalid:
5661 llvm_unreachable("Invalid special member.");
5662 }
5663}
5664
Douglas Gregorc99f1552009-12-03 18:33:45 +00005665/// \brief Perform semantic checks on a class definition that has been
5666/// completing, introducing implicitly-declared members, checking for
5667/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005668void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005669 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005670 return;
5671
John McCall02db245d2010-08-18 09:41:07 +00005672 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5673 AbstractUsageInfo Info(*this, Record);
5674 CheckAbstractClassUsage(Info, Record);
5675 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005676
5677 // If this is not an aggregate type and has no user-declared constructor,
5678 // complain about any non-static data members of reference or const scalar
5679 // type, since they will never get initializers.
5680 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005681 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5682 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005683 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005684 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005685 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005686 continue;
5687
Douglas Gregor454a5b62010-04-15 00:00:53 +00005688 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005689 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005690 if (!Complained) {
5691 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5692 << Record->getTagKind() << Record;
5693 Complained = true;
5694 }
5695
5696 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5697 << F->getType()->isReferenceType()
5698 << F->getDeclName();
5699 }
5700 }
5701 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005702
Douglas Gregor36c22a22010-10-15 13:21:21 +00005703 if (Record->getIdentifier()) {
5704 // C++ [class.mem]p13:
5705 // If T is the name of a class, then each of the following shall have a
5706 // name different from T:
5707 // - every member of every anonymous union that is a member of class T.
5708 //
5709 // C++ [class.mem]p14:
5710 // In addition, if class T has a user-declared constructor (12.1), every
5711 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005712 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5713 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5714 ++I) {
5715 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005716 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5717 isa<IndirectFieldDecl>(D)) {
5718 Diag(D->getLocation(), diag::err_member_name_of_class)
5719 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005720 break;
5721 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005722 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005723 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005724
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005725 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005726 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005727 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005728 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5729 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005730 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5731 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5732 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005733
David Majnemera5433082013-10-18 00:33:31 +00005734 if (Record->isAbstract()) {
5735 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5736 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5737 << FA->isSpelledAsSealed();
5738 DiagnoseAbstractType(Record);
5739 }
David Blaikie348df502012-09-21 03:21:07 +00005740 }
5741
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005742 bool HasMethodWithOverrideControl = false,
5743 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005744 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005745 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005746 // See if a method overloads virtual methods in a base
5747 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005748 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005749 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005750 if (M->hasAttr<OverrideAttr>())
5751 HasMethodWithOverrideControl = true;
5752 else if (M->size_overridden_methods() > 0)
5753 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005754 // Check whether the explicitly-defaulted special members are valid.
5755 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005756 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005757
5758 // For an explicitly defaulted or deleted special member, we defer
5759 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005760 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005761 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005762 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005763 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005764
5765 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005766 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005767 }
5768 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005769
5770 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5771 M->hasAttr<DLLExportAttr>()) {
5772 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5773 M->isTrivial() &&
5774 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5775 CSM == CXXDestructor))
5776 M->dropAttr<DLLExportAttr>();
5777
5778 if (M->hasAttr<DLLExportAttr>()) {
5779 DefineImplicitSpecialMember(*this, M, M->getLocation());
5780 ActOnFinishInlineFunctionDef(M);
5781 }
5782 }
Richard Smithbd305122012-12-11 01:14:52 +00005783 }
5784 }
5785
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005786 if (HasMethodWithOverrideControl &&
5787 HasOverridingMethodWithoutOverrideControl) {
5788 // At least one method has the 'override' control declared.
5789 // Diagnose all other overridden methods which do not have 'override' specified on them.
5790 for (auto *M : Record->methods())
5791 DiagnoseAbsenceOfOverrideControl(M);
5792 }
Sebastian Redl08905022011-02-05 19:23:19 +00005793
John McCall95833f32014-02-27 20:30:49 +00005794 // ms_struct is a request to use the same ABI rules as MSVC. Check
5795 // whether this class uses any C++ features that are implemented
5796 // completely differently in MSVC, and if so, emit a diagnostic.
5797 // That diagnostic defaults to an error, but we allow projects to
5798 // map it down to a warning (or ignore it). It's a fairly common
5799 // practice among users of the ms_struct pragma to mass-annotate
5800 // headers, sweeping up a bunch of types that the project doesn't
5801 // really rely on MSVC-compatible layout for. We must therefore
5802 // support "ms_struct except for C++ stuff" as a secondary ABI.
5803 if (Record->isMsStruct(Context) &&
5804 (Record->isPolymorphic() || Record->getNumBases())) {
5805 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005806 }
5807
Hans Wennborg17f9b442015-05-27 00:06:45 +00005808 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005809}
5810
Richard Smith41c35d62013-11-27 03:39:20 +00005811/// Look up the special member function that would be called by a special
5812/// member function for a subobject of class type.
5813///
5814/// \param Class The class type of the subobject.
5815/// \param CSM The kind of special member function.
5816/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5817/// \param ConstRHS True if this is a copy operation with a const object
5818/// on its RHS, that is, if the argument to the outer special member
5819/// function is 'const' and this is not a field marked 'mutable'.
5820static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5821 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5822 unsigned FieldQuals, bool ConstRHS) {
5823 unsigned LHSQuals = 0;
5824 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5825 LHSQuals = FieldQuals;
5826
5827 unsigned RHSQuals = FieldQuals;
5828 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5829 RHSQuals = 0;
5830 else if (ConstRHS)
5831 RHSQuals |= Qualifiers::Const;
5832
5833 return S.LookupSpecialMember(Class, CSM,
5834 RHSQuals & Qualifiers::Const,
5835 RHSQuals & Qualifiers::Volatile,
5836 false,
5837 LHSQuals & Qualifiers::Const,
5838 LHSQuals & Qualifiers::Volatile);
5839}
5840
Richard Smith80a47022016-06-29 01:10:27 +00005841class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005842 Sema &S;
5843 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005844
5845 /// A mapping from the base classes through which the constructor was
5846 /// inherited to the using shadow declaration in that base class (or a null
5847 /// pointer if the constructor was declared in that base class).
5848 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5849 InheritedFromBases;
5850
Richard Smith80a47022016-06-29 01:10:27 +00005851public:
Richard Smith5179eb72016-06-28 19:03:57 +00005852 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5853 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005854 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005855 bool DiagnosedMultipleConstructedBases = false;
5856 CXXRecordDecl *ConstructedBase = nullptr;
5857 UsingDecl *ConstructedBaseUsing = nullptr;
5858
5859 // Find the set of such base class subobjects and check that there's a
5860 // unique constructed subobject.
5861 for (auto *D : Shadow->redecls()) {
5862 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5863 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5864 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5865
5866 InheritedFromBases.insert(
5867 std::make_pair(DNominatedBase->getCanonicalDecl(),
5868 DShadow->getNominatedBaseClassShadowDecl()));
5869 if (DShadow->constructsVirtualBase())
5870 InheritedFromBases.insert(
5871 std::make_pair(DConstructedBase->getCanonicalDecl(),
5872 DShadow->getConstructedBaseClassShadowDecl()));
5873 else
5874 assert(DNominatedBase == DConstructedBase);
5875
5876 // [class.inhctor.init]p2:
5877 // If the constructor was inherited from multiple base class subobjects
5878 // of type B, the program is ill-formed.
5879 if (!ConstructedBase) {
5880 ConstructedBase = DConstructedBase;
5881 ConstructedBaseUsing = D->getUsingDecl();
5882 } else if (ConstructedBase != DConstructedBase &&
5883 !Shadow->isInvalidDecl()) {
5884 if (!DiagnosedMultipleConstructedBases) {
5885 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5886 << Shadow->getTargetDecl();
5887 S.Diag(ConstructedBaseUsing->getLocation(),
5888 diag::note_ambiguous_inherited_constructor_using)
5889 << ConstructedBase;
5890 DiagnosedMultipleConstructedBases = true;
5891 }
5892 S.Diag(D->getUsingDecl()->getLocation(),
5893 diag::note_ambiguous_inherited_constructor_using)
5894 << DConstructedBase;
5895 }
5896 }
5897
5898 if (DiagnosedMultipleConstructedBases)
5899 Shadow->setInvalidDecl();
5900 }
5901
5902 /// Find the constructor to use for inherited construction of a base class,
5903 /// and whether that base class constructor inherits the constructor from a
5904 /// virtual base class (in which case it won't actually invoke it).
5905 std::pair<CXXConstructorDecl *, bool>
5906 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5907 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5908 if (It == InheritedFromBases.end())
5909 return std::make_pair(nullptr, false);
5910
5911 // This is an intermediary class.
5912 if (It->second)
5913 return std::make_pair(
5914 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5915 It->second->constructsVirtualBase());
5916
5917 // This is the base class from which the constructor was inherited.
5918 return std::make_pair(Ctor, false);
5919 }
5920};
Richard Smith5179eb72016-06-28 19:03:57 +00005921
Richard Smithb5800092012-06-10 05:43:50 +00005922/// Is the special member function which would be selected to perform the
5923/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005924static bool
5925specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5926 Sema::CXXSpecialMember CSM, unsigned Quals,
5927 bool ConstRHS,
5928 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005929 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005930 // If we're inheriting a constructor, see if we need to call it for this base
5931 // class.
5932 if (InheritedCtor) {
5933 assert(CSM == Sema::CXXDefaultConstructor);
5934 auto BaseCtor =
5935 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5936 if (BaseCtor)
5937 return BaseCtor->isConstexpr();
5938 }
5939
5940 if (CSM == Sema::CXXDefaultConstructor)
5941 return ClassDecl->hasConstexprDefaultConstructor();
5942
Richard Smithb5800092012-06-10 05:43:50 +00005943 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005944 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005945 if (!SMOR || !SMOR->getMethod())
5946 // A constructor we wouldn't select can't be "involved in initializing"
5947 // anything.
5948 return true;
5949 return SMOR->getMethod()->isConstexpr();
5950}
5951
5952/// Determine whether the specified special member function would be constexpr
5953/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005954static bool defaultedSpecialMemberIsConstexpr(
5955 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5956 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005957 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005958 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005959 return false;
5960
5961 // C++11 [dcl.constexpr]p4:
5962 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005963 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005964 switch (CSM) {
5965 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00005966 if (Inherited)
5967 break;
Richard Smith4086a132012-06-10 07:07:24 +00005968 // Since default constructor lookup is essentially trivial (and cannot
5969 // involve, for instance, template instantiation), we compute whether a
5970 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5971 //
5972 // This is important for performance; we need to know whether the default
5973 // constructor is constexpr to determine whether the type is a literal type.
5974 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5975
Richard Smithb5800092012-06-10 05:43:50 +00005976 case Sema::CXXCopyConstructor:
5977 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005978 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005979 break;
5980
5981 case Sema::CXXCopyAssignment:
5982 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005983 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005984 return false;
5985 // In C++1y, we need to perform overload resolution.
5986 Ctor = false;
5987 break;
5988
Richard Smithb5800092012-06-10 05:43:50 +00005989 case Sema::CXXDestructor:
5990 case Sema::CXXInvalid:
5991 return false;
5992 }
5993
5994 // -- if the class is a non-empty union, or for each non-empty anonymous
5995 // union member of a non-union class, exactly one non-static data member
5996 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005997 //
5998 // If we squint, this is guaranteed, since exactly one non-static data member
5999 // will be initialized (if the constructor isn't deleted), we just don't know
6000 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006001 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006002 return CSM == Sema::CXXDefaultConstructor
6003 ? ClassDecl->hasInClassInitializer() ||
6004 !ClassDecl->hasVariantMembers()
6005 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006006
6007 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006008 if (Ctor && ClassDecl->getNumVBases())
6009 return false;
6010
6011 // C++1y [class.copy]p26:
6012 // -- [the class] is a literal type, and
6013 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006014 return false;
6015
6016 // -- every constructor involved in initializing [...] base class
6017 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006018 // -- the assignment operator selected to copy/move each direct base
6019 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006020 for (const auto &B : ClassDecl->bases()) {
6021 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006022 if (!BaseType) continue;
6023
6024 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006025 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6026 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006027 return false;
6028 }
6029
6030 // -- every constructor involved in initializing non-static data members
6031 // [...] shall be a constexpr constructor;
6032 // -- every non-static data member and base class sub-object shall be
6033 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006034 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006035 // thereof), the assignment operator selected to copy/move that member is
6036 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006037 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006038 if (F->isInvalidDecl())
6039 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006040 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6041 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006042 QualType BaseType = S.Context.getBaseElementType(F->getType());
6043 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006044 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006045 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6046 BaseType.getCVRQualifiers(),
6047 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006048 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006049 } else if (CSM == Sema::CXXDefaultConstructor) {
6050 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006051 }
6052 }
6053
6054 // All OK, it's constexpr!
6055 return true;
6056}
6057
Richard Smithd3b5c9082012-07-27 04:22:15 +00006058static Sema::ImplicitExceptionSpecification
6059computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6060 switch (S.getSpecialMember(MD)) {
6061 case Sema::CXXDefaultConstructor:
6062 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6063 case Sema::CXXCopyConstructor:
6064 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6065 case Sema::CXXCopyAssignment:
6066 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6067 case Sema::CXXMoveConstructor:
6068 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6069 case Sema::CXXMoveAssignment:
6070 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6071 case Sema::CXXDestructor:
6072 return S.ComputeDefaultedDtorExceptionSpec(MD);
6073 case Sema::CXXInvalid:
6074 break;
6075 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00006076 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6077 "only special members have implicit exception specs");
Richard Smith5179eb72016-06-28 19:03:57 +00006078 return S.ComputeInheritingCtorExceptionSpec(Loc,
6079 cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00006080}
6081
Reid Kleckner78af0702013-08-27 23:08:25 +00006082static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6083 CXXMethodDecl *MD) {
6084 FunctionProtoType::ExtProtoInfo EPI;
6085
6086 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006087 EPI.ExceptionSpec.Type = EST_Unevaluated;
6088 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006089
6090 // Set the calling convention to the default for C++ instance methods.
6091 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6092 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6093 /*IsCXXMethod=*/true));
6094 return EPI;
6095}
6096
Richard Smithd3b5c9082012-07-27 04:22:15 +00006097void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6098 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6099 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6100 return;
6101
Richard Smith7f782272012-07-30 23:48:14 +00006102 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006103 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6104 auto ESI = IES.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);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006302 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6303 EPI.ExceptionSpec = IES.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 Smith5e052982016-11-08 01:07:26 +00006660 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6661 bool AnyFields = false;
6662 for (auto *F : MD->getParent()->fields())
6663 if ((AnyFields = !F->isUnnamedBitfield()))
6664 break;
6665 if (!AnyFields)
6666 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006667 if (Diagnose)
6668 S.Diag(MD->getParent()->getLocation(),
6669 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006670 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006671 return true;
6672 }
6673 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006674}
6675
6676/// Determine whether a defaulted special member function should be defined as
6677/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6678/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006679bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006680 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006681 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006682 if (MD->isInvalidDecl())
6683 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006684 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006685 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006686 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006687 return false;
6688
Richard Smithd951a1d2012-02-18 02:02:13 +00006689 // C++11 [expr.lambda.prim]p19:
6690 // The closure type associated with a lambda-expression has a
6691 // deleted (8.4.3) default constructor and a deleted copy
6692 // assignment operator.
6693 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006694 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6695 if (Diagnose)
6696 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006697 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006698 }
6699
Richard Smith6f1e2c62012-04-02 20:59:25 +00006700 // For an anonymous struct or union, the copy and assignment special members
6701 // will never be used, so skip the check. For an anonymous union declared at
6702 // namespace scope, the constructor and destructor are used.
6703 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6704 RD->isAnonymousStructOrUnion())
6705 return false;
6706
Richard Smith852265f2012-03-30 20:53:28 +00006707 // C++11 [class.copy]p7, p18:
6708 // If the class definition declares a move constructor or move assignment
6709 // operator, an implicitly declared copy constructor or copy assignment
6710 // operator is defined as deleted.
6711 if (MD->isImplicit() &&
6712 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006713 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006714
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006715 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6716 // deletion of the corresponding copy operation, not both copy operations.
6717 // MSVC 2015 has adopted the standards conforming behavior.
6718 bool DeletesOnlyMatchingCopy =
6719 getLangOpts().MSVCCompat &&
6720 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6721
Richard Smith852265f2012-03-30 20:53:28 +00006722 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006723 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006724 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006725
6726 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006727 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006728 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006729 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006730 break;
6731 }
6732 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006733 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006734 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006735 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006736 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006737
6738 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006739 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006740 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006741 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006742 break;
6743 }
6744 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006745 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006746 }
6747
6748 if (UserDeclaredMove) {
6749 Diag(UserDeclaredMove->getLocation(),
6750 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006751 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006752 << UserDeclaredMove->isMoveAssignmentOperator();
6753 return true;
6754 }
6755 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006756
Richard Smith6f1e2c62012-04-02 20:59:25 +00006757 // Do access control from the special member function
6758 ContextRAII MethodContext(*this, MD);
6759
Richard Smith921bd202012-02-26 09:11:52 +00006760 // C++11 [class.dtor]p5:
6761 // -- for a virtual destructor, lookup of the non-array deallocation function
6762 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006763 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006764 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006765 DeclarationName Name =
6766 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6767 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006768 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006769 if (Diagnose)
6770 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006771 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006772 }
Richard Smith921bd202012-02-26 09:11:52 +00006773 }
6774
Richard Smith80a47022016-06-29 01:10:27 +00006775 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006776
Aaron Ballman574705e2014-03-13 15:41:46 +00006777 for (auto &BI : RD->bases())
Richard Smith0786d5b2016-08-31 20:37:39 +00006778 if ((SMI.IsAssignment || !BI.isVirtual()) &&
Aaron Ballman574705e2014-03-13 15:41:46 +00006779 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00006780 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006781
Richard Smithd1627032013-07-22 18:06:23 +00006782 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smith0786d5b2016-08-31 20:37:39 +00006783 // classes, since we are not going to construct them. For assignment
6784 // operators, we only assign (and thus only consider) direct bases.
6785 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006786 for (auto &BI : RD->vbases())
6787 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00006788 return true;
6789 }
Alexis Huntea6f0322011-05-11 22:34:38 +00006790
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006791 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00006792 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006793 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00006794 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006795
Richard Smithd951a1d2012-02-18 02:02:13 +00006796 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006797 return true;
6798
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006799 if (getLangOpts().CUDA) {
6800 // We should delete the special member in CUDA mode if target inference
6801 // failed.
6802 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6803 Diagnose);
6804 }
6805
Alexis Huntea6f0322011-05-11 22:34:38 +00006806 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006807}
6808
Richard Smith92f241f2012-12-08 02:53:02 +00006809/// Perform lookup for a special member of the specified kind, and determine
6810/// whether it is trivial. If the triviality can be determined without the
6811/// lookup, skip it. This is intended for use when determining whether a
6812/// special member of a containing object is trivial, and thus does not ever
6813/// perform overload resolution for default constructors.
6814///
6815/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6816/// member that was most likely to be intended to be trivial, if any.
6817static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6818 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006819 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006820 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006821 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006822
6823 switch (CSM) {
6824 case Sema::CXXInvalid:
6825 llvm_unreachable("not a special member");
6826
6827 case Sema::CXXDefaultConstructor:
6828 // C++11 [class.ctor]p5:
6829 // A default constructor is trivial if:
6830 // - all the [direct subobjects] have trivial default constructors
6831 //
6832 // Note, no overload resolution is performed in this case.
6833 if (RD->hasTrivialDefaultConstructor())
6834 return true;
6835
6836 if (Selected) {
6837 // If there's a default constructor which could have been trivial, dig it
6838 // out. Otherwise, if there's any user-provided default constructor, point
6839 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006840 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006841 if (RD->needsImplicitDefaultConstructor())
6842 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006843 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006844 if (!CI->isDefaultConstructor())
6845 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006846 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006847 if (!DefCtor->isUserProvided())
6848 break;
6849 }
6850
6851 *Selected = DefCtor;
6852 }
6853
6854 return false;
6855
6856 case Sema::CXXDestructor:
6857 // C++11 [class.dtor]p5:
6858 // A destructor is trivial if:
6859 // - all the direct [subobjects] have trivial destructors
6860 if (RD->hasTrivialDestructor())
6861 return true;
6862
6863 if (Selected) {
6864 if (RD->needsImplicitDestructor())
6865 S.DeclareImplicitDestructor(RD);
6866 *Selected = RD->getDestructor();
6867 }
6868
6869 return false;
6870
6871 case Sema::CXXCopyConstructor:
6872 // C++11 [class.copy]p12:
6873 // A copy constructor is trivial if:
6874 // - the constructor selected to copy each direct [subobject] is trivial
6875 if (RD->hasTrivialCopyConstructor()) {
6876 if (Quals == Qualifiers::Const)
6877 // We must either select the trivial copy constructor or reach an
6878 // ambiguity; no need to actually perform overload resolution.
6879 return true;
6880 } else if (!Selected) {
6881 return false;
6882 }
6883 // In C++98, we are not supposed to perform overload resolution here, but we
6884 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6885 // cases like B as having a non-trivial copy constructor:
6886 // struct A { template<typename T> A(T&); };
6887 // struct B { mutable A a; };
6888 goto NeedOverloadResolution;
6889
6890 case Sema::CXXCopyAssignment:
6891 // C++11 [class.copy]p25:
6892 // A copy assignment operator is trivial if:
6893 // - the assignment operator selected to copy each direct [subobject] is
6894 // trivial
6895 if (RD->hasTrivialCopyAssignment()) {
6896 if (Quals == Qualifiers::Const)
6897 return true;
6898 } else if (!Selected) {
6899 return false;
6900 }
6901 // In C++98, we are not supposed to perform overload resolution here, but we
6902 // treat that as a language defect.
6903 goto NeedOverloadResolution;
6904
6905 case Sema::CXXMoveConstructor:
6906 case Sema::CXXMoveAssignment:
6907 NeedOverloadResolution:
6908 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006909 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006910
6911 // The standard doesn't describe how to behave if the lookup is ambiguous.
6912 // We treat it as not making the member non-trivial, just like the standard
6913 // mandates for the default constructor. This should rarely matter, because
6914 // the member will also be deleted.
6915 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6916 return true;
6917
6918 if (!SMOR->getMethod()) {
6919 assert(SMOR->getKind() ==
6920 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6921 return false;
6922 }
6923
6924 // We deliberately don't check if we found a deleted special member. We're
6925 // not supposed to!
6926 if (Selected)
6927 *Selected = SMOR->getMethod();
6928 return SMOR->getMethod()->isTrivial();
6929 }
6930
6931 llvm_unreachable("unknown special method kind");
6932}
6933
Benjamin Kramer3e350262013-02-15 12:30:38 +00006934static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006935 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006936 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006937 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006938
6939 // Look for constructor templates.
6940 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6941 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6942 if (CXXConstructorDecl *CD =
6943 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6944 return CD;
6945 }
6946
Craig Topperc3ec1492014-05-26 06:22:03 +00006947 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006948}
6949
6950/// The kind of subobject we are checking for triviality. The values of this
6951/// enumeration are used in diagnostics.
6952enum TrivialSubobjectKind {
6953 /// The subobject is a base class.
6954 TSK_BaseClass,
6955 /// The subobject is a non-static data member.
6956 TSK_Field,
6957 /// The object is actually the complete object.
6958 TSK_CompleteObject
6959};
6960
6961/// Check whether the special member selected for a given type would be trivial.
6962static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006963 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006964 Sema::CXXSpecialMember CSM,
6965 TrivialSubobjectKind Kind,
6966 bool Diagnose) {
6967 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6968 if (!SubRD)
6969 return true;
6970
6971 CXXMethodDecl *Selected;
6972 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006973 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006974 return true;
6975
6976 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006977 if (ConstRHS)
6978 SubType.addConst();
6979
Richard Smith92f241f2012-12-08 02:53:02 +00006980 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6981 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6982 << Kind << SubType.getUnqualifiedType();
6983 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6984 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6985 } else if (!Selected)
6986 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6987 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6988 else if (Selected->isUserProvided()) {
6989 if (Kind == TSK_CompleteObject)
6990 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6991 << Kind << SubType.getUnqualifiedType() << CSM;
6992 else {
6993 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6994 << Kind << SubType.getUnqualifiedType() << CSM;
6995 S.Diag(Selected->getLocation(), diag::note_declared_at);
6996 }
6997 } else {
6998 if (Kind != TSK_CompleteObject)
6999 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7000 << Kind << SubType.getUnqualifiedType() << CSM;
7001
7002 // Explain why the defaulted or deleted special member isn't trivial.
7003 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7004 }
7005 }
7006
7007 return false;
7008}
7009
7010/// Check whether the members of a class type allow a special member to be
7011/// trivial.
7012static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7013 Sema::CXXSpecialMember CSM,
7014 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007015 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007016 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7017 continue;
7018
7019 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7020
7021 // Pretend anonymous struct or union members are members of this class.
7022 if (FI->isAnonymousStructOrUnion()) {
7023 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7024 CSM, ConstArg, Diagnose))
7025 return false;
7026 continue;
7027 }
7028
7029 // C++11 [class.ctor]p5:
7030 // A default constructor is trivial if [...]
7031 // -- no non-static data member of its class has a
7032 // brace-or-equal-initializer
7033 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7034 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007035 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007036 return false;
7037 }
7038
7039 // Objective C ARC 4.3.5:
7040 // [...] nontrivally ownership-qualified types are [...] not trivially
7041 // default constructible, copy constructible, move constructible, copy
7042 // assignable, move assignable, or destructible [...]
7043 if (S.getLangOpts().ObjCAutoRefCount &&
7044 FieldType.hasNonTrivialObjCLifetime()) {
7045 if (Diagnose)
7046 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7047 << RD << FieldType.getObjCLifetime();
7048 return false;
7049 }
7050
Richard Smith41c35d62013-11-27 03:39:20 +00007051 bool ConstRHS = ConstArg && !FI->isMutable();
7052 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7053 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007054 return false;
7055 }
7056
7057 return true;
7058}
7059
7060/// Diagnose why the specified class does not have a trivial special member of
7061/// the given kind.
7062void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7063 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007064
Richard Smith41c35d62013-11-27 03:39:20 +00007065 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7066 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007067 TSK_CompleteObject, /*Diagnose*/true);
7068}
7069
7070/// Determine whether a defaulted or deleted special member function is trivial,
7071/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7072/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7073bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7074 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007075 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7076
7077 CXXRecordDecl *RD = MD->getParent();
7078
7079 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007080
Richard Smith2002bfe2013-11-04 02:02:27 +00007081 // C++11 [class.copy]p12, p25: [DR1593]
7082 // A [special member] is trivial if [...] its parameter-type-list is
7083 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007084 switch (CSM) {
7085 case CXXDefaultConstructor:
7086 case CXXDestructor:
7087 // Trivial default constructors and destructors cannot have parameters.
7088 break;
7089
7090 case CXXCopyConstructor:
7091 case CXXCopyAssignment: {
7092 // Trivial copy operations always have const, non-volatile parameter types.
7093 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007094 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007095 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7096 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7097 if (Diagnose)
7098 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7099 << Param0->getSourceRange() << Param0->getType()
7100 << Context.getLValueReferenceType(
7101 Context.getRecordType(RD).withConst());
7102 return false;
7103 }
7104 break;
7105 }
7106
7107 case CXXMoveConstructor:
7108 case CXXMoveAssignment: {
7109 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007110 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007111 const RValueReferenceType *RT =
7112 Param0->getType()->getAs<RValueReferenceType>();
7113 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7114 if (Diagnose)
7115 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7116 << Param0->getSourceRange() << Param0->getType()
7117 << Context.getRValueReferenceType(Context.getRecordType(RD));
7118 return false;
7119 }
7120 break;
7121 }
7122
7123 case CXXInvalid:
7124 llvm_unreachable("not a special member");
7125 }
7126
Richard Smith92f241f2012-12-08 02:53:02 +00007127 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7128 if (Diagnose)
7129 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7130 diag::note_nontrivial_default_arg)
7131 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7132 return false;
7133 }
7134 if (MD->isVariadic()) {
7135 if (Diagnose)
7136 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7137 return false;
7138 }
7139
7140 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7141 // A copy/move [constructor or assignment operator] is trivial if
7142 // -- the [member] selected to copy/move each direct base class subobject
7143 // is trivial
7144 //
7145 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7146 // A [default constructor or destructor] is trivial if
7147 // -- all the direct base classes have trivial [default constructors or
7148 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007149 for (const auto &BI : RD->bases())
7150 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007151 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007152 return false;
7153
7154 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7155 // A copy/move [constructor or assignment operator] for a class X is
7156 // trivial if
7157 // -- for each non-static data member of X that is of class type (or array
7158 // thereof), the constructor selected to copy/move that member is
7159 // trivial
7160 //
7161 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7162 // A [default constructor or destructor] is trivial if
7163 // -- for all of the non-static data members of its class that are of class
7164 // type (or array thereof), each such class has a trivial [default
7165 // constructor or destructor]
7166 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7167 return false;
7168
7169 // C++11 [class.dtor]p5:
7170 // A destructor is trivial if [...]
7171 // -- the destructor is not virtual
7172 if (CSM == CXXDestructor && MD->isVirtual()) {
7173 if (Diagnose)
7174 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7175 return false;
7176 }
7177
7178 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7179 // A [special member] for class X is trivial if [...]
7180 // -- class X has no virtual functions and no virtual base classes
7181 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7182 if (!Diagnose)
7183 return false;
7184
7185 if (RD->getNumVBases()) {
7186 // Check for virtual bases. We already know that the corresponding
7187 // member in all bases is trivial, so vbases must all be direct.
7188 CXXBaseSpecifier &BS = *RD->vbases_begin();
7189 assert(BS.isVirtual());
7190 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7191 return false;
7192 }
7193
7194 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007195 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007196 if (MI->isVirtual()) {
7197 SourceLocation MLoc = MI->getLocStart();
7198 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7199 return false;
7200 }
7201 }
7202
7203 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7204 }
7205
7206 // Looks like it's trivial!
7207 return true;
7208}
7209
Benjamin Kramer024e6192011-03-04 13:12:48 +00007210namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007211struct FindHiddenVirtualMethod {
7212 Sema *S;
7213 CXXMethodDecl *Method;
7214 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7215 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007216
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007217private:
7218 /// Check whether any most overriden method from MD in Methods
7219 static bool CheckMostOverridenMethods(
7220 const CXXMethodDecl *MD,
7221 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7222 if (MD->size_overridden_methods() == 0)
7223 return Methods.count(MD->getCanonicalDecl());
7224 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7225 E = MD->end_overridden_methods();
7226 I != E; ++I)
7227 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007228 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007229 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007230 }
7231
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007232public:
7233 /// Member lookup function that determines whether a given C++
7234 /// method overloads virtual methods in a base class without overriding any,
7235 /// to be used with CXXRecordDecl::lookupInBases().
7236 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7237 RecordDecl *BaseRecord =
7238 Specifier->getType()->getAs<RecordType>()->getDecl();
7239
7240 DeclarationName Name = Method->getDeclName();
7241 assert(Name.getNameKind() == DeclarationName::Identifier);
7242
7243 bool foundSameNameMethod = false;
7244 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7245 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7246 Path.Decls = Path.Decls.slice(1)) {
7247 NamedDecl *D = Path.Decls.front();
7248 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7249 MD = MD->getCanonicalDecl();
7250 foundSameNameMethod = true;
7251 // Interested only in hidden virtual methods.
7252 if (!MD->isVirtual())
7253 continue;
7254 // If the method we are checking overrides a method from its base
7255 // don't warn about the other overloaded methods. Clang deviates from
7256 // GCC by only diagnosing overloads of inherited virtual functions that
7257 // do not override any other virtual functions in the base. GCC's
7258 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7259 // function from a base class. These cases may be better served by a
7260 // warning (not specific to virtual functions) on call sites when the
7261 // call would select a different function from the base class, were it
7262 // visible.
7263 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7264 if (!S->IsOverload(Method, MD, false))
7265 return true;
7266 // Collect the overload only if its hidden.
7267 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7268 overloadedMethods.push_back(MD);
7269 }
7270 }
7271
7272 if (foundSameNameMethod)
7273 OverloadedMethods.append(overloadedMethods.begin(),
7274 overloadedMethods.end());
7275 return foundSameNameMethod;
7276 }
7277};
7278} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007279
David Blaikie282c92a2012-10-19 00:53:08 +00007280/// \brief Add the most overriden methods from MD to Methods
7281static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007282 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007283 if (MD->size_overridden_methods() == 0)
7284 Methods.insert(MD->getCanonicalDecl());
7285 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7286 E = MD->end_overridden_methods();
7287 I != E; ++I)
7288 AddMostOverridenMethods(*I, Methods);
7289}
7290
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007291/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007292/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007293void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7294 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007295 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007296 return;
7297
7298 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7299 /*bool RecordPaths=*/false,
7300 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007301 FindHiddenVirtualMethod FHVM;
7302 FHVM.Method = MD;
7303 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007304
7305 // Keep the base methods that were overriden or introduced in the subclass
7306 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007307 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007308 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7309 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7310 NamedDecl *ND = *I;
7311 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007312 ND = shad->getTargetDecl();
7313 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007314 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007315 }
7316
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007317 if (DC->lookupInBases(FHVM, Paths))
7318 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007319}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007320
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007321void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7322 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7323 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7324 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7325 PartialDiagnostic PD = PDiag(
7326 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7327 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7328 Diag(overloadedMD->getLocation(), PD);
7329 }
7330}
7331
7332/// \brief Diagnose methods which overload virtual methods in a base class
7333/// without overriding any.
7334void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7335 if (MD->isInvalidDecl())
7336 return;
7337
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007338 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007339 return;
7340
7341 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7342 FindHiddenVirtualMethods(MD, OverloadedMethods);
7343 if (!OverloadedMethods.empty()) {
7344 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7345 << MD << (OverloadedMethods.size() > 1);
7346
7347 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007348 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007349}
7350
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007351void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007352 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007353 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007354 SourceLocation RBrac,
7355 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007356 if (!TagDecl)
7357 return;
Mike Stump11289f42009-09-09 15:08:12 +00007358
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007359 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007360
Rafael Espindola06e1b132012-07-12 04:32:30 +00007361 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7362 if (l->getKind() != AttributeList::AT_Visibility)
7363 continue;
7364 l->setInvalid();
7365 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7366 l->getName();
7367 }
7368
David Blaikie751c5582011-09-22 02:58:26 +00007369 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007370 // strict aliasing violation!
7371 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007372 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007373
Douglas Gregor0be31a22010-07-02 17:43:08 +00007374 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007375 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007376}
7377
Douglas Gregor05379422008-11-03 17:51:48 +00007378/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7379/// special functions, such as the default constructor, copy
7380/// constructor, or destructor, to the given C++ class (C++
7381/// [special]p1). This routine can only be executed just before the
7382/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007383void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007384 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007385 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007386
Richard Smith5179eb72016-06-28 19:03:57 +00007387 if (ClassDecl->hasInheritedConstructor())
7388 DeclareImplicitDefaultConstructor(ClassDecl);
7389 }
Richard Smith12e79312016-05-13 06:47:56 +00007390
Richard Smitha87b7662016-05-13 18:48:05 +00007391 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007392 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007393
Richard Smith6b02d462012-12-08 08:32:28 +00007394 // If the properties or semantics of the copy constructor couldn't be
7395 // determined while the class was being declared, force a declaration
7396 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007397 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7398 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007399 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007400 // For the MS ABI we need to know whether the copy ctor is deleted. A
7401 // prerequisite for deleting the implicit copy ctor is that the class has a
7402 // move ctor or move assignment that is either user-declared or whose
7403 // semantics are inherited from a subobject. FIXME: We should provide a more
7404 // direct way for CodeGen to ask whether the constructor was deleted.
7405 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7406 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7407 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7408 ClassDecl->hasUserDeclaredMoveAssignment() ||
7409 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7410 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007411 }
7412
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007413 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007414 ++ASTContext::NumImplicitMoveConstructors;
7415
Richard Smith12e79312016-05-13 06:47:56 +00007416 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7417 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007418 DeclareImplicitMoveConstructor(ClassDecl);
7419 }
7420
Richard Smitha87b7662016-05-13 18:48:05 +00007421 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007422 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007423
7424 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007425 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007426 // it shows up in the right place in the vtable and that we diagnose
7427 // problems with the implicit exception specification.
7428 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007429 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7430 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007431 DeclareImplicitCopyAssignment(ClassDecl);
7432 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007433
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007434 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007435 ++ASTContext::NumImplicitMoveAssignmentOperators;
7436
7437 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007438 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007439 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7440 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007441 DeclareImplicitMoveAssignment(ClassDecl);
7442 }
7443
Richard Smitha87b7662016-05-13 18:48:05 +00007444 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007445 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007446
7447 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007448 // have to declare the destructor immediately. This ensures that, e.g., it
7449 // shows up in the right place in the vtable and that we diagnose problems
7450 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007451 if (ClassDecl->isDynamicClass() ||
7452 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007453 DeclareImplicitDestructor(ClassDecl);
7454 }
Douglas Gregor05379422008-11-03 17:51:48 +00007455}
7456
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007457unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007458 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007459 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007460
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007461 // The order of template parameters is not important here. All names
7462 // get added to the same scope.
7463 SmallVector<TemplateParameterList *, 4> ParameterLists;
7464
7465 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7466 D = TD->getTemplatedDecl();
7467
7468 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7469 ParameterLists.push_back(PSD->getTemplateParameters());
7470
7471 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7472 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7473 ParameterLists.push_back(DD->getTemplateParameterList(i));
7474
7475 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7476 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7477 ParameterLists.push_back(FTD->getTemplateParameters());
7478 }
7479 }
7480
7481 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7482 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7483 ParameterLists.push_back(TD->getTemplateParameterList(i));
7484
7485 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7486 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7487 ParameterLists.push_back(CTD->getTemplateParameters());
7488 }
7489 }
7490
7491 unsigned Count = 0;
7492 for (TemplateParameterList *Params : ParameterLists) {
7493 if (Params->size() > 0)
7494 // Ignore explicit specializations; they don't contribute to the template
7495 // depth.
7496 ++Count;
7497 for (NamedDecl *Param : *Params) {
7498 if (Param->getDeclName()) {
7499 S->AddDecl(Param);
7500 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007501 }
7502 }
7503 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007504
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007505 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007506}
7507
John McCall48871652010-08-21 09:40:31 +00007508void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007509 if (!RecordD) return;
7510 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007511 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007512 PushDeclContext(S, Record);
7513}
7514
John McCall48871652010-08-21 09:40:31 +00007515void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007516 if (!RecordD) return;
7517 PopDeclContext();
7518}
7519
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007520/// This is used to implement the constant expression evaluation part of the
7521/// attribute enable_if extension. There is nothing in standard C++ which would
7522/// require reentering parameters.
7523void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7524 if (!Param)
7525 return;
7526
7527 S->AddDecl(Param);
7528 if (Param->getDeclName())
7529 IdResolver.AddDecl(Param);
7530}
7531
Douglas Gregor4d87df52008-12-16 21:30:33 +00007532/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7533/// parsing a top-level (non-nested) C++ class, and we are now
7534/// parsing those parts of the given Method declaration that could
7535/// not be parsed earlier (C++ [class.mem]p2), such as default
7536/// arguments. This action should enter the scope of the given
7537/// Method declaration as if we had just parsed the qualified method
7538/// name. However, it should not bring the parameters into scope;
7539/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007540void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007541}
7542
7543/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7544/// C++ method declaration. We're (re-)introducing the given
7545/// function parameter into scope for use in parsing later parts of
7546/// the method declaration. For example, we could see an
7547/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007548void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007549 if (!ParamD)
7550 return;
Mike Stump11289f42009-09-09 15:08:12 +00007551
John McCall48871652010-08-21 09:40:31 +00007552 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007553
7554 // If this parameter has an unparsed default argument, clear it out
7555 // to make way for the parsed default argument.
7556 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007557 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007558
John McCall48871652010-08-21 09:40:31 +00007559 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007560 if (Param->getDeclName())
7561 IdResolver.AddDecl(Param);
7562}
7563
7564/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7565/// processing the delayed method declaration for Method. The method
7566/// declaration is now considered finished. There may be a separate
7567/// ActOnStartOfFunctionDef action later (not necessarily
7568/// immediately!) for this method, if it was also defined inside the
7569/// class body.
John McCall48871652010-08-21 09:40:31 +00007570void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007571 if (!MethodD)
7572 return;
Mike Stump11289f42009-09-09 15:08:12 +00007573
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007574 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007575
John McCall48871652010-08-21 09:40:31 +00007576 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007577
7578 // Now that we have our default arguments, check the constructor
7579 // again. It could produce additional diagnostics or affect whether
7580 // the class has implicitly-declared destructors, among other
7581 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007582 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7583 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007584
7585 // Check the default arguments, which we may have added.
7586 if (!Method->isInvalidDecl())
7587 CheckCXXDefaultArguments(Method);
7588}
7589
Douglas Gregor831c93f2008-11-05 20:51:48 +00007590/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007591/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007592/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007593/// emit diagnostics and set the invalid bit to true. In any case, the type
7594/// will be updated to reflect a well-formed type for the constructor and
7595/// returned.
7596QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007597 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007598 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007599
7600 // C++ [class.ctor]p3:
7601 // A constructor shall not be virtual (10.3) or static (9.4). A
7602 // constructor can be invoked for a const, volatile or const
7603 // volatile object. A constructor shall not be declared const,
7604 // volatile, or const volatile (9.3.2).
7605 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007606 if (!D.isInvalidType())
7607 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7608 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7609 << SourceRange(D.getIdentifierLoc());
7610 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007611 }
John McCall8e7d6562010-08-26 03:08:43 +00007612 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007613 if (!D.isInvalidType())
7614 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7615 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7616 << SourceRange(D.getIdentifierLoc());
7617 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007618 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007619 }
Mike Stump11289f42009-09-09 15:08:12 +00007620
David Majnemer03f705f2014-07-08 18:18:04 +00007621 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7622 diagnoseIgnoredQualifiers(
7623 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7624 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7625 D.getDeclSpec().getRestrictSpecLoc(),
7626 D.getDeclSpec().getAtomicSpecLoc());
7627 D.setInvalidType();
7628 }
7629
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007630 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007631 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007632 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007633 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7634 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007635 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007636 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7637 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007638 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007639 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7640 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007641 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007642 }
Mike Stump11289f42009-09-09 15:08:12 +00007643
Douglas Gregordb9d6642011-01-26 05:01:58 +00007644 // C++0x [class.ctor]p4:
7645 // A constructor shall not be declared with a ref-qualifier.
7646 if (FTI.hasRefQualifier()) {
7647 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7648 << FTI.RefQualifierIsLValueRef
7649 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7650 D.setInvalidType();
7651 }
7652
Douglas Gregor831c93f2008-11-05 20:51:48 +00007653 // Rebuild the function type "R" without any type qualifiers (in
7654 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007655 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007656 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007657 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007658 return R;
7659
7660 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7661 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007662 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007663
7664 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007665}
7666
Douglas Gregor4d87df52008-12-16 21:30:33 +00007667/// CheckConstructor - Checks a fully-formed constructor for
7668/// well-formedness, issuing any diagnostics required. Returns true if
7669/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007670void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007671 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007672 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7673 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007674 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007675
7676 // C++ [class.copy]p3:
7677 // A declaration of a constructor for a class X is ill-formed if
7678 // its first parameter is of type (optionally cv-qualified) X and
7679 // either there are no other parameters or else all other
7680 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007681 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007682 ((Constructor->getNumParams() == 1) ||
7683 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007684 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7685 Constructor->getTemplateSpecializationKind()
7686 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007687 QualType ParamType = Constructor->getParamDecl(0)->getType();
7688 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7689 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007690 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007691 const char *ConstRef
7692 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7693 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007694 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007695 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007696
7697 // FIXME: Rather that making the constructor invalid, we should endeavor
7698 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007699 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007700 }
7701 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007702}
7703
John McCalldeb646e2010-08-04 01:04:25 +00007704/// CheckDestructor - Checks a fully-formed destructor definition for
7705/// well-formedness, issuing any diagnostics required. Returns true
7706/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007707bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007708 CXXRecordDecl *RD = Destructor->getParent();
7709
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007710 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007711 SourceLocation Loc;
7712
7713 if (!Destructor->isImplicit())
7714 Loc = Destructor->getLocation();
7715 else
7716 Loc = RD->getLocation();
7717
7718 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007719 if (FunctionDecl *OperatorDelete =
7720 FindDeallocationFunctionForDestructor(Loc, RD)) {
7721 MarkFunctionReferenced(Loc, OperatorDelete);
7722 Destructor->setOperatorDelete(OperatorDelete);
7723 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007724 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007725
7726 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007727}
7728
Douglas Gregor831c93f2008-11-05 20:51:48 +00007729/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7730/// the well-formednes of the destructor declarator @p D with type @p
7731/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007732/// emit diagnostics and set the declarator to invalid. Even if this happens,
7733/// will be updated to reflect a well-formed type for the destructor and
7734/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007735QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007736 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007737 // C++ [class.dtor]p1:
7738 // [...] A typedef-name that names a class is a class-name
7739 // (7.1.3); however, a typedef-name that names a class shall not
7740 // be used as the identifier in the declarator for a destructor
7741 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007742 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007743 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007744 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007745 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007746 else if (const TemplateSpecializationType *TST =
7747 DeclaratorType->getAs<TemplateSpecializationType>())
7748 if (TST->isTypeAlias())
7749 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7750 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007751
7752 // C++ [class.dtor]p2:
7753 // A destructor is used to destroy objects of its class type. A
7754 // destructor takes no parameters, and no return type can be
7755 // specified for it (not even void). The address of a destructor
7756 // shall not be taken. A destructor shall not be static. A
7757 // destructor can be invoked for a const, volatile or const
7758 // volatile object. A destructor shall not be declared const,
7759 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007760 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007761 if (!D.isInvalidType())
7762 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7763 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007764 << SourceRange(D.getIdentifierLoc())
7765 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7766
John McCall8e7d6562010-08-26 03:08:43 +00007767 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007768 }
David Majnemer03f705f2014-07-08 18:18:04 +00007769 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007770 // Destructors don't have return types, but the parser will
7771 // happily parse something like:
7772 //
7773 // class X {
7774 // float ~X();
7775 // };
7776 //
7777 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007778 if (D.getDeclSpec().hasTypeSpecifier())
7779 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7780 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7781 << SourceRange(D.getIdentifierLoc());
7782 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7783 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7784 SourceLocation(),
7785 D.getDeclSpec().getConstSpecLoc(),
7786 D.getDeclSpec().getVolatileSpecLoc(),
7787 D.getDeclSpec().getRestrictSpecLoc(),
7788 D.getDeclSpec().getAtomicSpecLoc());
7789 D.setInvalidType();
7790 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007791 }
Mike Stump11289f42009-09-09 15:08:12 +00007792
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007793 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007794 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007795 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007796 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7797 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007798 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007799 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7800 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007801 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007802 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7803 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007804 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007805 }
7806
Douglas Gregordb9d6642011-01-26 05:01:58 +00007807 // C++0x [class.dtor]p2:
7808 // A destructor shall not be declared with a ref-qualifier.
7809 if (FTI.hasRefQualifier()) {
7810 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7811 << FTI.RefQualifierIsLValueRef
7812 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7813 D.setInvalidType();
7814 }
7815
Douglas Gregor831c93f2008-11-05 20:51:48 +00007816 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007817 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007818 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7819
7820 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007821 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007822 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007823 }
7824
Mike Stump11289f42009-09-09 15:08:12 +00007825 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007826 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007827 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007828 D.setInvalidType();
7829 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007830
7831 // Rebuild the function type "R" without any type qualifiers or
7832 // parameters (in case any of the errors above fired) and with
7833 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007834 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007835 if (!D.isInvalidType())
7836 return R;
7837
Douglas Gregor95755162010-07-01 05:10:53 +00007838 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007839 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7840 EPI.Variadic = false;
7841 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007842 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007843 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007844}
7845
Craig Toppere335f252015-10-04 04:53:55 +00007846static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007847 if (Before.isInvalid())
7848 return;
7849 R.setBegin(Before.getBegin());
7850 if (R.getEnd().isInvalid())
7851 R.setEnd(Before.getEnd());
7852}
7853
Craig Toppere335f252015-10-04 04:53:55 +00007854static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007855 if (After.isInvalid())
7856 return;
7857 if (R.getBegin().isInvalid())
7858 R.setBegin(After.getBegin());
7859 R.setEnd(After.getEnd());
7860}
7861
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007862/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7863/// well-formednes of the conversion function declarator @p D with
7864/// type @p R. If there are any errors in the declarator, this routine
7865/// will emit diagnostics and return true. Otherwise, it will return
7866/// false. Either way, the type @p R will be updated to reflect a
7867/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007868void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007869 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007870 // C++ [class.conv.fct]p1:
7871 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007872 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007873 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007874 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007875 if (!D.isInvalidType())
7876 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007877 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7878 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007879 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007880 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007881 }
John McCall212fa2e2010-04-13 00:04:31 +00007882
Richard Smitha865a162014-12-19 02:07:47 +00007883 TypeSourceInfo *ConvTSI = nullptr;
7884 QualType ConvType =
7885 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007886
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007887 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007888 // Conversion functions don't have return types, but the parser will
7889 // happily parse something like:
7890 //
7891 // class X {
7892 // float operator bool();
7893 // };
7894 //
7895 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00007896 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7897 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7898 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00007899 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007900 }
7901
John McCall212fa2e2010-04-13 00:04:31 +00007902 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7903
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007904 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00007905 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007906 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7907
7908 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007909 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007910 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00007911 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007912 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007913 D.setInvalidType();
7914 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007915
John McCall212fa2e2010-04-13 00:04:31 +00007916 // Diagnose "&operator bool()" and other such nonsense. This
7917 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007918 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007919 bool NeedsTypedef = false;
7920 SourceRange Before, After;
7921
7922 // Walk the chunks and extract information on them for our diagnostic.
7923 bool PastFunctionChunk = false;
7924 for (auto &Chunk : D.type_objects()) {
7925 switch (Chunk.Kind) {
7926 case DeclaratorChunk::Function:
7927 if (!PastFunctionChunk) {
7928 if (Chunk.Fun.HasTrailingReturnType) {
7929 TypeSourceInfo *TRT = nullptr;
7930 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7931 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7932 }
7933 PastFunctionChunk = true;
7934 break;
7935 }
7936 // Fall through.
7937 case DeclaratorChunk::Array:
7938 NeedsTypedef = true;
7939 extendRight(After, Chunk.getSourceRange());
7940 break;
7941
7942 case DeclaratorChunk::Pointer:
7943 case DeclaratorChunk::BlockPointer:
7944 case DeclaratorChunk::Reference:
7945 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007946 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007947 extendLeft(Before, Chunk.getSourceRange());
7948 break;
7949
7950 case DeclaratorChunk::Paren:
7951 extendLeft(Before, Chunk.Loc);
7952 extendRight(After, Chunk.EndLoc);
7953 break;
7954 }
7955 }
7956
7957 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7958 After.isValid() ? After.getBegin() :
7959 D.getIdentifierLoc();
7960 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7961 DB << Before << After;
7962
7963 if (!NeedsTypedef) {
7964 DB << /*don't need a typedef*/0;
7965
7966 // If we can provide a correct fix-it hint, do so.
7967 if (After.isInvalid() && ConvTSI) {
7968 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007969 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007970 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7971 << FixItHint::CreateInsertionFromRange(
7972 InsertLoc, CharSourceRange::getTokenRange(Before))
7973 << FixItHint::CreateRemoval(Before);
7974 }
7975 } else if (!Proto->getReturnType()->isDependentType()) {
7976 DB << /*typedef*/1 << Proto->getReturnType();
7977 } else if (getLangOpts().CPlusPlus11) {
7978 DB << /*alias template*/2 << Proto->getReturnType();
7979 } else {
7980 DB << /*might not be fixable*/3;
7981 }
7982
7983 // Recover by incorporating the other type chunks into the result type.
7984 // Note, this does *not* change the name of the function. This is compatible
7985 // with the GCC extension:
7986 // struct S { &operator int(); } s;
7987 // int &r = s.operator int(); // ok in GCC
7988 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007989 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007990 }
7991
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007992 // C++ [class.conv.fct]p4:
7993 // The conversion-type-id shall not represent a function type nor
7994 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007995 if (ConvType->isArrayType()) {
7996 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7997 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007998 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007999 } else if (ConvType->isFunctionType()) {
8000 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8001 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008002 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008003 }
8004
8005 // Rebuild the function type "R" without any parameters (in case any
8006 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00008007 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00008008 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008009 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008010
Douglas Gregor5fb53972009-01-14 15:45:31 +00008011 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00008012 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008013 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008014 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008015 diag::warn_cxx98_compat_explicit_conversion_functions :
8016 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008017 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008018}
8019
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008020/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8021/// the declaration of the given C++ conversion function. This routine
8022/// is responsible for recording the conversion function in the C++
8023/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008024Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008025 assert(Conversion && "Expected to receive a conversion function declaration");
8026
Douglas Gregor4287b372008-12-12 08:25:50 +00008027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008028
8029 // Make sure we aren't redeclaring the conversion function.
8030 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008031
8032 // C++ [class.conv.fct]p1:
8033 // [...] A conversion function is never used to convert a
8034 // (possibly cv-qualified) object to the (possibly cv-qualified)
8035 // same object type (or a reference to it), to a (possibly
8036 // cv-qualified) base class of that type (or a reference to it),
8037 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008038 // FIXME: Suppress this warning if the conversion function ends up being a
8039 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008040 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008041 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008042 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008043 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008044 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8045 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008046 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008047 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008048 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8049 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008050 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008051 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008052 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008053 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008054 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008055 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008056 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008057 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008058 }
8059
Douglas Gregor457104e2010-09-29 04:25:11 +00008060 if (FunctionTemplateDecl *ConversionTemplate
8061 = Conversion->getDescribedFunctionTemplate())
8062 return ConversionTemplate;
8063
John McCall48871652010-08-21 09:40:31 +00008064 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008065}
8066
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008067//===----------------------------------------------------------------------===//
8068// Namespace Handling
8069//===----------------------------------------------------------------------===//
8070
Richard Smith45bb8852012-10-04 22:13:39 +00008071/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8072/// reopened.
8073static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8074 SourceLocation Loc,
8075 IdentifierInfo *II, bool *IsInline,
8076 NamespaceDecl *PrevNS) {
8077 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008078
Richard Smithf501cc32012-10-05 01:46:25 +00008079 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8080 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8081 // inline namespaces, with the intention of bringing names into namespace std.
8082 //
8083 // We support this just well enough to get that case working; this is not
8084 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008085 if (*IsInline && II && II->getName().startswith("__atomic") &&
8086 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008087 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008088 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8089 NS = NS->getPreviousDecl())
8090 NS->setInline(*IsInline);
8091 // Patch up the lookup table for the containing namespace. This isn't really
8092 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008093 for (auto *I : PrevNS->decls())
8094 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008095 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8096 return;
8097 }
8098
8099 if (PrevNS->isInline())
8100 // The user probably just forgot the 'inline', so suggest that it
8101 // be added back.
8102 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8103 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8104 else
Richard Smith360cb252016-09-30 23:16:08 +00008105 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008106
8107 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8108 *IsInline = PrevNS->isInline();
8109}
John McCallb1be5232010-08-26 09:15:37 +00008110
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008111/// ActOnStartNamespaceDef - This is called at the start of a namespace
8112/// definition.
John McCall48871652010-08-21 09:40:31 +00008113Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008114 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008115 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008116 SourceLocation IdentLoc,
8117 IdentifierInfo *II,
8118 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008119 AttributeList *AttrList,
8120 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008121 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8122 // For anonymous namespace, take the location of the left brace.
8123 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008124 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008125 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008126 bool IsStd = false;
8127 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008128 Scope *DeclRegionScope = NamespcScope->getParent();
8129
Craig Topperc3ec1492014-05-26 06:22:03 +00008130 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008131 if (II) {
8132 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008133 // The identifier in an original-namespace-definition shall not
8134 // have been previously defined in the declarative region in
8135 // which the original-namespace-definition appears. The
8136 // identifier in an original-namespace-definition is the name of
8137 // the namespace. Subsequently in that declarative region, it is
8138 // treated as an original-namespace-name.
8139 //
8140 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008141 // look through using directives, just look for any ordinary names
8142 // as if by qualified name lookup.
8143 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8144 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008145 NamedDecl *PrevDecl =
8146 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008147 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008148
Douglas Gregore57e7522012-01-07 09:11:48 +00008149 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008150 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008151 if (IsInline != PrevNS->isInline())
8152 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8153 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008154 } else if (PrevDecl) {
8155 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008156 Diag(Loc, diag::err_redefinition_different_kind)
8157 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008158 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008159 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008160 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008161 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008162 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008163 // This is the first "real" definition of the namespace "std", so update
8164 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008165 PrevNS = getStdNamespace();
8166 IsStd = true;
8167 AddToKnown = !IsInline;
8168 } else {
8169 // We've seen this namespace for the first time.
8170 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008171 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008172 } else {
John McCall4fa53422009-10-01 00:25:31 +00008173 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008174
8175 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008176 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008177 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008178 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008179 } else {
8180 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008181 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008182 }
8183
Richard Smith45bb8852012-10-04 22:13:39 +00008184 if (PrevNS && IsInline != PrevNS->isInline())
8185 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8186 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008187 }
8188
8189 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8190 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008191 if (IsInvalid)
8192 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008193
8194 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008195
Douglas Gregore57e7522012-01-07 09:11:48 +00008196 // FIXME: Should we be merging attributes?
8197 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008198 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008199
8200 if (IsStd)
8201 StdNamespace = Namespc;
8202 if (AddToKnown)
8203 KnownNamespaces[Namespc] = false;
8204
8205 if (II) {
8206 PushOnScopeChains(Namespc, DeclRegionScope);
8207 } else {
8208 // Link the anonymous namespace into its parent.
8209 DeclContext *Parent = CurContext->getRedeclContext();
8210 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8211 TU->setAnonymousNamespace(Namespc);
8212 } else {
8213 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008214 }
John McCall4fa53422009-10-01 00:25:31 +00008215
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008216 CurContext->addDecl(Namespc);
8217
John McCall4fa53422009-10-01 00:25:31 +00008218 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8219 // behaves as if it were replaced by
8220 // namespace unique { /* empty body */ }
8221 // using namespace unique;
8222 // namespace unique { namespace-body }
8223 // where all occurrences of 'unique' in a translation unit are
8224 // replaced by the same identifier and this identifier differs
8225 // from all other identifiers in the entire program.
8226
8227 // We just create the namespace with an empty name and then add an
8228 // implicit using declaration, just like the standard suggests.
8229 //
8230 // CodeGen enforces the "universally unique" aspect by giving all
8231 // declarations semantically contained within an anonymous
8232 // namespace internal linkage.
8233
Douglas Gregore57e7522012-01-07 09:11:48 +00008234 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008235 UD = UsingDirectiveDecl::Create(Context, Parent,
8236 /* 'using' */ LBrace,
8237 /* 'namespace' */ SourceLocation(),
8238 /* qualifier */ NestedNameSpecifierLoc(),
8239 /* identifier */ SourceLocation(),
8240 Namespc,
8241 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008242 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008243 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008244 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008245 }
8246
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008247 ActOnDocumentableDecl(Namespc);
8248
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008249 // Although we could have an invalid decl (i.e. the namespace name is a
8250 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008251 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8252 // for the namespace has the declarations that showed up in that particular
8253 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008254 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008255 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008256}
8257
Sebastian Redla6602e92009-11-23 15:34:23 +00008258/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8259/// is a namespace alias, returns the namespace it points to.
8260static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8261 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8262 return AD->getNamespace();
8263 return dyn_cast_or_null<NamespaceDecl>(D);
8264}
8265
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008266/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8267/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008268void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008269 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8270 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008271 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008272 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008273 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008274 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008275}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008276
John McCall28a0cf72010-08-25 07:42:41 +00008277CXXRecordDecl *Sema::getStdBadAlloc() const {
8278 return cast_or_null<CXXRecordDecl>(
8279 StdBadAlloc.get(Context.getExternalSource()));
8280}
8281
Richard Smith96269c52016-09-29 22:49:46 +00008282EnumDecl *Sema::getStdAlignValT() const {
8283 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8284}
8285
John McCall28a0cf72010-08-25 07:42:41 +00008286NamespaceDecl *Sema::getStdNamespace() const {
8287 return cast_or_null<NamespaceDecl>(
8288 StdNamespace.get(Context.getExternalSource()));
8289}
8290
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008291NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8292 if (!StdExperimentalNamespaceCache) {
8293 if (auto Std = getStdNamespace()) {
8294 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8295 SourceLocation(), LookupNamespaceName);
8296 if (!LookupQualifiedName(Result, Std) ||
8297 !(StdExperimentalNamespaceCache =
8298 Result.getAsSingle<NamespaceDecl>()))
8299 Result.suppressDiagnostics();
8300 }
8301 }
8302 return StdExperimentalNamespaceCache;
8303}
8304
Douglas Gregorcdf87022010-06-29 17:53:46 +00008305/// \brief Retrieve the special "std" namespace, which may require us to
8306/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008307NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008308 if (!StdNamespace) {
8309 // The "std" namespace has not yet been defined, so build one implicitly.
8310 StdNamespace = NamespaceDecl::Create(Context,
8311 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008312 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008313 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008314 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008315 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008316 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008317 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008318
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008319 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008320}
8321
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008322bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008323 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008324 "Looking for std::initializer_list outside of C++.");
8325
8326 // We're looking for implicit instantiations of
8327 // template <typename E> class std::initializer_list.
8328
8329 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8330 return false;
8331
Craig Topperc3ec1492014-05-26 06:22:03 +00008332 ClassTemplateDecl *Template = nullptr;
8333 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008334
Sebastian Redl43144e72012-01-17 22:49:58 +00008335 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008336
Sebastian Redl43144e72012-01-17 22:49:58 +00008337 ClassTemplateSpecializationDecl *Specialization =
8338 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8339 if (!Specialization)
8340 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008341
Sebastian Redl43144e72012-01-17 22:49:58 +00008342 Template = Specialization->getSpecializedTemplate();
8343 Arguments = Specialization->getTemplateArgs().data();
8344 } else if (const TemplateSpecializationType *TST =
8345 Ty->getAs<TemplateSpecializationType>()) {
8346 Template = dyn_cast_or_null<ClassTemplateDecl>(
8347 TST->getTemplateName().getAsTemplateDecl());
8348 Arguments = TST->getArgs();
8349 }
8350 if (!Template)
8351 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008352
8353 if (!StdInitializerList) {
8354 // Haven't recognized std::initializer_list yet, maybe this is it.
8355 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8356 if (TemplateClass->getIdentifier() !=
8357 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008358 !getStdNamespace()->InEnclosingNamespaceSetOf(
8359 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008360 return false;
8361 // This is a template called std::initializer_list, but is it the right
8362 // template?
8363 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008364 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008365 return false;
8366 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8367 return false;
8368
8369 // It's the right template.
8370 StdInitializerList = Template;
8371 }
8372
Richard Smith7d7dee72015-02-24 03:30:14 +00008373 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008374 return false;
8375
8376 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008377 if (Element)
8378 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008379 return true;
8380}
8381
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008382static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8383 NamespaceDecl *Std = S.getStdNamespace();
8384 if (!Std) {
8385 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008386 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008387 }
8388
8389 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8390 Loc, Sema::LookupOrdinaryName);
8391 if (!S.LookupQualifiedName(Result, Std)) {
8392 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008393 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008394 }
8395 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8396 if (!Template) {
8397 Result.suppressDiagnostics();
8398 // We found something weird. Complain about the first thing we found.
8399 NamedDecl *Found = *Result.begin();
8400 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008401 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008402 }
8403
8404 // We found some template called std::initializer_list. Now verify that it's
8405 // correct.
8406 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008407 if (Params->getMinRequiredArguments() != 1 ||
8408 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008409 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008410 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008411 }
8412
8413 return Template;
8414}
8415
8416QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8417 if (!StdInitializerList) {
8418 StdInitializerList = LookupStdInitializerList(*this, Loc);
8419 if (!StdInitializerList)
8420 return QualType();
8421 }
8422
8423 TemplateArgumentListInfo Args(Loc, Loc);
8424 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8425 Context.getTrivialTypeSourceInfo(Element,
8426 Loc)));
8427 return Context.getCanonicalType(
8428 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8429}
8430
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008431bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8432 // C++ [dcl.init.list]p2:
8433 // A constructor is an initializer-list constructor if its first parameter
8434 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8435 // std::initializer_list<E> for some type E, and either there are no other
8436 // parameters or else all other parameters have default arguments.
8437 if (Ctor->getNumParams() < 1 ||
8438 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8439 return false;
8440
8441 QualType ArgType = Ctor->getParamDecl(0)->getType();
8442 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8443 ArgType = RT->getPointeeType().getUnqualifiedType();
8444
Craig Topperc3ec1492014-05-26 06:22:03 +00008445 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008446}
8447
Douglas Gregora172e082011-03-26 22:25:30 +00008448/// \brief Determine whether a using statement is in a context where it will be
8449/// apply in all contexts.
8450static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8451 switch (CurContext->getDeclKind()) {
8452 case Decl::TranslationUnit:
8453 return true;
8454 case Decl::LinkageSpec:
8455 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8456 default:
8457 return false;
8458 }
8459}
8460
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008461namespace {
8462
8463// Callback to only accept typo corrections that are namespaces.
8464class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008465public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008466 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008467 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008468 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008469 return false;
8470 }
8471};
8472
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008473}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008474
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008475static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8476 CXXScopeSpec &SS,
8477 SourceLocation IdentLoc,
8478 IdentifierInfo *Ident) {
8479 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008480 if (TypoCorrection Corrected =
8481 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8482 llvm::make_unique<NamespaceValidatorCCC>(),
8483 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008484 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008485 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8486 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008487 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008488 S.diagnoseTypo(Corrected,
8489 S.PDiag(diag::err_using_directive_member_suggest)
8490 << Ident << DC << DroppedSpecifier << SS.getRange(),
8491 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008492 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008493 S.diagnoseTypo(Corrected,
8494 S.PDiag(diag::err_using_directive_suggest) << Ident,
8495 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008496 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008497 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008498 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008499 }
8500 return false;
8501}
8502
John McCall48871652010-08-21 09:40:31 +00008503Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008504 SourceLocation UsingLoc,
8505 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008506 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008507 SourceLocation IdentLoc,
8508 IdentifierInfo *NamespcName,
8509 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008510 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8511 assert(NamespcName && "Invalid NamespcName.");
8512 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008513
8514 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008515 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008516 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008517 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008518
Craig Topperc3ec1492014-05-26 06:22:03 +00008519 UsingDirectiveDecl *UDir = nullptr;
8520 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008521 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008522 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008523
Douglas Gregor34074322009-01-14 22:20:51 +00008524 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008525 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8526 LookupParsedName(R, S, &SS);
8527 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008528 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008529
Douglas Gregorcdf87022010-06-29 17:53:46 +00008530 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008531 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008532 // Allow "using namespace std;" or "using namespace ::std;" even if
8533 // "std" hasn't been defined yet, for GCC compatibility.
8534 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8535 NamespcName->isStr("std")) {
8536 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008537 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008538 R.resolveKind();
8539 }
8540 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008541 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008542 }
8543
John McCall9f3059a2009-10-09 21:13:30 +00008544 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008545 NamedDecl *Named = R.getRepresentativeDecl();
8546 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8547 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008548
Nico Riecke50e59a2014-11-24 17:29:52 +00008549 // The use of a nested name specifier may trigger deprecation warnings.
8550 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008551
Douglas Gregor889ceb72009-02-03 19:21:40 +00008552 // C++ [namespace.udir]p1:
8553 // A using-directive specifies that the names in the nominated
8554 // namespace can be used in the scope in which the
8555 // using-directive appears after the using-directive. During
8556 // unqualified name lookup (3.4.1), the names appear as if they
8557 // were declared in the nearest enclosing namespace which
8558 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008559 // namespace. [Note: in this context, "contains" means "contains
8560 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008561
8562 // Find enclosing context containing both using-directive and
8563 // nominated namespace.
8564 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8565 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8566 CommonAncestor = CommonAncestor->getParent();
8567
Sebastian Redla6602e92009-11-23 15:34:23 +00008568 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008569 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008570 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008571
Douglas Gregora172e082011-03-26 22:25:30 +00008572 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008573 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008574 Diag(IdentLoc, diag::warn_using_directive_in_header);
8575 }
8576
Douglas Gregor889ceb72009-02-03 19:21:40 +00008577 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008578 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008579 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008580 }
8581
Richard Smith54ecd982013-02-20 19:22:51 +00008582 if (UDir)
8583 ProcessDeclAttributeList(S, UDir, AttrList);
8584
John McCall48871652010-08-21 09:40:31 +00008585 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008586}
8587
8588void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008589 // If the scope has an associated entity and the using directive is at
8590 // namespace or translation unit scope, add the UsingDirectiveDecl into
8591 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008592 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008593 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008594 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008595 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008596 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008597 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008598 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008599}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008600
Douglas Gregorfec52632009-06-20 00:51:54 +00008601
John McCall48871652010-08-21 09:40:31 +00008602Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008603 AccessSpecifier AS,
8604 bool HasUsingKeyword,
8605 SourceLocation UsingLoc,
8606 CXXScopeSpec &SS,
8607 UnqualifiedId &Name,
8608 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008609 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00008610 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008611 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008612
Douglas Gregor220f4272009-11-04 16:30:06 +00008613 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008614 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008615 case UnqualifiedId::IK_Identifier:
8616 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008617 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008618 case UnqualifiedId::IK_ConversionFunctionId:
8619 break;
8620
8621 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008622 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008623 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008624 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008625 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008626 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008627 diag::err_using_decl_constructor)
8628 << SS.getRange();
8629
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008630 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008631
Craig Topperc3ec1492014-05-26 06:22:03 +00008632 return nullptr;
8633
Douglas Gregor220f4272009-11-04 16:30:06 +00008634 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008635 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008636 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008637 return nullptr;
8638
Douglas Gregor220f4272009-11-04 16:30:06 +00008639 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008640 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008641 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008642 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00008643 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008644
8645 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8646 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008647 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008648 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008649
Richard Smithc2bc61b2013-03-18 21:12:30 +00008650 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00008651 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008652 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008653 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8654 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008655 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008656 }
8657
Douglas Gregorc4356532010-12-16 00:46:58 +00008658 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8659 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00008660 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00008661
John McCall3f746822009-11-17 05:59:44 +00008662 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008663 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008664 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008665 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00008666 if (UD)
8667 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008668
John McCall48871652010-08-21 09:40:31 +00008669 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008670}
8671
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008672/// \brief Determine whether a using declaration considers the given
8673/// declarations as "equivalent", e.g., if they are redeclarations of
8674/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008675static bool
8676IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8677 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008678 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008679
Richard Smithdda56e42011-04-15 14:24:37 +00008680 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008681 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008682 return Context.hasSameType(TD1->getUnderlyingType(),
8683 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008684
8685 return false;
8686}
8687
8688
John McCall84d87672009-12-10 09:41:52 +00008689/// Determines whether to create a using shadow decl for a particular
8690/// decl, given the set of decls existing prior to this using lookup.
8691bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008692 const LookupResult &Previous,
8693 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008694 // Diagnose finding a decl which is not from a base class of the
8695 // current class. We do this now because there are cases where this
8696 // function will silently decide not to build a shadow decl, which
8697 // will pre-empt further diagnostics.
8698 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008699 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008700 // the qualifier.
8701 //
8702 // FIXME: diagnose the following if we care enough:
8703 // struct A { int foo; };
8704 // struct B : A { using A::foo; };
8705 // template <class T> struct C : A {};
8706 // template <class T> struct D : C<T> { using B::foo; } // <---
8707 // This is invalid (during instantiation) in C++03 because B::foo
8708 // resolves to the using decl in B, which is not a base class of D<T>.
8709 // We can't diagnose it immediately because C<T> is an unknown
8710 // specialization. The UsingShadowDecl in D<T> then points directly
8711 // to A::foo, which will look well-formed when we instantiate.
8712 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008713 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008714 DeclContext *OrigDC = Orig->getDeclContext();
8715
8716 // Handle enums and anonymous structs.
8717 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8718 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8719 while (OrigRec->isAnonymousStructOrUnion())
8720 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8721
8722 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8723 if (OrigDC == CurContext) {
8724 Diag(Using->getLocation(),
8725 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008726 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008727 Diag(Orig->getLocation(), diag::note_using_decl_target);
8728 return true;
8729 }
8730
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008731 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00008732 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008733 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00008734 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008735 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008736 Diag(Orig->getLocation(), diag::note_using_decl_target);
8737 return true;
8738 }
8739 }
8740
8741 if (Previous.empty()) return false;
8742
8743 NamedDecl *Target = Orig;
8744 if (isa<UsingShadowDecl>(Target))
8745 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8746
John McCalla17e83e2009-12-11 02:33:26 +00008747 // If the target happens to be one of the previous declarations, we
8748 // don't have a conflict.
8749 //
8750 // FIXME: but we might be increasing its access, in which case we
8751 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008752 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008753 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00008754 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8755 I != E; ++I) {
8756 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00008757 // We can have UsingDecls in our Previous results because we use the same
8758 // LookupResult for checking whether the UsingDecl itself is a valid
8759 // redeclaration.
8760 if (isa<UsingDecl>(D))
8761 continue;
8762
Richard Smithfd8634a2013-10-23 02:17:46 +00008763 if (IsEquivalentForUsingDecl(Context, D, Target)) {
8764 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8765 PrevShadow = Shadow;
8766 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00008767 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8768 // We don't conflict with an existing using shadow decl of an equivalent
8769 // declaration, but we're not a redeclaration of it.
8770 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00008771 }
John McCalla17e83e2009-12-11 02:33:26 +00008772
Richard Smithf091e122015-09-15 01:28:55 +00008773 if (isVisible(D))
8774 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00008775 }
8776
Richard Smithfd8634a2013-10-23 02:17:46 +00008777 if (FoundEquivalentDecl)
8778 return false;
8779
Alp Tokera2794f92014-01-22 07:29:52 +00008780 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008781 NamedDecl *OldDecl = nullptr;
8782 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8783 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00008784 case Ovl_Overload:
8785 return false;
8786
8787 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00008788 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008789 break;
Richard Smith18819302014-02-06 01:31:33 +00008790
John McCall84d87672009-12-10 09:41:52 +00008791 // We found a decl with the exact signature.
8792 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00008793 // If we're in a record, we want to hide the target, so we
8794 // return true (without a diagnostic) to tell the caller not to
8795 // build a shadow decl.
8796 if (CurContext->isRecord())
8797 return true;
8798
8799 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00008800 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008801 break;
8802 }
8803
8804 Diag(Target->getLocation(), diag::note_using_decl_target);
8805 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8806 return true;
8807 }
8808
8809 // Target is not a function.
8810
John McCall84d87672009-12-10 09:41:52 +00008811 if (isa<TagDecl>(Target)) {
8812 // No conflict between a tag and a non-tag.
8813 if (!Tag) return false;
8814
John McCalle29c5cd2009-12-10 19:51:03 +00008815 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008816 Diag(Target->getLocation(), diag::note_using_decl_target);
8817 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8818 return true;
8819 }
8820
8821 // No conflict between a tag and a non-tag.
8822 if (!NonTag) return false;
8823
John McCalle29c5cd2009-12-10 19:51:03 +00008824 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008825 Diag(Target->getLocation(), diag::note_using_decl_target);
8826 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8827 return true;
8828}
8829
Richard Smith5179eb72016-06-28 19:03:57 +00008830/// Determine whether a direct base class is a virtual base class.
8831static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8832 if (!Derived->getNumVBases())
8833 return false;
8834 for (auto &B : Derived->bases())
8835 if (B.getType()->getAsCXXRecordDecl() == Base)
8836 return B.isVirtual();
8837 llvm_unreachable("not a direct base class");
8838}
8839
John McCall3f746822009-11-17 05:59:44 +00008840/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00008841UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00008842 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00008843 NamedDecl *Orig,
8844 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00008845 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00008846 NamedDecl *Target = Orig;
8847 if (isa<UsingShadowDecl>(Target)) {
8848 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8849 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00008850 }
Richard Smithfd8634a2013-10-23 02:17:46 +00008851
Richard Smith5179eb72016-06-28 19:03:57 +00008852 NamedDecl *NonTemplateTarget = Target;
8853 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8854 NonTemplateTarget = TargetTD->getTemplatedDecl();
8855
8856 UsingShadowDecl *Shadow;
8857 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8858 bool IsVirtualBase =
8859 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8860 UD->getQualifier()->getAsRecordDecl());
8861 Shadow = ConstructorUsingShadowDecl::Create(
8862 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8863 } else {
8864 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8865 Target);
8866 }
John McCall3f746822009-11-17 05:59:44 +00008867 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00008868
Douglas Gregor457104e2010-09-29 04:25:11 +00008869 Shadow->setAccess(UD->getAccess());
8870 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8871 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00008872
8873 Shadow->setPreviousDecl(PrevDecl);
8874
John McCall3f746822009-11-17 05:59:44 +00008875 if (S)
John McCall3969e302009-12-08 07:46:18 +00008876 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00008877 else
John McCall3969e302009-12-08 07:46:18 +00008878 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00008879
John McCall3969e302009-12-08 07:46:18 +00008880
John McCall84d87672009-12-10 09:41:52 +00008881 return Shadow;
8882}
John McCall3969e302009-12-08 07:46:18 +00008883
John McCall84d87672009-12-10 09:41:52 +00008884/// Hides a using shadow declaration. This is required by the current
8885/// using-decl implementation when a resolvable using declaration in a
8886/// class is followed by a declaration which would hide or override
8887/// one or more of the using decl's targets; for example:
8888///
8889/// struct Base { void foo(int); };
8890/// struct Derived : Base {
8891/// using Base::foo;
8892/// void foo(int);
8893/// };
8894///
8895/// The governing language is C++03 [namespace.udecl]p12:
8896///
8897/// When a using-declaration brings names from a base class into a
8898/// derived class scope, member functions in the derived class
8899/// override and/or hide member functions with the same name and
8900/// parameter types in a base class (rather than conflicting).
8901///
8902/// There are two ways to implement this:
8903/// (1) optimistically create shadow decls when they're not hidden
8904/// by existing declarations, or
8905/// (2) don't create any shadow decls (or at least don't make them
8906/// visible) until we've fully parsed/instantiated the class.
8907/// The problem with (1) is that we might have to retroactively remove
8908/// a shadow decl, which requires several O(n) operations because the
8909/// decl structures are (very reasonably) not designed for removal.
8910/// (2) avoids this but is very fiddly and phase-dependent.
8911void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00008912 if (Shadow->getDeclName().getNameKind() ==
8913 DeclarationName::CXXConversionFunctionName)
8914 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8915
John McCall84d87672009-12-10 09:41:52 +00008916 // Remove it from the DeclContext...
8917 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008918
John McCall84d87672009-12-10 09:41:52 +00008919 // ...and the scope, if applicable...
8920 if (S) {
John McCall48871652010-08-21 09:40:31 +00008921 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00008922 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008923 }
8924
John McCall84d87672009-12-10 09:41:52 +00008925 // ...and the using decl.
8926 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8927
8928 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00008929 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00008930}
8931
Richard Smith09d5b3a2014-05-01 00:35:04 +00008932/// Find the base specifier for a base class with the given type.
8933static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8934 QualType DesiredBase,
8935 bool &AnyDependentBases) {
8936 // Check whether the named type is a direct base class.
8937 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8938 for (auto &Base : Derived->bases()) {
8939 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8940 if (CanonicalDesiredBase == BaseType)
8941 return &Base;
8942 if (BaseType->isDependentType())
8943 AnyDependentBases = true;
8944 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008945 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008946}
8947
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008948namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008949class UsingValidatorCCC : public CorrectionCandidateCallback {
8950public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00008951 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008952 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008953 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00008954 IsInstantiation(IsInstantiation), OldNNS(NNS),
8955 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008956
Craig Toppera798a9d2014-03-02 09:32:10 +00008957 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008958 NamedDecl *ND = Candidate.getCorrectionDecl();
8959
8960 // Keywords are not valid here.
8961 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008962 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008963
8964 // Completely unqualified names are invalid for a 'using' declaration.
8965 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8966 return false;
8967
Richard Smith9385d702016-05-14 01:58:49 +00008968 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8969 // reject.
8970
Richard Smith09d5b3a2014-05-01 00:35:04 +00008971 if (RequireMemberOf) {
8972 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8973 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8974 // No-one ever wants a using-declaration to name an injected-class-name
8975 // of a base class, unless they're declaring an inheriting constructor.
8976 ASTContext &Ctx = ND->getASTContext();
8977 if (!Ctx.getLangOpts().CPlusPlus11)
8978 return false;
8979 QualType FoundType = Ctx.getRecordType(FoundRecord);
8980
8981 // Check that the injected-class-name is named as a member of its own
8982 // type; we don't want to suggest 'using Derived::Base;', since that
8983 // means something else.
8984 NestedNameSpecifier *Specifier =
8985 Candidate.WillReplaceSpecifier()
8986 ? Candidate.getCorrectionSpecifier()
8987 : OldNNS;
8988 if (!Specifier->getAsType() ||
8989 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8990 return false;
8991
8992 // Check that this inheriting constructor declaration actually names a
8993 // direct base class of the current class.
8994 bool AnyDependentBases = false;
8995 if (!findDirectBaseWithType(RequireMemberOf,
8996 Ctx.getRecordType(FoundRecord),
8997 AnyDependentBases) &&
8998 !AnyDependentBases)
8999 return false;
9000 } else {
9001 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9002 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9003 return false;
9004
9005 // FIXME: Check that the base class member is accessible?
9006 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00009007 } else {
9008 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9009 if (FoundRecord && FoundRecord->isInjectedClassName())
9010 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009011 }
9012
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009013 if (isa<TypeDecl>(ND))
9014 return HasTypenameKeyword || !IsInstantiation;
9015
9016 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009017 }
9018
9019private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009020 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009021 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009022 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009023 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009024};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009025} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009026
John McCalle61f2ba2009-11-18 02:36:19 +00009027/// Builds a using declaration.
9028///
9029/// \param IsInstantiation - Whether this call arises from an
9030/// instantiation of an unresolved using declaration. We treat
9031/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009032NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9033 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009034 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009035 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009036 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00009037 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009038 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00009039 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009040 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009041 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009042 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009043
Anders Carlssonf038fc22009-08-28 05:49:21 +00009044 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009045
Anders Carlsson59140b32009-08-28 03:16:11 +00009046 if (SS.isEmpty()) {
9047 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00009048 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00009049 }
Mike Stump11289f42009-09-09 15:08:12 +00009050
Richard Smith5179eb72016-06-28 19:03:57 +00009051 // For an inheriting constructor declaration, the name of the using
9052 // declaration is the name of a constructor in this class, not in the
9053 // base class.
9054 DeclarationNameInfo UsingName = NameInfo;
9055 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9056 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9057 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9058 Context.getCanonicalType(Context.getRecordType(RD))));
9059
John McCall84d87672009-12-10 09:41:52 +00009060 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009061 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009062 ForRedeclaration);
9063 Previous.setHideTags(false);
9064 if (S) {
9065 LookupName(Previous, S);
9066
9067 // It is really dumb that we have to do this.
9068 LookupResult::Filter F = Previous.makeFilter();
9069 while (F.hasNext()) {
9070 NamedDecl *D = F.next();
9071 if (!isDeclInScope(D, CurContext, S))
9072 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009073 // If we found a local extern declaration that's not ordinarily visible,
9074 // and this declaration is being added to a non-block scope, ignore it.
9075 // We're only checking for scope conflicts here, not also for violations
9076 // of the linkage rules.
9077 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9078 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9079 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009080 }
9081 F.done();
9082 } else {
9083 assert(IsInstantiation && "no scope in non-instantiation");
9084 assert(CurContext->isRecord() && "scope not record in instantiation");
9085 LookupQualifiedName(Previous, CurContext);
9086 }
9087
John McCall84d87672009-12-10 09:41:52 +00009088 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009089 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9090 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009091 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009092
9093 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00009094 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009095 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009096
John McCall84c16cf2009-11-12 03:15:40 +00009097 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009098 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009099 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00009100 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009101 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009102 // FIXME: not all declaration name kinds are legal here
9103 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9104 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009105 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009106 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00009107 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009108 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9109 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00009110 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009111 D->setAccess(AS);
9112 CurContext->addDecl(D);
9113 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009114 }
John McCallb96ec562009-12-04 22:46:56 +00009115
Richard Smith09d5b3a2014-05-01 00:35:04 +00009116 auto Build = [&](bool Invalid) {
9117 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009118 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9119 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009120 UD->setAccess(AS);
9121 CurContext->addDecl(UD);
9122 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009123 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009124 };
9125 auto BuildInvalid = [&]{ return Build(true); };
9126 auto BuildValid = [&]{ return Build(false); };
9127
9128 if (RequireCompleteDeclContext(SS, LookupContext))
9129 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009130
Richard Smith78163e22015-04-01 19:31:06 +00009131 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009132 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009133
John McCall3969e302009-12-08 07:46:18 +00009134 // Unlike most lookups, we don't always want to hide tag
9135 // declarations: tag names are visible through the using declaration
9136 // even if hidden by ordinary names, *except* in a dependent context
9137 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009138 if (!IsInstantiation)
9139 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009140
John McCall5dadb652012-04-07 03:04:20 +00009141 // For the purposes of this lookup, we have a base object type
9142 // equal to that of the current context.
9143 if (CurContext->isRecord()) {
9144 R.setBaseObjectType(
9145 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9146 }
9147
John McCall27b18f82009-11-17 02:14:36 +00009148 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009149
Richard Smith78163e22015-04-01 19:31:06 +00009150 // Try to correct typos if possible. If constructor name lookup finds no
9151 // results, that means the named class has no explicit constructors, and we
9152 // suppressed declaring implicit ones (probably because it's dependent or
9153 // invalid).
9154 if (R.empty() &&
9155 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009156 if (TypoCorrection Corrected = CorrectTypo(
9157 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9158 llvm::make_unique<UsingValidatorCCC>(
9159 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9160 dyn_cast<CXXRecordDecl>(CurContext)),
9161 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009162 // We reject any correction for which ND would be NULL.
9163 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009164
Richard Smithf9b15102013-08-17 00:46:16 +00009165 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009166 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009167 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9168 << NameInfo.getName() << LookupContext << 0
9169 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009170
9171 // If we corrected to an inheriting constructor, handle it as one.
9172 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9173 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009174 // The parent of the injected class name is the class itself.
9175 RD = cast<CXXRecordDecl>(RD->getParent());
9176
Richard Smith09d5b3a2014-05-01 00:35:04 +00009177 // Fix up the information we'll use to build the using declaration.
9178 if (Corrected.WillReplaceSpecifier()) {
9179 NestedNameSpecifierLocBuilder Builder;
9180 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9181 QualifierLoc.getSourceRange());
9182 QualifierLoc = Builder.getWithLocInContext(Context);
9183 }
9184
Richard Smith5179eb72016-06-28 19:03:57 +00009185 // In this case, the name we introduce is the name of a derived class
9186 // constructor.
9187 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9188 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9189 Context.getCanonicalType(Context.getRecordType(CurClass))));
9190 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009191 for (auto *Ctor : LookupConstructors(RD))
9192 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009193 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009194 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009195 // FIXME: Pick up all the declarations if we found an overloaded
9196 // function.
9197 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009198 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009199 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009200 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009201 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009202 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009203 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009204 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009205 }
9206
Richard Smith09d5b3a2014-05-01 00:35:04 +00009207 if (R.isAmbiguous())
9208 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009209
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009210 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009211 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009212 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009213 Diag(IdentLoc, diag::err_using_typename_non_type);
9214 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9215 Diag((*I)->getUnderlyingDecl()->getLocation(),
9216 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009217 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009218 }
9219 } else {
9220 // If we asked for a non-typename and we got a type, error out,
9221 // but only if this is an instantiation of an unresolved using
9222 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009223 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009224 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9225 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009226 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009227 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009228 }
9229
Richard Smith5cbeb752016-05-05 02:13:49 +00009230 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009231 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009232 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009233 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9234 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009235 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009236 }
Mike Stump11289f42009-09-09 15:08:12 +00009237
Richard Smith5cbeb752016-05-05 02:13:49 +00009238 // C++14 [namespace.udecl]p7:
9239 // A using-declaration shall not name a scoped enumerator.
9240 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9241 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9242 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9243 << SS.getRange();
9244 return BuildInvalid();
9245 }
9246 }
9247
Richard Smith09d5b3a2014-05-01 00:35:04 +00009248 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009249
Richard Smith5179eb72016-06-28 19:03:57 +00009250 // Some additional rules apply to inheriting constructors.
9251 if (UsingName.getName().getNameKind() ==
9252 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009253 // Suppress access diagnostics; the access check is instead performed at the
9254 // point of use for an inheriting constructor.
9255 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009256 if (CheckInheritingConstructorUsingDecl(UD))
9257 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009258 }
9259
John McCall84d87672009-12-10 09:41:52 +00009260 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009261 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009262 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9263 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009264 }
John McCall3f746822009-11-17 05:59:44 +00009265
9266 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009267}
9268
Sebastian Redl08905022011-02-05 19:23:19 +00009269/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009270bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009271 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009272
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009273 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009274 assert(SourceType &&
9275 "Using decl naming constructor doesn't have type in scope spec.");
9276 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9277
9278 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009279 bool AnyDependentBases = false;
9280 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9281 AnyDependentBases);
9282 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009283 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009284 diag::err_using_decl_constructor_not_in_direct_base)
9285 << UD->getNameInfo().getSourceRange()
9286 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009287 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009288 return true;
9289 }
9290
Richard Smith09d5b3a2014-05-01 00:35:04 +00009291 if (Base)
9292 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009293
9294 return false;
9295}
9296
John McCall84d87672009-12-10 09:41:52 +00009297/// Checks that the given using declaration is not an invalid
9298/// redeclaration. Note that this is checking only for the using decl
9299/// itself, not for any ill-formedness among the UsingShadowDecls.
9300bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009301 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009302 const CXXScopeSpec &SS,
9303 SourceLocation NameLoc,
9304 const LookupResult &Prev) {
9305 // C++03 [namespace.udecl]p8:
9306 // C++0x [namespace.udecl]p10:
9307 // A using-declaration is a declaration and can therefore be used
9308 // repeatedly where (and only where) multiple declarations are
9309 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009310 //
John McCall032092f2010-11-29 18:01:58 +00009311 // That's in non-member contexts.
9312 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00009313 return false;
9314
Aaron Ballman4a979672014-01-03 13:56:08 +00009315 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00009316
9317 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9318 NamedDecl *D = *I;
9319
9320 bool DTypename;
9321 NestedNameSpecifier *DQual;
9322 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009323 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009324 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009325 } else if (UnresolvedUsingValueDecl *UD
9326 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9327 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009328 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009329 } else if (UnresolvedUsingTypenameDecl *UD
9330 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9331 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009332 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009333 } else continue;
9334
9335 // using decls differ if one says 'typename' and the other doesn't.
9336 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009337 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009338
9339 // using decls differ if they name different scopes (but note that
9340 // template instantiation can cause this check to trigger when it
9341 // didn't before instantiation).
9342 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9343 Context.getCanonicalNestedNameSpecifier(DQual))
9344 continue;
9345
9346 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009347 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009348 return true;
9349 }
9350
9351 return false;
9352}
9353
John McCall3969e302009-12-08 07:46:18 +00009354
John McCallb96ec562009-12-04 22:46:56 +00009355/// Checks that the given nested-name qualifier used in a using decl
9356/// in the current context is appropriately related to the current
9357/// scope. If an error is found, diagnoses it and returns true.
9358bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9359 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009360 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009361 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009362 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009363
John McCall3969e302009-12-08 07:46:18 +00009364 if (!CurContext->isRecord()) {
9365 // C++03 [namespace.udecl]p3:
9366 // C++0x [namespace.udecl]p8:
9367 // A using-declaration for a class member shall be a member-declaration.
9368
9369 // If we weren't able to compute a valid scope, it must be a
9370 // dependent class scope.
Richard Smith5cbeb752016-05-05 02:13:49 +00009371 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9372 auto *RD = NamedContext
9373 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9374 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009375 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009376 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009377
John McCall3969e302009-12-08 07:46:18 +00009378 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9379 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009380
9381 // If we have a complete, non-dependent source type, try to suggest a
9382 // way to get the same effect.
9383 if (!RD)
9384 return true;
9385
9386 // Find what this using-declaration was referring to.
9387 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9388 R.setHideTags(false);
9389 R.suppressDiagnostics();
9390 LookupQualifiedName(R, RD);
9391
9392 if (R.getAsSingle<TypeDecl>()) {
9393 if (getLangOpts().CPlusPlus11) {
9394 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9395 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9396 << 0 // alias declaration
9397 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9398 NameInfo.getName().getAsString() +
9399 " = ");
9400 } else {
9401 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9402 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009403 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009404 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9405 << 1 // typedef declaration
9406 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9407 << FixItHint::CreateInsertion(
9408 InsertLoc, " " + NameInfo.getName().getAsString());
9409 }
9410 } else if (R.getAsSingle<VarDecl>()) {
9411 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9412 // repeating the type of the static data member here.
9413 FixItHint FixIt;
9414 if (getLangOpts().CPlusPlus11) {
9415 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9416 FixIt = FixItHint::CreateReplacement(
9417 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9418 }
9419
9420 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9421 << 2 // reference declaration
9422 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009423 } else if (R.getAsSingle<EnumConstantDecl>()) {
9424 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9425 // repeating the type of the enumeration here, and we can't do so if
9426 // the type is anonymous.
9427 FixItHint FixIt;
9428 if (getLangOpts().CPlusPlus11) {
9429 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9430 FixIt = FixItHint::CreateReplacement(
9431 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9432 }
9433
9434 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9435 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9436 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009437 }
John McCall3969e302009-12-08 07:46:18 +00009438 return true;
9439 }
9440
9441 // Otherwise, everything is known to be fine.
9442 return false;
9443 }
9444
9445 // The current scope is a record.
9446
9447 // If the named context is dependent, we can't decide much.
9448 if (!NamedContext) {
9449 // FIXME: in C++0x, we can diagnose if we can prove that the
9450 // nested-name-specifier does not refer to a base class, which is
9451 // still possible in some cases.
9452
9453 // Otherwise we have to conservatively report that things might be
9454 // okay.
9455 return false;
9456 }
9457
9458 if (!NamedContext->isRecord()) {
9459 // Ideally this would point at the last name in the specifier,
9460 // but we don't have that level of source info.
9461 Diag(SS.getRange().getBegin(),
9462 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009463 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009464 return true;
9465 }
9466
Douglas Gregor7c842292010-12-21 07:41:49 +00009467 if (!NamedContext->isDependentContext() &&
9468 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9469 return true;
9470
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009471 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009472 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009473 // In a using-declaration used as a member-declaration, the
9474 // nested-name-specifier shall name a base class of the class
9475 // being defined.
9476
9477 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9478 cast<CXXRecordDecl>(NamedContext))) {
9479 if (CurContext == NamedContext) {
9480 Diag(NameLoc,
9481 diag::err_using_decl_nested_name_specifier_is_current_class)
9482 << SS.getRange();
9483 return true;
9484 }
9485
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009486 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9487 Diag(SS.getRange().getBegin(),
9488 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9489 << SS.getScopeRep()
9490 << cast<CXXRecordDecl>(CurContext)
9491 << SS.getRange();
9492 }
John McCall3969e302009-12-08 07:46:18 +00009493 return true;
9494 }
9495
9496 return false;
9497 }
9498
9499 // C++03 [namespace.udecl]p4:
9500 // A using-declaration used as a member-declaration shall refer
9501 // to a member of a base class of the class being defined [etc.].
9502
9503 // Salient point: SS doesn't have to name a base class as long as
9504 // lookup only finds members from base classes. Therefore we can
9505 // diagnose here only if we can prove that that can't happen,
9506 // i.e. if the class hierarchies provably don't intersect.
9507
9508 // TODO: it would be nice if "definitely valid" results were cached
9509 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9510 // need to be repeated.
9511
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009512 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9513 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9514 Bases.insert(Base);
9515 return true;
John McCall3969e302009-12-08 07:46:18 +00009516 };
9517
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009518 // Collect all bases. Return false if we find a dependent base.
9519 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009520 return false;
9521
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009522 // Returns true if the base is dependent or is one of the accumulated base
9523 // classes.
9524 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9525 return !Bases.count(Base);
9526 };
9527
9528 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009529 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009530 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9531 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009532 return false;
9533
9534 Diag(SS.getRange().getBegin(),
9535 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009536 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009537 << cast<CXXRecordDecl>(CurContext)
9538 << SS.getRange();
9539
9540 return true;
John McCallb96ec562009-12-04 22:46:56 +00009541}
9542
Richard Smithdda56e42011-04-15 14:24:37 +00009543Decl *Sema::ActOnAliasDeclaration(Scope *S,
9544 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009545 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009546 SourceLocation UsingLoc,
9547 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009548 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009549 TypeResult Type,
9550 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009551 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009552 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009553 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009554 assert((S->getFlags() & Scope::DeclScope) &&
9555 "got alias-declaration outside of declaration scope");
9556
9557 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009558 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009559
9560 bool Invalid = false;
9561 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009562 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009563 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009564
9565 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009566 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009567
9568 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009569 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009570 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009571 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9572 TInfo->getTypeLoc().getBeginLoc());
9573 }
Richard Smithdda56e42011-04-15 14:24:37 +00009574
9575 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9576 LookupName(Previous, S);
9577
9578 // Warn about shadowing the name of a template parameter.
9579 if (Previous.isSingleResult() &&
9580 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009581 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009582 Previous.clear();
9583 }
9584
9585 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9586 "name in alias declaration must be an identifier");
9587 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9588 Name.StartLocation,
9589 Name.Identifier, TInfo);
9590
9591 NewTD->setAccess(AS);
9592
9593 if (Invalid)
9594 NewTD->setInvalidDecl();
9595
Richard Smith54ecd982013-02-20 19:22:51 +00009596 ProcessDeclAttributeList(S, NewTD, AttrList);
9597
Richard Smith3f1b5d02011-05-05 21:57:07 +00009598 CheckTypedefForVariablyModifiedType(S, NewTD);
9599 Invalid |= NewTD->isInvalidDecl();
9600
Richard Smithdda56e42011-04-15 14:24:37 +00009601 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009602
9603 NamedDecl *NewND;
9604 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009605 TypeAliasTemplateDecl *OldDecl = nullptr;
9606 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009607
9608 if (TemplateParamLists.size() != 1) {
9609 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009610 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9611 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009612 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009613 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009614
Richard Smith882593f2016-04-06 17:38:58 +00009615 // Check that we can declare a template here.
9616 if (CheckTemplateDeclScope(S, TemplateParams))
9617 return nullptr;
9618
Richard Smith3f1b5d02011-05-05 21:57:07 +00009619 // Only consider previous declarations in the same scope.
9620 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9621 /*ExplicitInstantiationOrSpecialization*/false);
9622 if (!Previous.empty()) {
9623 Redeclaration = true;
9624
9625 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9626 if (!OldDecl && !Invalid) {
9627 Diag(UsingLoc, diag::err_redefinition_different_kind)
9628 << Name.Identifier;
9629
9630 NamedDecl *OldD = Previous.getRepresentativeDecl();
9631 if (OldD->getLocation().isValid())
9632 Diag(OldD->getLocation(), diag::note_previous_definition);
9633
9634 Invalid = true;
9635 }
9636
9637 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9638 if (TemplateParameterListsAreEqual(TemplateParams,
9639 OldDecl->getTemplateParameters(),
9640 /*Complain=*/true,
9641 TPL_TemplateMatch))
9642 OldTemplateParams = OldDecl->getTemplateParameters();
9643 else
9644 Invalid = true;
9645
9646 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9647 if (!Invalid &&
9648 !Context.hasSameType(OldTD->getUnderlyingType(),
9649 NewTD->getUnderlyingType())) {
9650 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9651 // but we can't reasonably accept it.
9652 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9653 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9654 if (OldTD->getLocation().isValid())
9655 Diag(OldTD->getLocation(), diag::note_previous_definition);
9656 Invalid = true;
9657 }
9658 }
9659 }
9660
9661 // Merge any previous default template arguments into our parameters,
9662 // and check the parameter list.
9663 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9664 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00009665 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009666
9667 TypeAliasTemplateDecl *NewDecl =
9668 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9669 Name.Identifier, TemplateParams,
9670 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00009671 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009672
9673 NewDecl->setAccess(AS);
9674
9675 if (Invalid)
9676 NewDecl->setInvalidDecl();
9677 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00009678 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009679
9680 NewND = NewDecl;
9681 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00009682 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9683 setTagNameForLinkagePurposes(TD, NewTD);
9684 handleTagNumbering(TD, S);
9685 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00009686 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9687 NewND = NewTD;
9688 }
Richard Smithdda56e42011-04-15 14:24:37 +00009689
Richard Smith3cbf3f12016-07-15 20:53:25 +00009690 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00009691 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009692 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00009693}
9694
Richard Smithf4634362014-09-03 23:11:22 +00009695Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9696 SourceLocation AliasLoc,
9697 IdentifierInfo *Alias, CXXScopeSpec &SS,
9698 SourceLocation IdentLoc,
9699 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00009700
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009701 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00009702 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9703 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009704
John McCall27b18f82009-11-17 02:14:36 +00009705 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00009706 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009707
John McCall9f3059a2009-10-09 21:13:30 +00009708 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00009709 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00009710 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00009711 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00009712 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00009713 }
Richard Smithf4634362014-09-03 23:11:22 +00009714 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00009715 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00009716
9717 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00009718 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9719 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00009720 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00009721
Richard Smith2b2a1762015-12-03 23:24:04 +00009722 // Check we're not shadowing a template parameter.
9723 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9724 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9725 PrevR.clear();
9726 }
Aaron Ballman43f40102014-11-14 22:34:56 +00009727
Richard Smith2b2a1762015-12-03 23:24:04 +00009728 // Filter out any other lookup result from an enclosing scope.
9729 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9730 /*AllowInlineNamespace*/false);
9731
9732 // Find the previous declaration and check that we can redeclare it.
9733 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00009734 if (PrevR.isSingleResult()) {
9735 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9736 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009737 // We already have an alias with the same name that points to the same
9738 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00009739 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9740 Prev = AD;
9741 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009742 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9743 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +00009744 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +00009745 << AD->getNamespace();
9746 return nullptr;
9747 }
Richard Smith2b2a1762015-12-03 23:24:04 +00009748 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +00009749 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +00009750 ? diag::err_redefinition
9751 : diag::err_redefinition_different_kind;
9752 Diag(AliasLoc, DiagID) << Alias;
9753 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9754 return nullptr;
9755 }
9756 }
Mike Stump11289f42009-09-09 15:08:12 +00009757
Nico Riecke50e59a2014-11-24 17:29:52 +00009758 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00009759 DiagnoseUseOfDecl(ND, IdentLoc);
9760
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009761 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00009762 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00009763 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00009764 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00009765 if (Prev)
9766 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00009767
John McCalld8d0d432010-02-16 06:53:13 +00009768 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00009769 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00009770}
9771
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009772Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009773Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9774 CXXMethodDecl *MD) {
9775 CXXRecordDecl *ClassDecl = MD->getParent();
9776
Douglas Gregor6d880b12010-07-01 22:31:05 +00009777 // C++ [except.spec]p14:
9778 // An implicitly declared special member function (Clause 12) shall have an
9779 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00009780 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009781 if (ClassDecl->isInvalidDecl())
9782 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00009783
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009784 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009785 for (const auto &B : ClassDecl->bases()) {
9786 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00009787 continue;
9788
Aaron Ballman574705e2014-03-13 15:41:46 +00009789 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009790 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009791 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9792 // If this is a deleted function, add it anyway. This might be conformant
9793 // with the standard. This might not. I'm not sure. It might not matter.
9794 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00009795 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009796 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009797 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009798
9799 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009800 for (const auto &B : ClassDecl->vbases()) {
9801 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009802 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009803 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9804 // If this is a deleted function, add it anyway. This might be conformant
9805 // with the standard. This might not. I'm not sure. It might not matter.
9806 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009807 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009808 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009809 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009810
9811 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009812 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00009813 if (F->hasInClassInitializer()) {
9814 if (Expr *E = F->getInClassInitializer())
9815 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00009816 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00009817 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00009818 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9819 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9820 // If this is a deleted function, add it anyway. This might be conformant
9821 // with the standard. This might not. I'm not sure. It might not matter.
9822 // In particular, the problem is that this function never gets called. It
9823 // might just be ill-formed because this function attempts to refer to
9824 // a deleted function here.
9825 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009826 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009827 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009828 }
John McCalldb40c7f2010-12-14 08:05:40 +00009829
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009830 return ExceptSpec;
9831}
9832
Richard Smithc2bc61b2013-03-18 21:12:30 +00009833Sema::ImplicitExceptionSpecification
Richard Smith5179eb72016-06-28 19:03:57 +00009834Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9835 CXXConstructorDecl *CD) {
Richard Smithb7151b92013-04-10 06:11:48 +00009836 CXXRecordDecl *ClassDecl = CD->getParent();
9837
9838 // C++ [except.spec]p14:
9839 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00009840 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00009841 if (ClassDecl->isInvalidDecl())
9842 return ExceptSpec;
9843
Richard Smith5179eb72016-06-28 19:03:57 +00009844 auto Inherited = CD->getInheritedConstructor();
9845 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
Richard Smithb7151b92013-04-10 06:11:48 +00009846
Richard Smith5179eb72016-06-28 19:03:57 +00009847 // Direct and virtual base-class constructors.
9848 for (bool VBase : {false, true}) {
9849 for (CXXBaseSpecifier &B :
9850 VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9851 // Don't visit direct vbases twice.
9852 if (B.isVirtual() != VBase)
Richard Smithb7151b92013-04-10 06:11:48 +00009853 continue;
Richard Smithb7151b92013-04-10 06:11:48 +00009854
Richard Smith5179eb72016-06-28 19:03:57 +00009855 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9856 if (!BaseClass)
Richard Smithb7151b92013-04-10 06:11:48 +00009857 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00009858
9859 CXXConstructorDecl *Constructor =
9860 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9861 .first;
9862 if (!Constructor)
9863 Constructor = LookupDefaultConstructor(BaseClass);
Richard Smithb7151b92013-04-10 06:11:48 +00009864 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009865 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00009866 }
9867 }
9868
9869 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009870 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00009871 if (F->hasInClassInitializer()) {
9872 if (Expr *E = F->getInClassInitializer())
9873 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00009874 } else if (const RecordType *RecordTy
9875 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9876 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9877 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9878 if (Constructor)
9879 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9880 }
9881 }
9882
Richard Smithc2bc61b2013-03-18 21:12:30 +00009883 return ExceptSpec;
9884}
9885
Richard Smith8bf22e52012-11-29 01:34:07 +00009886namespace {
9887/// RAII object to register a special member as being currently declared.
9888struct DeclaringSpecialMember {
9889 Sema &S;
9890 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +00009891 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +00009892 bool WasAlreadyBeingDeclared;
9893
9894 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +00009895 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +00009896 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00009897 if (WasAlreadyBeingDeclared)
9898 // This almost never happens, but if it does, ensure that our cache
9899 // doesn't contain a stale result.
9900 S.SpecialMemberCache.clear();
9901
9902 // FIXME: Register a note to be produced if we encounter an error while
9903 // declaring the special member.
9904 }
9905 ~DeclaringSpecialMember() {
9906 if (!WasAlreadyBeingDeclared)
9907 S.SpecialMembersBeingDeclared.erase(D);
9908 }
9909
9910 /// \brief Are we already trying to declare this special member?
9911 bool isAlreadyBeingDeclared() const {
9912 return WasAlreadyBeingDeclared;
9913 }
9914};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009915}
Richard Smith8bf22e52012-11-29 01:34:07 +00009916
Richard Smith12e79312016-05-13 06:47:56 +00009917void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9918 // Look up any existing declarations, but don't trigger declaration of all
9919 // implicit special members with this name.
9920 DeclarationName Name = FD->getDeclName();
9921 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9922 ForRedeclaration);
9923 for (auto *D : FD->getParent()->lookup(Name))
9924 if (auto *Acceptable = R.getAcceptableDecl(D))
9925 R.addDecl(Acceptable);
9926 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +00009927 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +00009928
9929 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9930}
9931
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009932CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9933 CXXRecordDecl *ClassDecl) {
9934 // C++ [class.ctor]p5:
9935 // A default constructor for a class X is a constructor of class X
9936 // that can be called without an argument. If there is no
9937 // user-declared constructor for class X, a default constructor is
9938 // implicitly declared. An implicitly-declared default constructor
9939 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009940 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009941 "Should not build implicit default constructor!");
9942
Richard Smith8bf22e52012-11-29 01:34:07 +00009943 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9944 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009945 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009946
Richard Smithb5800092012-06-10 05:43:50 +00009947 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9948 CXXDefaultConstructor,
9949 false);
9950
Douglas Gregor6d880b12010-07-01 22:31:05 +00009951 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009952 CanQualType ClassType
9953 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009954 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009955 DeclarationName Name
9956 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009957 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00009958 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009959 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9960 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9961 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009962 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00009963 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009964
9965 if (getLangOpts().CUDA) {
9966 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9967 DefaultCon,
9968 /* ConstRHS */ false,
9969 /* Diagnose */ false);
9970 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009971
9972 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009973 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009974 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009975
Richard Smith6b02d462012-12-08 08:32:28 +00009976 // We don't need to use SpecialMemberIsTrivial here; triviality for default
9977 // constructors is easy to compute.
9978 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9979
Douglas Gregor9672f922010-07-03 00:47:00 +00009980 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00009981 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00009982
Richard Smith12e79312016-05-13 06:47:56 +00009983 Scope *S = getScopeForContext(ClassDecl);
9984 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9985
9986 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9987 SetDeclDeleted(DefaultCon, ClassLoc);
9988
9989 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +00009990 PushOnScopeChains(DefaultCon, S, false);
9991 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00009992
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009993 return DefaultCon;
9994}
9995
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009996void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9997 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009998 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009999 !Constructor->doesThisDeclarationHaveABody() &&
10000 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010001 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010002
Anders Carlsson423f5d82010-04-23 16:04:08 +000010003 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010004 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010005
Eli Friedmaneaf34142012-10-18 20:14:08 +000010006 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010007 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +000010008 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010009 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010010 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +000010011 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +000010012 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +000010013 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +000010014 }
Douglas Gregor73193272010-09-20 16:48:21 +000010015
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010016 // The exception specification is needed because we are defining the
10017 // function.
10018 ResolveExceptionSpec(CurrentLocation,
10019 Constructor->getType()->castAs<FunctionProtoType>());
10020
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010021 SourceLocation Loc = Constructor->getLocEnd().isValid()
10022 ? Constructor->getLocEnd()
10023 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010024 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010025
Eli Friedman276dd182013-09-05 00:02:25 +000010026 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010027 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010028
10029 if (ASTMutationListener *L = getASTMutationListener()) {
10030 L->CompletedImplicitDefinition(Constructor);
10031 }
Richard Trieuef64e942013-10-25 00:56:00 +000010032
10033 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010034}
10035
Richard Smith938f40b2011-06-11 17:19:42 +000010036void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010037 // Perform any delayed checks on exception specifications.
10038 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010039}
10040
Richard Smith5179eb72016-06-28 19:03:57 +000010041/// Find or create the fake constructor we synthesize to model constructing an
10042/// object of a derived class via a constructor of a base class.
10043CXXConstructorDecl *
10044Sema::findInheritingConstructor(SourceLocation Loc,
10045 CXXConstructorDecl *BaseCtor,
10046 ConstructorUsingShadowDecl *Shadow) {
10047 CXXRecordDecl *Derived = Shadow->getParent();
10048 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010049
Richard Smith5179eb72016-06-28 19:03:57 +000010050 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10051 // For now we use the name of the base class constructor as a member of the
10052 // derived class to indicate a (fake) inherited constructor name.
10053 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010054
Richard Smith5179eb72016-06-28 19:03:57 +000010055 // Check to see if we already have a fake constructor for this inherited
10056 // constructor call.
10057 for (NamedDecl *Ctor : Derived->lookup(Name))
10058 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10059 ->getInheritedConstructor()
10060 .getConstructor(),
10061 BaseCtor))
10062 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010063
Richard Smith5179eb72016-06-28 19:03:57 +000010064 DeclarationNameInfo NameInfo(Name, UsingLoc);
10065 TypeSourceInfo *TInfo =
10066 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10067 FunctionProtoTypeLoc ProtoLoc =
10068 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010069
Richard Smith5179eb72016-06-28 19:03:57 +000010070 // Check the inherited constructor is valid and find the list of base classes
10071 // from which it was inherited.
10072 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010073
Richard Smith5179eb72016-06-28 19:03:57 +000010074 bool Constexpr =
10075 BaseCtor->isConstexpr() &&
10076 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10077 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010078
Richard Smith5179eb72016-06-28 19:03:57 +000010079 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10080 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10081 BaseCtor->isExplicit(), /*Inline=*/true,
10082 /*ImplicitlyDeclared=*/true, Constexpr,
10083 InheritedConstructor(Shadow, BaseCtor));
10084 if (Shadow->isInvalidDecl())
10085 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010086
Richard Smith5179eb72016-06-28 19:03:57 +000010087 // Build an unevaluated exception specification for this fake constructor.
10088 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10089 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10090 EPI.ExceptionSpec.Type = EST_Unevaluated;
10091 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10092 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10093 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010094
Richard Smith5179eb72016-06-28 19:03:57 +000010095 // Build the parameter declarations.
10096 SmallVector<ParmVarDecl *, 16> ParamDecls;
10097 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010098 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010099 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10100 ParmVarDecl *PD = ParmVarDecl::Create(
10101 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10102 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10103 PD->setScopeInfo(0, I);
10104 PD->setImplicit();
10105 // Ensure attributes are propagated onto parameters (this matters for
10106 // format, pass_object_size, ...).
10107 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10108 ParamDecls.push_back(PD);
10109 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010110 }
10111
Richard Smith5179eb72016-06-28 19:03:57 +000010112 // Set up the new constructor.
10113 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10114 DerivedCtor->setAccess(BaseCtor->getAccess());
10115 DerivedCtor->setParams(ParamDecls);
10116 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010117
10118 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10119 SetDeclDeleted(DerivedCtor, UsingLoc);
10120
Richard Smith5179eb72016-06-28 19:03:57 +000010121 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010122}
10123
Richard Smith80a47022016-06-29 01:10:27 +000010124void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10125 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10126 Ctor->getInheritedConstructor().getShadowDecl());
10127 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10128 /*Diagnose*/true);
10129}
10130
Richard Smithc2bc61b2013-03-18 21:12:30 +000010131void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10132 CXXConstructorDecl *Constructor) {
10133 CXXRecordDecl *ClassDecl = Constructor->getParent();
10134 assert(Constructor->getInheritedConstructor() &&
10135 !Constructor->doesThisDeclarationHaveABody() &&
10136 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010137 if (Constructor->isInvalidDecl())
10138 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010139
Richard Smith5179eb72016-06-28 19:03:57 +000010140 ConstructorUsingShadowDecl *Shadow =
10141 Constructor->getInheritedConstructor().getShadowDecl();
10142 CXXConstructorDecl *InheritedCtor =
10143 Constructor->getInheritedConstructor().getConstructor();
10144
10145 // [class.inhctor.init]p1:
10146 // initialization proceeds as if a defaulted default constructor is used to
10147 // initialize the D object and each base class subobject from which the
10148 // constructor was inherited
10149
10150 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10151 CXXRecordDecl *RD = Shadow->getParent();
10152 SourceLocation InitLoc = Shadow->getLocation();
10153
10154 // Initializations are performed "as if by a defaulted default constructor",
10155 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010156 SynthesizedFunctionScope Scope(*this, Constructor);
10157 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010158
10159 // Build explicit initializers for all base classes from which the
10160 // constructor was inherited.
10161 SmallVector<CXXCtorInitializer*, 8> Inits;
10162 for (bool VBase : {false, true}) {
10163 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10164 if (B.isVirtual() != VBase)
10165 continue;
10166
10167 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10168 if (!BaseRD)
10169 continue;
10170
10171 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10172 if (!BaseCtor.first)
10173 continue;
10174
10175 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10176 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10177 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10178
10179 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10180 Inits.push_back(new (Context) CXXCtorInitializer(
10181 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10182 SourceLocation()));
10183 }
10184 }
10185
10186 // We now proceed as if for a defaulted default constructor, with the relevant
10187 // initializers replaced.
10188
10189 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10190 if (HadError || Trap.hasErrorOccurred()) {
10191 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010192 Constructor->setInvalidDecl();
10193 return;
10194 }
10195
Richard Smith5179eb72016-06-28 19:03:57 +000010196 // The exception specification is needed because we are defining the
10197 // function.
10198 ResolveExceptionSpec(CurrentLocation,
10199 Constructor->getType()->castAs<FunctionProtoType>());
10200
10201 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010202
Eli Friedman276dd182013-09-05 00:02:25 +000010203 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010204 MarkVTableUsed(CurrentLocation, ClassDecl);
10205
10206 if (ASTMutationListener *L = getASTMutationListener()) {
10207 L->CompletedImplicitDefinition(Constructor);
10208 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010209
Richard Smith5179eb72016-06-28 19:03:57 +000010210 DiagnoseUninitializedFields(*this, Constructor);
10211}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010212
Alexis Huntf91729462011-05-12 22:46:25 +000010213Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010214Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10215 CXXRecordDecl *ClassDecl = MD->getParent();
10216
Douglas Gregorf1203042010-07-01 19:09:28 +000010217 // C++ [except.spec]p14:
10218 // An implicitly declared special member function (Clause 12) shall have
10219 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +000010220 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010221 if (ClassDecl->isInvalidDecl())
10222 return ExceptSpec;
10223
Douglas Gregorf1203042010-07-01 19:09:28 +000010224 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010225 for (const auto &B : ClassDecl->bases()) {
10226 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +000010227 continue;
10228
Aaron Ballman574705e2014-03-13 15:41:46 +000010229 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10230 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010231 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010232 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010233
Douglas Gregorf1203042010-07-01 19:09:28 +000010234 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010235 for (const auto &B : ClassDecl->vbases()) {
10236 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10237 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010238 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010239 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010240
Douglas Gregorf1203042010-07-01 19:09:28 +000010241 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010242 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +000010243 if (const RecordType *RecordTy
10244 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +000010245 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010246 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010247 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010248
Alexis Huntf91729462011-05-12 22:46:25 +000010249 return ExceptSpec;
10250}
10251
10252CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10253 // C++ [class.dtor]p2:
10254 // If a class has no user-declared destructor, a destructor is
10255 // declared implicitly. An implicitly-declared destructor is an
10256 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010257 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010258
Richard Smith8bf22e52012-11-29 01:34:07 +000010259 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10260 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010261 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010262
Douglas Gregor7454c562010-07-02 20:37:36 +000010263 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010264 CanQualType ClassType
10265 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010266 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010267 DeclarationName Name
10268 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010269 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010270 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010271 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010272 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010273 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010274 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010275 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010276
10277 if (getLangOpts().CUDA) {
10278 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10279 Destructor,
10280 /* ConstRHS */ false,
10281 /* Diagnose */ false);
10282 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010283
10284 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010285 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010286 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010287
Richard Smith6b02d462012-12-08 08:32:28 +000010288 // We don't need to use SpecialMemberIsTrivial here; triviality for
10289 // destructors is easy to compute.
10290 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10291
Douglas Gregor7454c562010-07-02 20:37:36 +000010292 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010293 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010294
Richard Smith12e79312016-05-13 06:47:56 +000010295 Scope *S = getScopeForContext(ClassDecl);
10296 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10297
Richard Smithb2f0f052016-10-10 18:54:32 +000010298 // We can't check whether an implicit destructor is deleted before we complete
10299 // the definition of the class, because its validity depends on the alignment
10300 // of the class. We'll check this from ActOnFields once the class is complete.
10301 if (ClassDecl->isCompleteDefinition() &&
10302 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010303 SetDeclDeleted(Destructor, ClassLoc);
10304
Douglas Gregor7454c562010-07-02 20:37:36 +000010305 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010306 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010307 PushOnScopeChains(Destructor, S, false);
10308 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010309
Douglas Gregorf1203042010-07-01 19:09:28 +000010310 return Destructor;
10311}
10312
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010313void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010314 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010315 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010316 !Destructor->doesThisDeclarationHaveABody() &&
10317 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010318 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010319 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010320 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010321
Douglas Gregor54818f02010-05-12 16:39:35 +000010322 if (Destructor->isInvalidDecl())
10323 return;
10324
Eli Friedmaneaf34142012-10-18 20:14:08 +000010325 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010326
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010327 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010328 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10329 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010330
Douglas Gregor54818f02010-05-12 16:39:35 +000010331 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010332 Diag(CurrentLocation, diag::note_member_synthesized_at)
10333 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10334
10335 Destructor->setInvalidDecl();
10336 return;
10337 }
10338
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010339 // The exception specification is needed because we are defining the
10340 // function.
10341 ResolveExceptionSpec(CurrentLocation,
10342 Destructor->getType()->castAs<FunctionProtoType>());
10343
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010344 SourceLocation Loc = Destructor->getLocEnd().isValid()
10345 ? Destructor->getLocEnd()
10346 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010347 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010348 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010349 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010350
10351 if (ASTMutationListener *L = getASTMutationListener()) {
10352 L->CompletedImplicitDefinition(Destructor);
10353 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010354}
10355
Richard Smith84973e52012-04-21 18:42:51 +000010356/// \brief Perform any semantic analysis which needs to be delayed until all
10357/// pending class member declarations have been parsed.
10358void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010359 // If the context is an invalid C++ class, just suppress these checks.
10360 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10361 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010362 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010363 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010364 return;
10365 }
10366 }
Richard Smith84973e52012-04-21 18:42:51 +000010367}
10368
Reid Klecknerc01ee752016-11-23 16:51:30 +000010369static void checkDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010370 // Don't do anything for template patterns.
10371 if (Class->getDescribedClassTemplate())
10372 return;
10373
David Majnemer474b3232015-12-31 05:36:46 +000010374 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10375 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10376
10377 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010378 for (Decl *Member : Class->decls()) {
10379 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10380 if (!CD) {
10381 // Recurse on nested classes.
10382 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
Reid Klecknerc01ee752016-11-23 16:51:30 +000010383 checkDefaultArgExprsForConstructors(S, NestedRD);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010384 continue;
10385 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10386 continue;
10387 }
10388
David Majnemer474b3232015-12-31 05:36:46 +000010389 CallingConv ActualCallingConv =
10390 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10391
10392 // Skip default constructors with typical calling conventions and no default
10393 // arguments.
10394 unsigned NumParams = CD->getNumParams();
10395 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10396 continue;
10397
10398 if (LastExportedDefaultCtor) {
10399 S.Diag(LastExportedDefaultCtor->getLocation(),
10400 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10401 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10402 << CD->getDeclName();
10403 return;
10404 }
10405 LastExportedDefaultCtor = CD;
10406
10407 for (unsigned I = 0; I != NumParams; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +000010408 (void)S.CheckCXXDefaultArgExpr(Class->getLocation(), CD,
10409 CD->getParamDecl(I));
David Majnemer9321f922015-06-11 02:38:06 +000010410 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010411 }
10412 }
10413}
10414
Hans Wennborg99000c22015-08-15 01:18:16 +000010415void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010416 auto *RD = dyn_cast<CXXRecordDecl>(D);
10417
10418 // Default constructors that are annotated with __declspec(dllexport) which
10419 // have default arguments or don't use the standard calling convention are
10420 // wrapped with a thunk called the default constructor closure.
10421 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
Reid Klecknerc01ee752016-11-23 16:51:30 +000010422 checkDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +000010423
Reid Kleckner5b640342016-02-26 19:51:02 +000010424 referenceDLLExportedClassMethods();
10425}
10426
10427void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010428 if (!DelayedDllExportClasses.empty()) {
10429 // Calling ReferenceDllExportedMethods might cause the current function to
10430 // be called again, so use a local copy of DelayedDllExportClasses.
10431 SmallVector<CXXRecordDecl *, 4> WorkList;
10432 std::swap(DelayedDllExportClasses, WorkList);
10433 for (CXXRecordDecl *Class : WorkList)
10434 ReferenceDllExportedMethods(*this, Class);
10435 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010436}
10437
Richard Smithd3b5c9082012-07-27 04:22:15 +000010438void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10439 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010440 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010441 "adjusting dtor exception specs was introduced in c++11");
10442
Sebastian Redl623ea822011-05-19 05:13:44 +000010443 // C++11 [class.dtor]p3:
10444 // A declaration of a destructor that does not have an exception-
10445 // specification is implicitly considered to have the same exception-
10446 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010447 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010448 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010449 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010450 return;
10451
Chandler Carruth9a797572011-09-20 04:55:26 +000010452 // Replace the destructor's type, building off the existing one. Fortunately,
10453 // the only thing of interest in the destructor type is its extended info.
10454 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010455 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010456 EPI.ExceptionSpec.Type = EST_Unevaluated;
10457 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010458 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010459
Sebastian Redl623ea822011-05-19 05:13:44 +000010460 // FIXME: If the destructor has a body that could throw, and the newly created
10461 // spec doesn't allow exceptions, we should emit a warning, because this
10462 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010463 // However, we don't have a body or an exception specification yet, so it
10464 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010465}
10466
Pavel Labath58934982013-08-30 08:52:28 +000010467namespace {
10468/// \brief An abstract base class for all helper classes used in building the
10469// copy/move operators. These classes serve as factory functions and help us
10470// avoid using the same Expr* in the AST twice.
10471class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010472 ExprBuilder(const ExprBuilder&) = delete;
10473 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010474
10475protected:
10476 static Expr *assertNotNull(Expr *E) {
10477 assert(E && "Expression construction must not fail.");
10478 return E;
10479 }
10480
10481public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010482 ExprBuilder() {}
10483 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010484
10485 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10486};
10487
10488class RefBuilder: public ExprBuilder {
10489 VarDecl *Var;
10490 QualType VarType;
10491
10492public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010493 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010494 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010495 }
10496
10497 RefBuilder(VarDecl *Var, QualType VarType)
10498 : Var(Var), VarType(VarType) {}
10499};
10500
10501class ThisBuilder: public ExprBuilder {
10502public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010503 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010504 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010505 }
10506};
10507
10508class CastBuilder: public ExprBuilder {
10509 const ExprBuilder &Builder;
10510 QualType Type;
10511 ExprValueKind Kind;
10512 const CXXCastPath &Path;
10513
10514public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010515 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010516 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10517 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010518 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010519 }
10520
10521 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10522 const CXXCastPath &Path)
10523 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10524};
10525
10526class DerefBuilder: public ExprBuilder {
10527 const ExprBuilder &Builder;
10528
10529public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010530 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010531 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010532 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010533 }
10534
10535 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10536};
10537
10538class MemberBuilder: public ExprBuilder {
10539 const ExprBuilder &Builder;
10540 QualType Type;
10541 CXXScopeSpec SS;
10542 bool IsArrow;
10543 LookupResult &MemberLookup;
10544
10545public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010546 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010547 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010548 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010549 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010550 }
10551
10552 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10553 LookupResult &MemberLookup)
10554 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10555 MemberLookup(MemberLookup) {}
10556};
10557
10558class MoveCastBuilder: public ExprBuilder {
10559 const ExprBuilder &Builder;
10560
10561public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010562 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010563 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10564 }
10565
10566 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10567};
10568
10569class LvalueConvBuilder: public ExprBuilder {
10570 const ExprBuilder &Builder;
10571
10572public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010573 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010574 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010575 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010576 }
10577
10578 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10579};
10580
10581class SubscriptBuilder: public ExprBuilder {
10582 const ExprBuilder &Base;
10583 const ExprBuilder &Index;
10584
10585public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010586 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010587 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010588 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010589 }
10590
10591 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10592 : Base(Base), Index(Index) {}
10593};
10594
10595} // end anonymous namespace
10596
Richard Smith41ae3282012-11-14 00:50:40 +000010597/// When generating a defaulted copy or move assignment operator, if a field
10598/// should be copied with __builtin_memcpy rather than via explicit assignments,
10599/// do so. This optimization only applies for arrays of scalars, and for arrays
10600/// of class type where the selected copy/move-assignment operator is trivial.
10601static StmtResult
10602buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010603 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010604 // Compute the size of the memory buffer to be copied.
10605 QualType SizeType = S.Context.getSizeType();
10606 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10607 S.Context.getTypeSizeInChars(T).getQuantity());
10608
10609 // Take the address of the field references for "from" and "to". We
10610 // directly construct UnaryOperators here because semantic analysis
10611 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010612 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010613 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10614 S.Context.getPointerType(From->getType()),
10615 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010616 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010617 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10618 S.Context.getPointerType(To->getType()),
10619 VK_RValue, OK_Ordinary, Loc);
10620
10621 const Type *E = T->getBaseElementTypeUnsafe();
10622 bool NeedsCollectableMemCpy =
10623 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10624
10625 // Create a reference to the __builtin_objc_memmove_collectable function
10626 StringRef MemCpyName = NeedsCollectableMemCpy ?
10627 "__builtin_objc_memmove_collectable" :
10628 "__builtin_memcpy";
10629 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10630 Sema::LookupOrdinaryName);
10631 S.LookupName(R, S.TUScope, true);
10632
10633 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10634 if (!MemCpy)
10635 // Something went horribly wrong earlier, and we will have complained
10636 // about it.
10637 return StmtError();
10638
10639 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010640 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010641 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10642
10643 Expr *CallArgs[] = {
10644 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10645 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010646 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010647 Loc, CallArgs, Loc);
10648
10649 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010650 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010651}
10652
Sebastian Redl22653ba2011-08-30 19:58:05 +000010653/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010654/// \c To.
10655///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010656/// This routine is used to copy/move the members of a class with an
10657/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010658/// copied are arrays, this routine builds for loops to copy them.
10659///
10660/// \param S The Sema object used for type-checking.
10661///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010662/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010663///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010664/// \param T The type of the expressions being copied/moved. Both expressions
10665/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010666///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010667/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010668///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010669/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010670///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010671/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010672/// Otherwise, it's a non-static member subobject.
10673///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010674/// \param Copying Whether we're copying or moving.
10675///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010676/// \param Depth Internal parameter recording the depth of the recursion.
10677///
Richard Smith41ae3282012-11-14 00:50:40 +000010678/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10679/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010680static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010681buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010682 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010683 bool CopyingBaseSubobject, bool Copying,
10684 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010685 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010686 // Each subobject is assigned in the manner appropriate to its type:
10687 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010688 // - if the subobject is of class type, as if by a call to operator= with
10689 // the subobject as the object expression and the corresponding
10690 // subobject of x as a single function argument (as if by explicit
10691 // qualification; that is, ignoring any possible virtual overriding
10692 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010693 //
10694 // C++03 [class.copy]p13:
10695 // - if the subobject is of class type, the copy assignment operator for
10696 // the class is used (as if by explicit qualification; that is,
10697 // ignoring any possible virtual overriding functions in more derived
10698 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010699 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10700 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010701
Douglas Gregorb139cd52010-05-01 20:49:11 +000010702 // Look for operator=.
10703 DeclarationName Name
10704 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10705 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10706 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010707
Richard Smith52c0b582012-11-13 00:54:12 +000010708 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10709 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010710 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010711 LookupResult::Filter F = OpLookup.makeFilter();
10712 while (F.hasNext()) {
10713 NamedDecl *D = F.next();
10714 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10715 if (Method->isCopyAssignmentOperator() ||
10716 (!Copying && Method->isMoveAssignmentOperator()))
10717 continue;
10718
10719 F.erase();
10720 }
10721 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010722 }
Richard Smith52c0b582012-11-13 00:54:12 +000010723
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010724 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010725 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010726 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010727 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010728 // ambiguities), we need to cast "this" to that subobject type; to
10729 // ensure that we don't go through the virtual call mechanism, we need
10730 // to qualify the operator= name with the base class (see below). However,
10731 // this means that if the base class has a protected copy assignment
10732 // operator, the protected member access check will fail. So, we
10733 // rewrite "protected" access to "public" access in this case, since we
10734 // know by construction that we're calling from a derived class.
10735 if (CopyingBaseSubobject) {
10736 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10737 L != LEnd; ++L) {
10738 if (L.getAccess() == AS_protected)
10739 L.setAccess(AS_public);
10740 }
10741 }
Richard Smith52c0b582012-11-13 00:54:12 +000010742
Douglas Gregorb139cd52010-05-01 20:49:11 +000010743 // Create the nested-name-specifier that will be used to qualify the
10744 // reference to operator=; this is required to suppress the virtual
10745 // call mechanism.
10746 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000010747 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000010748 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000010749 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000010750 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000010751 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000010752
Douglas Gregorb139cd52010-05-01 20:49:11 +000010753 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000010754 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000010755 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10756 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010757 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000010758 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010759 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010760 /*SuppressQualifierCheck=*/true);
10761 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010762 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010763
Douglas Gregorb139cd52010-05-01 20:49:11 +000010764 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000010765
Pavel Labath58934982013-08-30 08:52:28 +000010766 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000010767 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010768 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000010769 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010770 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010771 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010772
Richard Smith41ae3282012-11-14 00:50:40 +000010773 // If we built a call to a trivial 'operator=' while copying an array,
10774 // bail out. We'll replace the whole shebang with a memcpy.
10775 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10776 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000010777 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010778
Richard Smith52c0b582012-11-13 00:54:12 +000010779 // Convert to an expression-statement, and clean up any produced
10780 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000010781 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010782 }
John McCallab8c2732010-03-16 06:11:48 +000010783
Richard Smith52c0b582012-11-13 00:54:12 +000010784 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000010785 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000010786 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010787 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000010788 ExprResult Assignment = S.CreateBuiltinBinOp(
10789 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010790 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010791 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000010792 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010793 }
Richard Smith52c0b582012-11-13 00:54:12 +000010794
10795 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000010796 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000010797
Douglas Gregorb139cd52010-05-01 20:49:11 +000010798 // Construct a loop over the array bounds, e.g.,
10799 //
10800 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10801 //
10802 // that will copy each of the array elements.
10803 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000010804
Douglas Gregorb139cd52010-05-01 20:49:11 +000010805 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000010806 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010807 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010808 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010809 llvm::raw_svector_ostream OS(Str);
10810 OS << "__i" << Depth;
10811 IterationVarName = &S.Context.Idents.get(OS.str());
10812 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000010813 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010814 IterationVarName, SizeType,
10815 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000010816 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000010817
Douglas Gregorb139cd52010-05-01 20:49:11 +000010818 // Initialize the iteration variable to zero.
10819 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010820 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010821
Pavel Labath58934982013-08-30 08:52:28 +000010822 // Creates a reference to the iteration variable.
10823 RefBuilder IterationVarRef(IterationVar, SizeType);
10824 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000010825
Douglas Gregorb139cd52010-05-01 20:49:11 +000010826 // Create the DeclStmt that holds the iteration variable.
10827 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010828
Douglas Gregorb139cd52010-05-01 20:49:11 +000010829 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000010830 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10831 MoveCastBuilder FromIndexMove(FromIndexCopy);
10832 const ExprBuilder *FromIndex;
10833 if (Copying)
10834 FromIndex = &FromIndexCopy;
10835 else
10836 FromIndex = &FromIndexMove;
10837
10838 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010839
10840 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000010841 StmtResult Copy =
10842 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000010843 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000010844 Copying, Depth + 1);
10845 // Bail out if copying fails or if we determined that we should use memcpy.
10846 if (Copy.isInvalid() || !Copy.get())
10847 return Copy;
10848
10849 // Create the comparison against the array bound.
10850 llvm::APInt Upper
10851 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10852 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000010853 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000010854 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10855 BO_NE, S.Context.BoolTy,
10856 VK_RValue, OK_Ordinary, Loc, false);
10857
10858 // Create the pre-increment of the iteration variable.
10859 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000010860 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10861 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010862
Douglas Gregorb139cd52010-05-01 20:49:11 +000010863 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000010864 return S.ActOnForStmt(
10865 Loc, Loc, InitStmt,
10866 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10867 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010868}
10869
Richard Smith41ae3282012-11-14 00:50:40 +000010870static StmtResult
10871buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010872 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010873 bool CopyingBaseSubobject, bool Copying) {
10874 // Maybe we should use a memcpy?
10875 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10876 T.isTriviallyCopyableType(S.Context))
10877 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10878
10879 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10880 CopyingBaseSubobject,
10881 Copying, 0));
10882
10883 // If we ended up picking a trivial assignment operator for an array of a
10884 // non-trivially-copyable class type, just emit a memcpy.
10885 if (!Result.isInvalid() && !Result.get())
10886 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10887
10888 return Result;
10889}
10890
Richard Smithd3b5c9082012-07-27 04:22:15 +000010891Sema::ImplicitExceptionSpecification
10892Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10893 CXXRecordDecl *ClassDecl = MD->getParent();
10894
10895 ImplicitExceptionSpecification ExceptSpec(*this);
10896 if (ClassDecl->isInvalidDecl())
10897 return ExceptSpec;
10898
10899 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010900 assert(T->getNumParams() == 1 && "not a copy assignment op");
10901 unsigned ArgQuals =
10902 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010903
Douglas Gregor68e11362010-07-01 17:48:08 +000010904 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010905 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010906 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010907
10908 // It is unspecified whether or not an implicit copy assignment operator
10909 // attempts to deduplicate calls to assignment operators of virtual bases are
10910 // made. As such, this exception specification is effectively unspecified.
10911 // Based on a similar decision made for constness in C++0x, we're erring on
10912 // the side of assuming such calls to be made regardless of whether they
10913 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010914 for (const auto &Base : ClassDecl->bases()) {
10915 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010916 continue;
10917
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010918 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010919 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010920 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10921 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010922 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010923 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010924
Aaron Ballman445a9392014-03-13 16:15:17 +000010925 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010926 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010927 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010928 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10929 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010930 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010931 }
10932
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010933 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010934 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010935 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10936 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010937 LookupCopyingAssignment(FieldClassDecl,
10938 ArgQuals | FieldType.getCVRQualifiers(),
10939 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010940 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010941 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010942 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010943
Richard Smithd3b5c9082012-07-27 04:22:15 +000010944 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010945}
10946
10947CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10948 // Note: The following rules are largely analoguous to the copy
10949 // constructor rules. Note that virtual bases are not taken into account
10950 // for determining the argument type of the operator. Note also that
10951 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010952 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010953
Richard Smith8bf22e52012-11-29 01:34:07 +000010954 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10955 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010956 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010957
Alexis Hunt119f3652011-05-14 05:23:20 +000010958 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10959 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010960 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10961 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010962 ArgType = ArgType.withConst();
10963 ArgType = Context.getLValueReferenceType(ArgType);
10964
Richard Smith99005e62013-05-07 03:19:20 +000010965 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10966 CXXCopyAssignment,
10967 Const);
10968
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010969 // An implicitly-declared copy assignment operator is an inline public
10970 // member of its class.
10971 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010972 SourceLocation ClassLoc = ClassDecl->getLocation();
10973 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010974 CXXMethodDecl *CopyAssignment =
10975 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010976 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10977 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010978 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010979 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010980 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010981
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010982 if (getLangOpts().CUDA) {
10983 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10984 CopyAssignment,
10985 /* ConstRHS */ Const,
10986 /* Diagnose */ false);
10987 }
10988
Richard Smithd3b5c9082012-07-27 04:22:15 +000010989 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010990 FunctionProtoType::ExtProtoInfo EPI =
10991 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010992 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010993
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010994 // Add the parameter to the operator.
10995 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010996 ClassLoc, ClassLoc,
10997 /*Id=*/nullptr, ArgType,
10998 /*TInfo=*/nullptr, SC_None,
10999 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011000 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011001
Richard Smith6b02d462012-12-08 08:32:28 +000011002 CopyAssignment->setTrivial(
11003 ClassDecl->needsOverloadResolutionForCopyAssignment()
11004 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11005 : ClassDecl->hasTrivialCopyAssignment());
11006
Richard Smith6b02d462012-12-08 08:32:28 +000011007 // Note that we have added this copy-assignment operator.
11008 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11009
Richard Smith12e79312016-05-13 06:47:56 +000011010 Scope *S = getScopeForContext(ClassDecl);
11011 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11012
11013 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11014 SetDeclDeleted(CopyAssignment, ClassLoc);
11015
11016 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011017 PushOnScopeChains(CopyAssignment, S, false);
11018 ClassDecl->addDecl(CopyAssignment);
11019
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011020 return CopyAssignment;
11021}
11022
Richard Smithd577fbb2013-06-13 03:23:42 +000011023/// Diagnose an implicit copy operation for a class which is odr-used, but
11024/// which is deprecated because the class has a user-declared copy constructor,
11025/// copy assignment operator, or destructor.
11026static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11027 SourceLocation UseLoc) {
11028 assert(CopyOp->isImplicit());
11029
11030 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011031 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011032
11033 // In Microsoft mode, assignment operations don't affect constructors and
11034 // vice versa.
11035 if (RD->hasUserDeclaredDestructor()) {
11036 UserDeclaredOperation = RD->getDestructor();
11037 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11038 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011039 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011040 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011041 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011042 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011043 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011044 break;
11045 }
11046 }
11047 assert(UserDeclaredOperation);
11048 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11049 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011050 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011051 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011052 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011053 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011054 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011055 break;
11056 }
11057 }
11058 assert(UserDeclaredOperation);
11059 }
11060
11061 if (UserDeclaredOperation) {
11062 S.Diag(UserDeclaredOperation->getLocation(),
11063 diag::warn_deprecated_copy_operation)
11064 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11065 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11066 S.Diag(UseLoc, diag::note_member_synthesized_at)
11067 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11068 : Sema::CXXCopyAssignment)
11069 << RD;
11070 }
11071}
11072
Douglas Gregorb139cd52010-05-01 20:49:11 +000011073void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11074 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011075 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011076 CopyAssignOperator->isOverloadedOperator() &&
11077 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011078 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11079 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011080 "DefineImplicitCopyAssignment called for wrong function");
11081
11082 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11083
11084 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11085 CopyAssignOperator->setInvalidDecl();
11086 return;
11087 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011088
11089 // C++11 [class.copy]p18:
11090 // The [definition of an implicitly declared copy assignment operator] is
11091 // deprecated if the class has a user-declared copy constructor or a
11092 // user-declared destructor.
11093 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11094 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11095
Eli Friedman276dd182013-09-05 00:02:25 +000011096 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011097
Eli Friedmaneaf34142012-10-18 20:14:08 +000011098 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011099 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011100
11101 // C++0x [class.copy]p30:
11102 // The implicitly-defined or explicitly-defaulted copy assignment operator
11103 // for a non-union class X performs memberwise copy assignment of its
11104 // subobjects. The direct base classes of X are assigned first, in the
11105 // order of their declaration in the base-specifier-list, and then the
11106 // immediate non-static data members of X are assigned, in the order in
11107 // which they were declared in the class definition.
11108
11109 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011110 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011111
11112 // The parameter for the "other" object, which we are copying from.
11113 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11114 Qualifiers OtherQuals = Other->getType().getQualifiers();
11115 QualType OtherRefType = Other->getType();
11116 if (const LValueReferenceType *OtherRef
11117 = OtherRefType->getAs<LValueReferenceType>()) {
11118 OtherRefType = OtherRef->getPointeeType();
11119 OtherQuals = OtherRefType.getQualifiers();
11120 }
11121
11122 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011123 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11124 ? CopyAssignOperator->getLocEnd()
11125 : CopyAssignOperator->getLocation();
11126
Pavel Labath58934982013-08-30 08:52:28 +000011127 // Builds a DeclRefExpr for the "other" object.
11128 RefBuilder OtherRef(Other, OtherRefType);
11129
11130 // Builds the "this" pointer.
11131 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011132
11133 // Assign base classes.
11134 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011135 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011136 // Form the assignment:
11137 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011138 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011139 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011140 Invalid = true;
11141 continue;
11142 }
11143
John McCallcf142162010-08-07 06:22:56 +000011144 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011145 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011146
Douglas Gregorb139cd52010-05-01 20:49:11 +000011147 // Construct the "from" expression, which is an implicit cast to the
11148 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011149 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11150 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011151
11152 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011153 DerefBuilder DerefThis(This);
11154 CastBuilder To(DerefThis,
11155 Context.getCVRQualifiedType(
11156 BaseType, CopyAssignOperator->getTypeQualifiers()),
11157 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011158
11159 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011160 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011161 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011162 /*CopyingBaseSubobject=*/true,
11163 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011164 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011165 Diag(CurrentLocation, diag::note_member_synthesized_at)
11166 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11167 CopyAssignOperator->setInvalidDecl();
11168 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011169 }
11170
11171 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011172 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011173 }
11174
Douglas Gregorb139cd52010-05-01 20:49:11 +000011175 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011176 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011177 // FIXME: We should form some kind of AST representation for the implied
11178 // memcpy in a union copy operation.
11179 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011180 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011181
11182 if (Field->isInvalidDecl()) {
11183 Invalid = true;
11184 continue;
11185 }
11186
Douglas Gregorb139cd52010-05-01 20:49:11 +000011187 // Check for members of reference type; we can't copy those.
11188 if (Field->getType()->isReferenceType()) {
11189 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11190 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11191 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011192 Diag(CurrentLocation, diag::note_member_synthesized_at)
11193 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011194 Invalid = true;
11195 continue;
11196 }
11197
11198 // Check for members of const-qualified, non-class type.
11199 QualType BaseType = Context.getBaseElementType(Field->getType());
11200 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11201 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11202 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11203 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011204 Diag(CurrentLocation, diag::note_member_synthesized_at)
11205 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011206 Invalid = true;
11207 continue;
11208 }
John McCall1b1a1db2011-06-17 00:18:42 +000011209
11210 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011211 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11212 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011213
11214 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011215 if (FieldType->isIncompleteArrayType()) {
11216 assert(ClassDecl->hasFlexibleArrayMember() &&
11217 "Incomplete array type is not valid");
11218 continue;
11219 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011220
11221 // Build references to the field in the object we're copying from and to.
11222 CXXScopeSpec SS; // Intentionally empty
11223 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11224 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011225 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011226 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011227
11228 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11229
11230 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011231
Douglas Gregorb139cd52010-05-01 20:49:11 +000011232 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011233 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011234 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011235 /*CopyingBaseSubobject=*/false,
11236 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011237 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011238 Diag(CurrentLocation, diag::note_member_synthesized_at)
11239 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11240 CopyAssignOperator->setInvalidDecl();
11241 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011242 }
11243
11244 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011245 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011246 }
11247
11248 if (!Invalid) {
11249 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011250 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011251
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011252 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011253 if (Return.isInvalid())
11254 Invalid = true;
11255 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011256 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011257
11258 if (Trap.hasErrorOccurred()) {
11259 Diag(CurrentLocation, diag::note_member_synthesized_at)
11260 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11261 Invalid = true;
11262 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011263 }
11264 }
11265
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011266 // The exception specification is needed because we are defining the
11267 // function.
11268 ResolveExceptionSpec(CurrentLocation,
11269 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11270
Douglas Gregorb139cd52010-05-01 20:49:11 +000011271 if (Invalid) {
11272 CopyAssignOperator->setInvalidDecl();
11273 return;
11274 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011275
11276 StmtResult Body;
11277 {
11278 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011279 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011280 /*isStmtExpr=*/false);
11281 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11282 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011283 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011284
11285 if (ASTMutationListener *L = getASTMutationListener()) {
11286 L->CompletedImplicitDefinition(CopyAssignOperator);
11287 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011288}
11289
Sebastian Redl22653ba2011-08-30 19:58:05 +000011290Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011291Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11292 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011293
Richard Smithd3b5c9082012-07-27 04:22:15 +000011294 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011295 if (ClassDecl->isInvalidDecl())
11296 return ExceptSpec;
11297
11298 // C++0x [except.spec]p14:
11299 // An implicitly declared special member function (Clause 12) shall have an
11300 // exception-specification. [...]
11301
11302 // It is unspecified whether or not an implicit move assignment operator
11303 // attempts to deduplicate calls to assignment operators of virtual bases are
11304 // made. As such, this exception specification is effectively unspecified.
11305 // Based on a similar decision made for constness in C++0x, we're erring on
11306 // the side of assuming such calls to be made regardless of whether they
11307 // actually happen.
11308 // Note that a move constructor is not implicitly declared when there are
11309 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000011310 for (const auto &Base : ClassDecl->bases()) {
11311 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000011312 continue;
11313
11314 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011315 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011316 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011317 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011318 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011319 }
11320
Aaron Ballman445a9392014-03-13 16:15:17 +000011321 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011322 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011323 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011324 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011325 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011326 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011327 }
11328
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011329 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011330 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011331 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011332 if (CXXMethodDecl *MoveAssign =
11333 LookupMovingAssignment(FieldClassDecl,
11334 FieldType.getCVRQualifiers(),
11335 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011336 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011337 }
11338 }
11339
11340 return ExceptSpec;
11341}
11342
11343CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011344 assert(ClassDecl->needsImplicitMoveAssignment());
11345
Richard Smith8bf22e52012-11-29 01:34:07 +000011346 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11347 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011348 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011349
Sebastian Redl22653ba2011-08-30 19:58:05 +000011350 // Note: The following rules are largely analoguous to the move
11351 // constructor rules.
11352
Sebastian Redl22653ba2011-08-30 19:58:05 +000011353 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11354 QualType RetType = Context.getLValueReferenceType(ArgType);
11355 ArgType = Context.getRValueReferenceType(ArgType);
11356
Richard Smith99005e62013-05-07 03:19:20 +000011357 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11358 CXXMoveAssignment,
11359 false);
11360
Sebastian Redl22653ba2011-08-30 19:58:05 +000011361 // An implicitly-declared move assignment operator is an inline public
11362 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011363 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11364 SourceLocation ClassLoc = ClassDecl->getLocation();
11365 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011366 CXXMethodDecl *MoveAssignment =
11367 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011368 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011369 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011370 MoveAssignment->setAccess(AS_public);
11371 MoveAssignment->setDefaulted();
11372 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011373
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011374 if (getLangOpts().CUDA) {
11375 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11376 MoveAssignment,
11377 /* ConstRHS */ false,
11378 /* Diagnose */ false);
11379 }
11380
Richard Smithd3b5c9082012-07-27 04:22:15 +000011381 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011382 FunctionProtoType::ExtProtoInfo EPI =
11383 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011384 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011385
Sebastian Redl22653ba2011-08-30 19:58:05 +000011386 // Add the parameter to the operator.
11387 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011388 ClassLoc, ClassLoc,
11389 /*Id=*/nullptr, ArgType,
11390 /*TInfo=*/nullptr, SC_None,
11391 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011392 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011393
Richard Smith6b02d462012-12-08 08:32:28 +000011394 MoveAssignment->setTrivial(
11395 ClassDecl->needsOverloadResolutionForMoveAssignment()
11396 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11397 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011398
Richard Smith12e79312016-05-13 06:47:56 +000011399 // Note that we have added this copy-assignment operator.
11400 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11401
11402 Scope *S = getScopeForContext(ClassDecl);
11403 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11404
Richard Smithd951a1d2012-02-18 02:02:13 +000011405 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011406 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11407 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011408 }
11409
Richard Smith12e79312016-05-13 06:47:56 +000011410 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011411 PushOnScopeChains(MoveAssignment, S, false);
11412 ClassDecl->addDecl(MoveAssignment);
11413
Sebastian Redl22653ba2011-08-30 19:58:05 +000011414 return MoveAssignment;
11415}
11416
Richard Smithb2504bd2013-11-04 04:26:14 +000011417/// Check if we're implicitly defining a move assignment operator for a class
11418/// with virtual bases. Such a move assignment might move-assign the virtual
11419/// base multiple times.
11420static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11421 SourceLocation CurrentLocation) {
11422 assert(!Class->isDependentContext() && "should not define dependent move");
11423
11424 // Only a virtual base could get implicitly move-assigned multiple times.
11425 // Only a non-trivial move assignment can observe this. We only want to
11426 // diagnose if we implicitly define an assignment operator that assigns
11427 // two base classes, both of which move-assign the same virtual base.
11428 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11429 Class->getNumBases() < 2)
11430 return;
11431
11432 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11433 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11434 VBaseMap VBases;
11435
Aaron Ballman574705e2014-03-13 15:41:46 +000011436 for (auto &BI : Class->bases()) {
11437 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011438 while (!Worklist.empty()) {
11439 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11440 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11441
11442 // If the base has no non-trivial move assignment operators,
11443 // we don't care about moves from it.
11444 if (!Base->hasNonTrivialMoveAssignment())
11445 continue;
11446
11447 // If there's nothing virtual here, skip it.
11448 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11449 continue;
11450
11451 // If we're not actually going to call a move assignment for this base,
11452 // or the selected move assignment is trivial, skip it.
11453 Sema::SpecialMemberOverloadResult *SMOR =
11454 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11455 /*ConstArg*/false, /*VolatileArg*/false,
11456 /*RValueThis*/true, /*ConstThis*/false,
11457 /*VolatileThis*/false);
11458 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11459 !SMOR->getMethod()->isMoveAssignmentOperator())
11460 continue;
11461
11462 if (BaseSpec->isVirtual()) {
11463 // We're going to move-assign this virtual base, and its move
11464 // assignment operator is not trivial. If this can happen for
11465 // multiple distinct direct bases of Class, diagnose it. (If it
11466 // only happens in one base, we'll diagnose it when synthesizing
11467 // that base class's move assignment operator.)
11468 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011469 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011470 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011471 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011472 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11473 << Class << Base;
11474 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11475 << (Base->getCanonicalDecl() ==
11476 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11477 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011478 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011479 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011480 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11481 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011482
11483 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011484 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011485 }
11486 } else {
11487 // Only walk over bases that have defaulted move assignment operators.
11488 // We assume that any user-provided move assignment operator handles
11489 // the multiple-moves-of-vbase case itself somehow.
11490 if (!SMOR->getMethod()->isDefaulted())
11491 continue;
11492
11493 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011494 for (auto &BI : Base->bases())
11495 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011496 }
11497 }
11498 }
11499}
11500
Sebastian Redl22653ba2011-08-30 19:58:05 +000011501void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11502 CXXMethodDecl *MoveAssignOperator) {
11503 assert((MoveAssignOperator->isDefaulted() &&
11504 MoveAssignOperator->isOverloadedOperator() &&
11505 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011506 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11507 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011508 "DefineImplicitMoveAssignment called for wrong function");
11509
11510 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11511
11512 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11513 MoveAssignOperator->setInvalidDecl();
11514 return;
11515 }
11516
Eli Friedman276dd182013-09-05 00:02:25 +000011517 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011518
Eli Friedmaneaf34142012-10-18 20:14:08 +000011519 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011520 DiagnosticErrorTrap Trap(Diags);
11521
11522 // C++0x [class.copy]p28:
11523 // The implicitly-defined or move assignment operator for a non-union class
11524 // X performs memberwise move assignment of its subobjects. The direct base
11525 // classes of X are assigned first, in the order of their declaration in the
11526 // base-specifier-list, and then the immediate non-static data members of X
11527 // are assigned, in the order in which they were declared in the class
11528 // definition.
11529
Richard Smithb2504bd2013-11-04 04:26:14 +000011530 // Issue a warning if our implicit move assignment operator will move
11531 // from a virtual base more than once.
11532 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011533
Sebastian Redl22653ba2011-08-30 19:58:05 +000011534 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011535 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011536
11537 // The parameter for the "other" object, which we are move from.
11538 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11539 QualType OtherRefType = Other->getType()->
11540 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011541 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011542 "Bad argument type of defaulted move assignment");
11543
11544 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011545 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11546 ? MoveAssignOperator->getLocEnd()
11547 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011548
Pavel Labath58934982013-08-30 08:52:28 +000011549 // Builds a reference to the "other" object.
11550 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011551 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011552 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011553
Pavel Labath58934982013-08-30 08:52:28 +000011554 // Builds the "this" pointer.
11555 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011556
Sebastian Redl22653ba2011-08-30 19:58:05 +000011557 // Assign base classes.
11558 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011559 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011560 // C++11 [class.copy]p28:
11561 // It is unspecified whether subobjects representing virtual base classes
11562 // are assigned more than once by the implicitly-defined copy assignment
11563 // operator.
11564 // FIXME: Do not assign to a vbase that will be assigned by some other base
11565 // class. For a move-assignment, this can result in the vbase being moved
11566 // multiple times.
11567
Sebastian Redl22653ba2011-08-30 19:58:05 +000011568 // Form the assignment:
11569 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011570 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011571 if (!BaseType->isRecordType()) {
11572 Invalid = true;
11573 continue;
11574 }
11575
11576 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011577 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011578
11579 // Construct the "from" expression, which is an implicit cast to the
11580 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011581 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011582
11583 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011584 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011585
11586 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011587 CastBuilder To(DerefThis,
11588 Context.getCVRQualifiedType(
11589 BaseType, MoveAssignOperator->getTypeQualifiers()),
11590 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011591
11592 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011593 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011594 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011595 /*CopyingBaseSubobject=*/true,
11596 /*Copying=*/false);
11597 if (Move.isInvalid()) {
11598 Diag(CurrentLocation, diag::note_member_synthesized_at)
11599 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11600 MoveAssignOperator->setInvalidDecl();
11601 return;
11602 }
11603
11604 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011605 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011606 }
11607
Sebastian Redl22653ba2011-08-30 19:58:05 +000011608 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011609 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011610 // FIXME: We should form some kind of AST representation for the implied
11611 // memcpy in a union copy operation.
11612 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011613 continue;
11614
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011615 if (Field->isInvalidDecl()) {
11616 Invalid = true;
11617 continue;
11618 }
11619
Sebastian Redl22653ba2011-08-30 19:58:05 +000011620 // Check for members of reference type; we can't move those.
11621 if (Field->getType()->isReferenceType()) {
11622 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11623 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11624 Diag(Field->getLocation(), diag::note_declared_at);
11625 Diag(CurrentLocation, diag::note_member_synthesized_at)
11626 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11627 Invalid = true;
11628 continue;
11629 }
11630
11631 // Check for members of const-qualified, non-class type.
11632 QualType BaseType = Context.getBaseElementType(Field->getType());
11633 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11634 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11635 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11636 Diag(Field->getLocation(), diag::note_declared_at);
11637 Diag(CurrentLocation, diag::note_member_synthesized_at)
11638 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11639 Invalid = true;
11640 continue;
11641 }
11642
11643 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011644 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11645 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011646
11647 QualType FieldType = Field->getType().getNonReferenceType();
11648 if (FieldType->isIncompleteArrayType()) {
11649 assert(ClassDecl->hasFlexibleArrayMember() &&
11650 "Incomplete array type is not valid");
11651 continue;
11652 }
11653
11654 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011655 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11656 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011657 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011658 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011659 MemberBuilder From(MoveOther, OtherRefType,
11660 /*IsArrow=*/false, MemberLookup);
11661 MemberBuilder To(This, getCurrentThisType(),
11662 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011663
Pavel Labath58934982013-08-30 08:52:28 +000011664 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011665 "Member reference with rvalue base must be rvalue except for reference "
11666 "members, which aren't allowed for move assignment.");
11667
Sebastian Redl22653ba2011-08-30 19:58:05 +000011668 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011669 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011670 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011671 /*CopyingBaseSubobject=*/false,
11672 /*Copying=*/false);
11673 if (Move.isInvalid()) {
11674 Diag(CurrentLocation, diag::note_member_synthesized_at)
11675 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11676 MoveAssignOperator->setInvalidDecl();
11677 return;
11678 }
Richard Smith11d19592012-11-12 23:33:00 +000011679
Sebastian Redl22653ba2011-08-30 19:58:05 +000011680 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011681 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011682 }
11683
11684 if (!Invalid) {
11685 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011686 ExprResult ThisObj =
11687 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11688
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011689 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011690 if (Return.isInvalid())
11691 Invalid = true;
11692 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011693 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011694
11695 if (Trap.hasErrorOccurred()) {
11696 Diag(CurrentLocation, diag::note_member_synthesized_at)
11697 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11698 Invalid = true;
11699 }
11700 }
11701 }
11702
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011703 // The exception specification is needed because we are defining the
11704 // function.
11705 ResolveExceptionSpec(CurrentLocation,
11706 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11707
Sebastian Redl22653ba2011-08-30 19:58:05 +000011708 if (Invalid) {
11709 MoveAssignOperator->setInvalidDecl();
11710 return;
11711 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011712
11713 StmtResult Body;
11714 {
11715 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011716 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011717 /*isStmtExpr=*/false);
11718 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11719 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011720 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011721
11722 if (ASTMutationListener *L = getASTMutationListener()) {
11723 L->CompletedImplicitDefinition(MoveAssignOperator);
11724 }
11725}
11726
Richard Smithd3b5c9082012-07-27 04:22:15 +000011727Sema::ImplicitExceptionSpecification
11728Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11729 CXXRecordDecl *ClassDecl = MD->getParent();
11730
11731 ImplicitExceptionSpecification ExceptSpec(*this);
11732 if (ClassDecl->isInvalidDecl())
11733 return ExceptSpec;
11734
11735 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011736 assert(T->getNumParams() >= 1 && "not a copy ctor");
11737 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011738
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011739 // C++ [except.spec]p14:
11740 // An implicitly declared special member function (Clause 12) shall have an
11741 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000011742 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011743 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000011744 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011745 continue;
11746
Douglas Gregora6d69502010-07-02 23:41:54 +000011747 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011748 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011749 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011750 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000011751 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011752 }
Aaron Ballman445a9392014-03-13 16:15:17 +000011753 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000011754 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011755 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011756 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011757 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000011758 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011759 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011760 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011761 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000011762 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11763 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000011764 LookupCopyingConstructor(FieldClassDecl,
11765 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000011766 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011767 }
11768 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011769
Richard Smithd3b5c9082012-07-27 04:22:15 +000011770 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000011771}
11772
11773CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11774 CXXRecordDecl *ClassDecl) {
11775 // C++ [class.copy]p4:
11776 // If the class definition does not explicitly declare a copy
11777 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011778 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011779
Richard Smith8bf22e52012-11-29 01:34:07 +000011780 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11781 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011782 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011783
Alexis Hunt913820d2011-05-13 06:10:58 +000011784 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11785 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011786 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011787 if (Const)
11788 ArgType = ArgType.withConst();
11789 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011790
Richard Smithb5800092012-06-10 05:43:50 +000011791 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11792 CXXCopyConstructor,
11793 Const);
11794
Douglas Gregor54be3392010-07-01 17:57:27 +000011795 DeclarationName Name
11796 = Context.DeclarationNames.getCXXConstructorName(
11797 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011798 SourceLocation ClassLoc = ClassDecl->getLocation();
11799 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011800
11801 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011802 // member of its class.
11803 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011804 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011805 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011806 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011807 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011808 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011809
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011810 if (getLangOpts().CUDA) {
11811 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11812 CopyConstructor,
11813 /* ConstRHS */ Const,
11814 /* Diagnose */ false);
11815 }
11816
Richard Smithd3b5c9082012-07-27 04:22:15 +000011817 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011818 FunctionProtoType::ExtProtoInfo EPI =
11819 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011820 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011821 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011822
Douglas Gregor54be3392010-07-01 17:57:27 +000011823 // Add the parameter to the constructor.
11824 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011825 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011826 /*IdentifierInfo=*/nullptr,
11827 ArgType, /*TInfo=*/nullptr,
11828 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011829 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011830
Richard Smith6b02d462012-12-08 08:32:28 +000011831 CopyConstructor->setTrivial(
11832 ClassDecl->needsOverloadResolutionForCopyConstructor()
11833 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11834 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011835
Richard Smith6b02d462012-12-08 08:32:28 +000011836 // Note that we have declared this constructor.
11837 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11838
Richard Smith12e79312016-05-13 06:47:56 +000011839 Scope *S = getScopeForContext(ClassDecl);
11840 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11841
11842 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11843 SetDeclDeleted(CopyConstructor, ClassLoc);
11844
11845 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011846 PushOnScopeChains(CopyConstructor, S, false);
11847 ClassDecl->addDecl(CopyConstructor);
11848
Douglas Gregor54be3392010-07-01 17:57:27 +000011849 return CopyConstructor;
11850}
11851
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011852void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011853 CXXConstructorDecl *CopyConstructor) {
11854 assert((CopyConstructor->isDefaulted() &&
11855 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011856 !CopyConstructor->doesThisDeclarationHaveABody() &&
11857 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011858 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011859
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011860 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011861 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011862
Richard Smithd577fbb2013-06-13 03:23:42 +000011863 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011864 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011865 // deprecated if the class has a user-declared copy assignment operator
11866 // or a user-declared destructor.
11867 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11868 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11869
Eli Friedmaneaf34142012-10-18 20:14:08 +000011870 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011871 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011872
David Blaikie3fc2f912013-01-17 05:26:25 +000011873 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011874 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011875 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011876 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011877 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011878 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011879 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11880 ? CopyConstructor->getLocEnd()
11881 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011882 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011883 CopyConstructor->setBody(
11884 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011885 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011886
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011887 // The exception specification is needed because we are defining the
11888 // function.
11889 ResolveExceptionSpec(CurrentLocation,
11890 CopyConstructor->getType()->castAs<FunctionProtoType>());
11891
Eli Friedman276dd182013-09-05 00:02:25 +000011892 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011893 MarkVTableUsed(CurrentLocation, ClassDecl);
11894
Sebastian Redlab238a72011-04-24 16:28:06 +000011895 if (ASTMutationListener *L = getASTMutationListener()) {
11896 L->CompletedImplicitDefinition(CopyConstructor);
11897 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011898}
11899
Sebastian Redl22653ba2011-08-30 19:58:05 +000011900Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011901Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11902 CXXRecordDecl *ClassDecl = MD->getParent();
11903
Sebastian Redl22653ba2011-08-30 19:58:05 +000011904 // C++ [except.spec]p14:
11905 // An implicitly declared special member function (Clause 12) shall have an
11906 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011907 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011908 if (ClassDecl->isInvalidDecl())
11909 return ExceptSpec;
11910
11911 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011912 for (const auto &B : ClassDecl->bases()) {
11913 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011914 continue;
11915
Aaron Ballman574705e2014-03-13 15:41:46 +000011916 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011917 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011918 CXXConstructorDecl *Constructor =
11919 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011920 // If this is a deleted function, add it anyway. This might be conformant
11921 // with the standard. This might not. I'm not sure. It might not matter.
11922 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011923 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011924 }
11925 }
11926
11927 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011928 for (const auto &B : ClassDecl->vbases()) {
11929 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011930 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011931 CXXConstructorDecl *Constructor =
11932 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011933 // If this is a deleted function, add it anyway. This might be conformant
11934 // with the standard. This might not. I'm not sure. It might not matter.
11935 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011936 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011937 }
11938 }
11939
11940 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011941 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011942 QualType FieldType = Context.getBaseElementType(F->getType());
11943 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11944 CXXConstructorDecl *Constructor =
11945 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011946 // If this is a deleted function, add it anyway. This might be conformant
11947 // with the standard. This might not. I'm not sure. It might not matter.
11948 // In particular, the problem is that this function never gets called. It
11949 // might just be ill-formed because this function attempts to refer to
11950 // a deleted function here.
11951 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011952 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011953 }
11954 }
11955
11956 return ExceptSpec;
11957}
11958
11959CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11960 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011961 assert(ClassDecl->needsImplicitMoveConstructor());
11962
Richard Smith8bf22e52012-11-29 01:34:07 +000011963 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11964 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011965 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011966
Sebastian Redl22653ba2011-08-30 19:58:05 +000011967 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11968 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011969
Richard Smithb5800092012-06-10 05:43:50 +000011970 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11971 CXXMoveConstructor,
11972 false);
11973
Sebastian Redl22653ba2011-08-30 19:58:05 +000011974 DeclarationName Name
11975 = Context.DeclarationNames.getCXXConstructorName(
11976 Context.getCanonicalType(ClassType));
11977 SourceLocation ClassLoc = ClassDecl->getLocation();
11978 DeclarationNameInfo NameInfo(Name, ClassLoc);
11979
Richard Smith99005e62013-05-07 03:19:20 +000011980 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011981 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011982 // member of its class.
11983 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011984 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011985 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011986 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011987 MoveConstructor->setAccess(AS_public);
11988 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011989
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011990 if (getLangOpts().CUDA) {
11991 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11992 MoveConstructor,
11993 /* ConstRHS */ false,
11994 /* Diagnose */ false);
11995 }
11996
Richard Smithd3b5c9082012-07-27 04:22:15 +000011997 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011998 FunctionProtoType::ExtProtoInfo EPI =
11999 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012000 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012001 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012002
Sebastian Redl22653ba2011-08-30 19:58:05 +000012003 // Add the parameter to the constructor.
12004 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12005 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012006 /*IdentifierInfo=*/nullptr,
12007 ArgType, /*TInfo=*/nullptr,
12008 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012009 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012010
Richard Smith6b02d462012-12-08 08:32:28 +000012011 MoveConstructor->setTrivial(
12012 ClassDecl->needsOverloadResolutionForMoveConstructor()
12013 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12014 : ClassDecl->hasTrivialMoveConstructor());
12015
Richard Smith12e79312016-05-13 06:47:56 +000012016 // Note that we have declared this constructor.
12017 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12018
12019 Scope *S = getScopeForContext(ClassDecl);
12020 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12021
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012022 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012023 ClassDecl->setImplicitMoveConstructorIsDeleted();
12024 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012025 }
12026
Richard Smith12e79312016-05-13 06:47:56 +000012027 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012028 PushOnScopeChains(MoveConstructor, S, false);
12029 ClassDecl->addDecl(MoveConstructor);
12030
12031 return MoveConstructor;
12032}
12033
12034void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12035 CXXConstructorDecl *MoveConstructor) {
12036 assert((MoveConstructor->isDefaulted() &&
12037 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012038 !MoveConstructor->doesThisDeclarationHaveABody() &&
12039 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012040 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12041
12042 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12043 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12044
Eli Friedmaneaf34142012-10-18 20:14:08 +000012045 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012046 DiagnosticErrorTrap Trap(Diags);
12047
David Blaikie3fc2f912013-01-17 05:26:25 +000012048 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012049 Trap.hasErrorOccurred()) {
12050 Diag(CurrentLocation, diag::note_member_synthesized_at)
12051 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12052 MoveConstructor->setInvalidDecl();
12053 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012054 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12055 ? MoveConstructor->getLocEnd()
12056 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012057 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012058 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012059 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012060 }
12061
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012062 // The exception specification is needed because we are defining the
12063 // function.
12064 ResolveExceptionSpec(CurrentLocation,
12065 MoveConstructor->getType()->castAs<FunctionProtoType>());
12066
Eli Friedman276dd182013-09-05 00:02:25 +000012067 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012068 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012069
12070 if (ASTMutationListener *L = getASTMutationListener()) {
12071 L->CompletedImplicitDefinition(MoveConstructor);
12072 }
12073}
12074
Douglas Gregor74f7d502012-02-15 19:33:52 +000012075bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012076 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012077}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012078
12079void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012080 SourceLocation CurrentLocation,
12081 CXXConversionDecl *Conv) {
12082 CXXRecordDecl *Lambda = Conv->getParent();
12083 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12084 // If we are defining a specialization of a conversion to function-ptr
12085 // cache the deduced template arguments for this specialization
12086 // so that we can use them to retrieve the corresponding call-operator
12087 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012088 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12089
Faisal Vali571df122013-09-29 08:45:24 +000012090 // Retrieve the corresponding call-operator specialization.
12091 if (Lambda->isGenericLambda()) {
12092 assert(Conv->isFunctionTemplateSpecialization());
12093 FunctionTemplateDecl *CallOpTemplate =
12094 CallOp->getDescribedFunctionTemplate();
12095 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012096 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012097 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012098 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012099 InsertPos);
12100 assert(CallOpSpec &&
12101 "Conversion operator must have a corresponding call operator");
12102 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12103 }
12104 // Mark the call operator referenced (and add to pending instantiations
12105 // if necessary).
12106 // For both the conversion and static-invoker template specializations
12107 // we construct their body's in this function, so no need to add them
12108 // to the PendingInstantiations.
12109 MarkFunctionReferenced(CurrentLocation, CallOp);
12110
Eli Friedmaneaf34142012-10-18 20:14:08 +000012111 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012112 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012113
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012114 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012115 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12116 // ... and get the corresponding specialization for a generic lambda.
12117 if (Lambda->isGenericLambda()) {
12118 assert(DeducedTemplateArgs &&
12119 "Must have deduced template arguments from Conversion Operator");
12120 FunctionTemplateDecl *InvokeTemplate =
12121 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012122 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012123 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012124 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012125 InsertPos);
12126 assert(InvokeSpec &&
12127 "Must have a corresponding static invoker specialization");
12128 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12129 }
12130 // Construct the body of the conversion function { return __invoke; }.
12131 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012132 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012133 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012134 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012135 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12136 Conv->getLocation(),
12137 Conv->getLocation()));
12138
12139 Conv->markUsed(Context);
12140 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012141
Faisal Vali571df122013-09-29 08:45:24 +000012142 // Fill in the __invoke function with a dummy implementation. IR generation
12143 // will fill in the actual details.
12144 Invoker->markUsed(Context);
12145 Invoker->setReferenced();
12146 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12147
Douglas Gregord3b672c2012-02-16 01:06:16 +000012148 if (ASTMutationListener *L = getASTMutationListener()) {
12149 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012150 L->CompletedImplicitDefinition(Invoker);
12151 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012152}
12153
Faisal Vali571df122013-09-29 08:45:24 +000012154
12155
Douglas Gregord3b672c2012-02-16 01:06:16 +000012156void Sema::DefineImplicitLambdaToBlockPointerConversion(
12157 SourceLocation CurrentLocation,
12158 CXXConversionDecl *Conv)
12159{
Faisal Vali850da1a2013-09-29 17:08:32 +000012160 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012161
Eli Friedman276dd182013-09-05 00:02:25 +000012162 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012163
Eli Friedmaneaf34142012-10-18 20:14:08 +000012164 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012165 DiagnosticErrorTrap Trap(Diags);
12166
Douglas Gregored90df32012-02-22 05:02:47 +000012167 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012168 Expr *This = ActOnCXXThis(CurrentLocation).get();
12169 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012170
Eli Friedman98b01ed2012-03-01 04:01:32 +000012171 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12172 Conv->getLocation(),
12173 Conv, DerefThis);
12174
12175 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12176 // behavior. Note that only the general conversion function does this
12177 // (since it's unusable otherwise); in the case where we inline the
12178 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012179 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012180 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12181 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012182 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012183
12184 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012185 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012186 Conv->setInvalidDecl();
12187 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012188 }
Douglas Gregored90df32012-02-22 05:02:47 +000012189
Douglas Gregored90df32012-02-22 05:02:47 +000012190 // Create the return statement that returns the block from the conversion
12191 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012192 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012193 if (Return.isInvalid()) {
12194 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12195 Conv->setInvalidDecl();
12196 return;
12197 }
12198
12199 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012200 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012201 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012202 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012203 Conv->getLocation()));
12204
Douglas Gregored90df32012-02-22 05:02:47 +000012205 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012206 if (ASTMutationListener *L = getASTMutationListener()) {
12207 L->CompletedImplicitDefinition(Conv);
12208 }
12209}
12210
Douglas Gregord2f70072012-03-10 06:53:13 +000012211/// \brief Determine whether the given list arguments contains exactly one
12212/// "real" (non-default) argument.
12213static bool hasOneRealArgument(MultiExprArg Args) {
12214 switch (Args.size()) {
12215 case 0:
12216 return false;
12217
12218 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012219 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012220 return false;
12221
12222 // fall through
12223 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012224 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012225 }
12226
12227 return false;
12228}
12229
John McCalldadc5752010-08-24 06:29:42 +000012230ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012231Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012232 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012233 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012234 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012235 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012236 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012237 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012238 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012239 unsigned ConstructKind,
12240 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012241 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012242
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012243 // C++0x [class.copy]p34:
12244 // When certain criteria are met, an implementation is allowed to
12245 // omit the copy/move construction of a class object, even if the
12246 // copy/move constructor and/or destructor for the object have
12247 // side effects. [...]
12248 // - when a temporary class object that has not been bound to a
12249 // reference (12.2) would be copied/moved to a class object
12250 // with the same cv-unqualified type, the copy/move operation
12251 // can be omitted by constructing the temporary object
12252 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012253 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012254 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012255 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012256 Elidable = SubExpr->isTemporaryObject(
12257 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012258 }
Mike Stump11289f42009-09-09 15:08:12 +000012259
Richard Smithc2bebe92016-05-11 20:37:46 +000012260 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12261 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012262 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012263 IsListInitialization,
12264 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012265 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012266}
12267
John McCalldadc5752010-08-24 06:29:42 +000012268ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012269Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012270 NamedDecl *FoundDecl,
12271 CXXConstructorDecl *Constructor,
12272 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012273 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012274 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012275 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012276 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012277 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012278 unsigned ConstructKind,
12279 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012280 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012281 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012282 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12283 return ExprError();
12284 }
Richard Smith5179eb72016-06-28 19:03:57 +000012285
Richard Smithc83bf822016-06-10 00:58:19 +000012286 return BuildCXXConstructExpr(
12287 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12288 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12289 RequiresZeroInit, ConstructKind, ParenRange);
12290}
12291
12292/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12293/// including handling of its default argument expressions.
12294ExprResult
12295Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12296 CXXConstructorDecl *Constructor,
12297 bool Elidable,
12298 MultiExprArg ExprArgs,
12299 bool HadMultipleCandidates,
12300 bool IsListInitialization,
12301 bool IsStdInitListInitialization,
12302 bool RequiresZeroInit,
12303 unsigned ConstructKind,
12304 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012305 assert(declaresSameEntity(
12306 Constructor->getParent(),
12307 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12308 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012309 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012310 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12311 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012312
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012313 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012314 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012315 ExprArgs, HadMultipleCandidates, IsListInitialization,
12316 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012317 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12318 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012319}
12320
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012321ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12322 assert(Field->hasInClassInitializer());
12323
12324 // If we already have the in-class initializer nothing needs to be done.
12325 if (Field->getInClassInitializer())
12326 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12327
12328 // Maybe we haven't instantiated the in-class initializer. Go check the
12329 // pattern FieldDecl to see if it has one.
12330 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12331
12332 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12333 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12334 DeclContext::lookup_result Lookup =
12335 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012336
12337 // Lookup can return at most two results: the pattern for the field, or the
12338 // injected class name of the parent record. No other member can have the
12339 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012340 // In modules mode, lookup can return multiple results (coming from
12341 // different modules).
12342 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012343 "more than two lookup results for field name");
12344 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12345 if (!Pattern) {
12346 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12347 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012348 for (auto L : Lookup)
12349 if (isa<FieldDecl>(L)) {
12350 Pattern = cast<FieldDecl>(L);
12351 break;
12352 }
12353 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012354 }
12355
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012356 if (InstantiateInClassInitializer(Loc, Field, Pattern,
12357 getTemplateInstantiationArgs(Field)))
12358 return ExprError();
12359 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12360 }
12361
12362 // DR1351:
12363 // If the brace-or-equal-initializer of a non-static data member
12364 // invokes a defaulted default constructor of its class or of an
12365 // enclosing class in a potentially evaluated subexpression, the
12366 // program is ill-formed.
12367 //
12368 // This resolution is unworkable: the exception specification of the
12369 // default constructor can be needed in an unevaluated context, in
12370 // particular, in the operand of a noexcept-expression, and we can be
12371 // unable to compute an exception specification for an enclosed class.
12372 //
12373 // Any attempt to resolve the exception specification of a defaulted default
12374 // constructor before the initializer is lexically complete will ultimately
12375 // come here at which point we can diagnose it.
12376 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012377 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12378 << OutermostClass << Field;
12379 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012380
12381 return ExprError();
12382}
12383
John McCall03c48482010-02-02 09:10:11 +000012384void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012385 if (VD->isInvalidDecl()) return;
12386
John McCall03c48482010-02-02 09:10:11 +000012387 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012388 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012389 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012390 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012391
Chandler Carruth86d17d32011-03-27 21:26:48 +000012392 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012393 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012394 CheckDestructorAccess(VD->getLocation(), Destructor,
12395 PDiag(diag::err_access_dtor_var)
12396 << VD->getDeclName()
12397 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012398 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012399
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012400 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012401 if (!VD->hasGlobalStorage()) return;
12402
12403 // Emit warning for non-trivial dtor in global scope (a real global,
12404 // class-static, function-static).
12405 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12406
12407 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012408 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012409 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012410}
12411
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012412/// \brief Given a constructor and the set of arguments provided for the
12413/// constructor, convert the arguments and add any required default arguments
12414/// to form a proper call to this constructor.
12415///
12416/// \returns true if an error occurred, false otherwise.
12417bool
12418Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12419 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012420 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012421 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012422 bool AllowExplicit,
12423 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012424 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12425 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012426 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012427
12428 const FunctionProtoType *Proto
12429 = Constructor->getType()->getAs<FunctionProtoType>();
12430 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012431 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012432
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012433 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012434 if (NumArgs < NumParams)
12435 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012436 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012437 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012438
12439 VariadicCallType CallType =
12440 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012441 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012442 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012443 Proto, 0,
12444 llvm::makeArrayRef(Args, NumArgs),
12445 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012446 CallType, AllowExplicit,
12447 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012448 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012449
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012450 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012451
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012452 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012453 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012454 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012455
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012456 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012457}
12458
Anders Carlssone363c8e2009-12-12 00:32:00 +000012459static inline bool
12460CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12461 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012462 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012463 if (isa<NamespaceDecl>(DC)) {
12464 return SemaRef.Diag(FnDecl->getLocation(),
12465 diag::err_operator_new_delete_declared_in_namespace)
12466 << FnDecl->getDeclName();
12467 }
12468
12469 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012470 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012471 return SemaRef.Diag(FnDecl->getLocation(),
12472 diag::err_operator_new_delete_declared_static)
12473 << FnDecl->getDeclName();
12474 }
12475
Anders Carlsson60659a82009-12-12 02:43:16 +000012476 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012477}
12478
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012479static inline bool
12480CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12481 CanQualType ExpectedResultType,
12482 CanQualType ExpectedFirstParamType,
12483 unsigned DependentParamTypeDiag,
12484 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012485 QualType ResultType =
12486 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012487
12488 // Check that the result type is not dependent.
12489 if (ResultType->isDependentType())
12490 return SemaRef.Diag(FnDecl->getLocation(),
12491 diag::err_operator_new_delete_dependent_result_type)
12492 << FnDecl->getDeclName() << ExpectedResultType;
12493
12494 // Check that the result type is what we expect.
12495 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12496 return SemaRef.Diag(FnDecl->getLocation(),
12497 diag::err_operator_new_delete_invalid_result_type)
12498 << FnDecl->getDeclName() << ExpectedResultType;
12499
12500 // A function template must have at least 2 parameters.
12501 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12502 return SemaRef.Diag(FnDecl->getLocation(),
12503 diag::err_operator_new_delete_template_too_few_parameters)
12504 << FnDecl->getDeclName();
12505
12506 // The function decl must have at least 1 parameter.
12507 if (FnDecl->getNumParams() == 0)
12508 return SemaRef.Diag(FnDecl->getLocation(),
12509 diag::err_operator_new_delete_too_few_parameters)
12510 << FnDecl->getDeclName();
12511
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012512 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012513 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12514 if (FirstParamType->isDependentType())
12515 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12516 << FnDecl->getDeclName() << ExpectedFirstParamType;
12517
12518 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012519 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012520 ExpectedFirstParamType)
12521 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12522 << FnDecl->getDeclName() << ExpectedFirstParamType;
12523
12524 return false;
12525}
12526
Anders Carlsson12308f42009-12-11 23:23:22 +000012527static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012528CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012529 // C++ [basic.stc.dynamic.allocation]p1:
12530 // A program is ill-formed if an allocation function is declared in a
12531 // namespace scope other than global scope or declared static in global
12532 // scope.
12533 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12534 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012535
12536 CanQualType SizeTy =
12537 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12538
12539 // C++ [basic.stc.dynamic.allocation]p1:
12540 // The return type shall be void*. The first parameter shall have type
12541 // std::size_t.
12542 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12543 SizeTy,
12544 diag::err_operator_new_dependent_param_type,
12545 diag::err_operator_new_param_type))
12546 return true;
12547
12548 // C++ [basic.stc.dynamic.allocation]p1:
12549 // The first parameter shall not have an associated default argument.
12550 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012551 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012552 diag::err_operator_new_default_arg)
12553 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12554
12555 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012556}
12557
12558static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012559CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012560 // C++ [basic.stc.dynamic.deallocation]p1:
12561 // A program is ill-formed if deallocation functions are declared in a
12562 // namespace scope other than global scope or declared static in global
12563 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012564 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12565 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012566
12567 // C++ [basic.stc.dynamic.deallocation]p2:
12568 // Each deallocation function shall return void and its first parameter
12569 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012570 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12571 SemaRef.Context.VoidPtrTy,
12572 diag::err_operator_delete_dependent_param_type,
12573 diag::err_operator_delete_param_type))
12574 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012575
Anders Carlsson12308f42009-12-11 23:23:22 +000012576 return false;
12577}
12578
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012579/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12580/// of this overloaded operator is well-formed. If so, returns false;
12581/// otherwise, emits appropriate diagnostics and returns true.
12582bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012583 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012584 "Expected an overloaded operator declaration");
12585
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012586 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12587
Mike Stump11289f42009-09-09 15:08:12 +000012588 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012589 // The allocation and deallocation functions, operator new,
12590 // operator new[], operator delete and operator delete[], are
12591 // described completely in 3.7.3. The attributes and restrictions
12592 // found in the rest of this subclause do not apply to them unless
12593 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012594 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012595 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012596
Anders Carlsson22f443f2009-12-12 00:26:23 +000012597 if (Op == OO_New || Op == OO_Array_New)
12598 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012599
12600 // C++ [over.oper]p6:
12601 // An operator function shall either be a non-static member
12602 // function or be a non-member function and have at least one
12603 // parameter whose type is a class, a reference to a class, an
12604 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012605 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12606 if (MethodDecl->isStatic())
12607 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012608 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012609 } else {
12610 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012611 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012612 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012613 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12614 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012615 ClassOrEnumParam = true;
12616 break;
12617 }
12618 }
12619
Douglas Gregord69246b2008-11-17 16:14:12 +000012620 if (!ClassOrEnumParam)
12621 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012622 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012623 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012624 }
12625
12626 // C++ [over.oper]p8:
12627 // An operator function cannot have default arguments (8.3.6),
12628 // except where explicitly stated below.
12629 //
Mike Stump11289f42009-09-09 15:08:12 +000012630 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012631 // (C++ [over.call]p1).
12632 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012633 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012634 if (Param->hasDefaultArg())
12635 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012636 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012637 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012638 }
12639 }
12640
Douglas Gregor6cf08062008-11-10 13:38:07 +000012641 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12642 { false, false, false }
12643#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12644 , { Unary, Binary, MemberOnly }
12645#include "clang/Basic/OperatorKinds.def"
12646 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012647
Douglas Gregor6cf08062008-11-10 13:38:07 +000012648 bool CanBeUnaryOperator = OperatorUses[Op][0];
12649 bool CanBeBinaryOperator = OperatorUses[Op][1];
12650 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012651
12652 // C++ [over.oper]p8:
12653 // [...] Operator functions cannot have more or fewer parameters
12654 // than the number required for the corresponding operator, as
12655 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012656 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012657 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012658 if (Op != OO_Call &&
12659 ((NumParams == 1 && !CanBeUnaryOperator) ||
12660 (NumParams == 2 && !CanBeBinaryOperator) ||
12661 (NumParams < 1) || (NumParams > 2))) {
12662 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012663 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012664 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012665 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012666 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012667 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012668 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012669 assert(CanBeBinaryOperator &&
12670 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012671 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012672 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012673
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012674 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012675 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012676 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012677
Douglas Gregord69246b2008-11-17 16:14:12 +000012678 // Overloaded operators other than operator() cannot be variadic.
12679 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012680 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012681 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012682 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012683 }
12684
12685 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012686 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12687 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012688 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012689 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012690 }
12691
12692 // C++ [over.inc]p1:
12693 // The user-defined function called operator++ implements the
12694 // prefix and postfix ++ operator. If this function is a member
12695 // function with no parameters, or a non-member function with one
12696 // parameter of class or enumeration type, it defines the prefix
12697 // increment operator ++ for objects of that type. If the function
12698 // is a member function with one parameter (which shall be of type
12699 // int) or a non-member function with two parameters (the second
12700 // of which shall be of type int), it defines the postfix
12701 // increment operator ++ for objects of that type.
12702 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12703 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012704 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012705
Richard Smith538b52a2014-01-30 22:24:05 +000012706 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12707 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012708 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012709 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012710 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012711 }
12712
Douglas Gregord69246b2008-11-17 16:14:12 +000012713 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012714}
Chris Lattner3b024a32008-12-17 07:09:26 +000012715
Richard Smithc28aee62016-02-17 00:04:04 +000012716static bool
12717checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12718 FunctionTemplateDecl *TpDecl) {
12719 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12720
12721 // Must have one or two template parameters.
12722 if (TemplateParams->size() == 1) {
12723 NonTypeTemplateParmDecl *PmDecl =
12724 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12725
12726 // The template parameter must be a char parameter pack.
12727 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12728 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12729 return false;
12730
12731 } else if (TemplateParams->size() == 2) {
12732 TemplateTypeParmDecl *PmType =
12733 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12734 NonTypeTemplateParmDecl *PmArgs =
12735 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12736
12737 // The second template parameter must be a parameter pack with the
12738 // first template parameter as its type.
12739 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12740 PmArgs->isTemplateParameterPack()) {
12741 const TemplateTypeParmType *TArgs =
12742 PmArgs->getType()->getAs<TemplateTypeParmType>();
12743 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12744 TArgs->getIndex() == PmType->getIndex()) {
12745 if (SemaRef.ActiveTemplateInstantiations.empty())
12746 SemaRef.Diag(TpDecl->getLocation(),
12747 diag::ext_string_literal_operator_template);
12748 return false;
12749 }
12750 }
12751 }
12752
12753 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12754 diag::err_literal_operator_template)
12755 << TpDecl->getTemplateParameters()->getSourceRange();
12756 return true;
12757}
12758
Alexis Huntc88db062010-01-13 09:01:02 +000012759/// CheckLiteralOperatorDeclaration - Check whether the declaration
12760/// of this literal operator function is well-formed. If so, returns
12761/// false; otherwise, emits appropriate diagnostics and returns true.
12762bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012763 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012764 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12765 << FnDecl->getDeclName();
12766 return true;
12767 }
12768
Richard Smith72eebee2012-03-04 09:41:16 +000012769 if (FnDecl->isExternC()) {
12770 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012771 if (const LinkageSpecDecl *LSD =
12772 FnDecl->getDeclContext()->getExternCContext())
12773 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012774 return true;
12775 }
12776
Richard Smithbcc22fc2012-03-09 08:00:36 +000012777 // This might be the definition of a literal operator template.
12778 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012779
Richard Smithbcc22fc2012-03-09 08:00:36 +000012780 // This might be a specialization of a literal operator template.
12781 if (!TpDecl)
12782 TpDecl = FnDecl->getPrimaryTemplate();
12783
Richard Smithb8b41d32013-10-07 19:57:58 +000012784 // template <char...> type operator "" name() and
12785 // template <class T, T...> type operator "" name() are the only valid
12786 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012787 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012788 if (FnDecl->param_size() != 0) {
12789 Diag(FnDecl->getLocation(),
12790 diag::err_literal_operator_template_with_params);
12791 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012792 }
Richard Smithc28aee62016-02-17 00:04:04 +000012793
12794 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12795 return true;
12796
12797 } else if (FnDecl->param_size() == 1) {
12798 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12799
12800 QualType ParamType = Param->getType().getUnqualifiedType();
12801
12802 // Only unsigned long long int, long double, any character type, and const
12803 // char * are allowed as the only parameters.
12804 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12805 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12806 Context.hasSameType(ParamType, Context.CharTy) ||
12807 Context.hasSameType(ParamType, Context.WideCharTy) ||
12808 Context.hasSameType(ParamType, Context.Char16Ty) ||
12809 Context.hasSameType(ParamType, Context.Char32Ty)) {
12810 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12811 QualType InnerType = Ptr->getPointeeType();
12812
12813 // Pointer parameter must be a const char *.
12814 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12815 Context.CharTy) &&
12816 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12817 Diag(Param->getSourceRange().getBegin(),
12818 diag::err_literal_operator_param)
12819 << ParamType << "'const char *'" << Param->getSourceRange();
12820 return true;
12821 }
12822
12823 } else if (ParamType->isRealFloatingType()) {
12824 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12825 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12826 return true;
12827
12828 } else if (ParamType->isIntegerType()) {
12829 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12830 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12831 return true;
12832
12833 } else {
12834 Diag(Param->getSourceRange().getBegin(),
12835 diag::err_literal_operator_invalid_param)
12836 << ParamType << Param->getSourceRange();
12837 return true;
12838 }
12839
12840 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012841 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12842
Richard Smithc28aee62016-02-17 00:04:04 +000012843 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012844
Richard Smithc28aee62016-02-17 00:04:04 +000012845 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12846
12847 // Two parameter function must have a pointer to const as a
12848 // first parameter; let's strip those qualifiers.
12849 const PointerType *PT = FirstParamType->getAs<PointerType>();
12850
12851 if (!PT) {
12852 Diag((*Param)->getSourceRange().getBegin(),
12853 diag::err_literal_operator_param)
12854 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12855 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012856 }
12857
Richard Smithc28aee62016-02-17 00:04:04 +000012858 QualType PointeeType = PT->getPointeeType();
12859 // First parameter must be const
12860 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12861 Diag((*Param)->getSourceRange().getBegin(),
12862 diag::err_literal_operator_param)
12863 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12864 return true;
12865 }
Alexis Huntc88db062010-01-13 09:01:02 +000012866
Richard Smithc28aee62016-02-17 00:04:04 +000012867 QualType InnerType = PointeeType.getUnqualifiedType();
12868 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12869 // are allowed as the first parameter to a two-parameter function
12870 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12871 Context.hasSameType(InnerType, Context.WideCharTy) ||
12872 Context.hasSameType(InnerType, Context.Char16Ty) ||
12873 Context.hasSameType(InnerType, Context.Char32Ty))) {
12874 Diag((*Param)->getSourceRange().getBegin(),
12875 diag::err_literal_operator_param)
12876 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12877 return true;
12878 }
12879
12880 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012881 ++Param;
12882
Richard Smithc28aee62016-02-17 00:04:04 +000012883 // The second parameter must be a std::size_t.
12884 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12885 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12886 Diag((*Param)->getSourceRange().getBegin(),
12887 diag::err_literal_operator_param)
12888 << SecondParamType << Context.getSizeType()
12889 << (*Param)->getSourceRange();
12890 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012891 }
Richard Smithc28aee62016-02-17 00:04:04 +000012892 } else {
12893 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012894 return true;
12895 }
12896
Richard Smithc28aee62016-02-17 00:04:04 +000012897 // Parameters are good.
12898
Richard Smith768cecc2012-03-09 08:16:22 +000012899 // A parameter-declaration-clause containing a default argument is not
12900 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012901 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012902 if (Param->hasDefaultArg()) {
12903 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012904 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012905 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012906 break;
12907 }
12908 }
12909
Richard Smith0df56f42012-03-08 02:39:21 +000012910 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012911 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12912 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012913 // C++11 [usrlit.suffix]p1:
12914 // Literal suffix identifiers that do not start with an underscore
12915 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012916 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12917 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012918 }
Richard Smith0df56f42012-03-08 02:39:21 +000012919
Alexis Huntc88db062010-01-13 09:01:02 +000012920 return false;
12921}
12922
Douglas Gregor07665a62009-01-05 19:45:36 +000012923/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12924/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012925/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12926/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012927/// the '{' brace. Otherwise, this linkage specification does not
12928/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012929Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012930 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012931 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012932 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12933 if (!Lit->isAscii()) {
12934 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12935 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012936 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012937 }
12938
12939 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012940 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012941 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012942 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012943 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012944 Language = LinkageSpecDecl::lang_cxx;
12945 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012946 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12947 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012948 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012949 }
Mike Stump11289f42009-09-09 15:08:12 +000012950
Chris Lattner438e5012008-12-17 07:13:27 +000012951 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000012952
Richard Smith4ee696d2014-02-17 23:25:27 +000012953 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12954 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000012955 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012956 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000012957 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000012958 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000012959}
12960
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000012961/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000012962/// the C++ linkage specification LinkageSpec. If RBraceLoc is
12963/// valid, it's the position of the closing '}' brace in a linkage
12964/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000012965Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012966 Decl *LinkageSpec,
12967 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012968 if (RBraceLoc.isValid()) {
12969 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12970 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012971 }
Richard Smith4ee696d2014-02-17 23:25:27 +000012972 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000012973 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000012974}
12975
Michael Han84324352013-02-22 17:15:32 +000012976Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12977 AttributeList *AttrList,
12978 SourceLocation SemiLoc) {
12979 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12980 // Attribute declarations appertain to empty declaration so we handle
12981 // them here.
12982 if (AttrList)
12983 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000012984
Michael Han84324352013-02-22 17:15:32 +000012985 CurContext->addDecl(ED);
12986 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000012987}
12988
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012989/// \brief Perform semantic analysis for the variable declaration that
12990/// occurs within a C++ catch clause, returning the newly-created
12991/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012992VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000012993 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012994 SourceLocation StartLoc,
12995 SourceLocation Loc,
12996 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012997 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012998 QualType ExDeclType = TInfo->getType();
12999
Sebastian Redl54c04d42008-12-22 19:15:10 +000013000 // Arrays and functions decay.
13001 if (ExDeclType->isArrayType())
13002 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13003 else if (ExDeclType->isFunctionType())
13004 ExDeclType = Context.getPointerType(ExDeclType);
13005
13006 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13007 // The exception-declaration shall not denote a pointer or reference to an
13008 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013009 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013010 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013011 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013012 Invalid = true;
13013 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013014
David Majnemere56d1a02016-06-08 16:05:07 +000013015 if (ExDeclType->isVariablyModifiedType()) {
13016 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13017 Invalid = true;
13018 }
13019
Sebastian Redl54c04d42008-12-22 19:15:10 +000013020 QualType BaseType = ExDeclType;
13021 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013022 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013023 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013024 BaseType = Ptr->getPointeeType();
13025 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013026 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013027 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013028 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013029 BaseType = Ref->getPointeeType();
13030 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013031 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013032 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013033 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013034 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013035 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013036
Mike Stump11289f42009-09-09 15:08:12 +000013037 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013038 RequireNonAbstractType(Loc, ExDeclType,
13039 diag::err_abstract_type_in_decl,
13040 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013041 Invalid = true;
13042
John McCall2ca705e2010-07-24 00:37:23 +000013043 // Only the non-fragile NeXT runtime currently supports C++ catches
13044 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013045 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013046 QualType T = ExDeclType;
13047 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13048 T = RT->getPointeeType();
13049
13050 if (T->isObjCObjectType()) {
13051 Diag(Loc, diag::err_objc_object_catch);
13052 Invalid = true;
13053 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013054 // FIXME: should this be a test for macosx-fragile specifically?
13055 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013056 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013057 }
13058 }
13059
Abramo Bagnaradff19302011-03-08 08:55:46 +000013060 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013061 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013062 ExDecl->setExceptionVariable(true);
13063
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013064 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013065 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013066 Invalid = true;
13067
Douglas Gregor750734c2011-07-06 18:14:43 +000013068 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013069 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013070 // Insulate this from anything else we might currently be parsing.
13071 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13072
Douglas Gregor6de584c2010-03-05 23:38:39 +000013073 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013074 // The object declared in an exception-declaration or, if the
13075 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013076 // copy-initialized (8.5) from the exception object. [...]
13077 // The object is destroyed when the handler exits, after the destruction
13078 // of any automatic objects initialized within the handler.
13079 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013080 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013081 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013082 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013083
13084 InitializedEntity entity =
13085 InitializedEntity::InitializeVariable(ExDecl);
13086 InitializationKind initKind =
13087 InitializationKind::CreateCopy(Loc, SourceLocation());
13088
13089 Expr *opaqueValue =
13090 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013091 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13092 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013093 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013094 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013095 else {
13096 // If the constructor used was non-trivial, set this as the
13097 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013098 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013099 if (!construct->getConstructor()->isTrivial()) {
13100 Expr *init = MaybeCreateExprWithCleanups(construct);
13101 ExDecl->setInit(init);
13102 }
13103
13104 // And make sure it's destructable.
13105 FinalizeVarWithDestructor(ExDecl, recordType);
13106 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013107 }
13108 }
13109
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013110 if (Invalid)
13111 ExDecl->setInvalidDecl();
13112
13113 return ExDecl;
13114}
13115
13116/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13117/// handler.
John McCall48871652010-08-21 09:40:31 +000013118Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013120 bool Invalid = D.isInvalidType();
13121
13122 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013123 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13124 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013125 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13126 D.getIdentifierLoc());
13127 Invalid = true;
13128 }
13129
Sebastian Redl54c04d42008-12-22 19:15:10 +000013130 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013131 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013132 LookupOrdinaryName,
13133 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013134 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013135 // it contains any previous declaration, except for function parameters in
13136 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013137 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013138 if (isDeclInScope(PrevDecl, CurContext, S)) {
13139 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13140 << D.getIdentifier();
13141 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13142 Invalid = true;
13143 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013144 // Maybe we will complain about the shadowed template parameter.
13145 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013146 }
13147
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013148 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013149 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13150 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013151 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013152 }
13153
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013154 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013155 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013156 D.getIdentifierLoc(),
13157 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013158 if (Invalid)
13159 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013160
Sebastian Redl54c04d42008-12-22 19:15:10 +000013161 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013162 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013163 PushOnScopeChains(ExDecl, S);
13164 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013165 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013166
Douglas Gregor758a8692009-06-17 21:51:59 +000013167 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013168 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013169}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013170
Abramo Bagnaraea947882011-03-08 16:41:52 +000013171Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013172 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013173 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013174 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013175 StringLiteral *AssertMessage =
13176 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013177
Richard Smithded9c2e2012-07-11 22:37:56 +000013178 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013179 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013180
13181 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13182 AssertMessage, RParenLoc, false);
13183}
13184
13185Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13186 Expr *AssertExpr,
13187 StringLiteral *AssertMessage,
13188 SourceLocation RParenLoc,
13189 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013190 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013191 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13192 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013193 // In a static_assert-declaration, the constant-expression shall be a
13194 // constant expression that can be contextually converted to bool.
13195 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13196 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013197 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013198
Richard Smith902ca212011-12-14 23:32:26 +000013199 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013200 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013201 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013202 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013203 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013204
Richard Smithded9c2e2012-07-11 22:37:56 +000013205 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013206 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013207 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013208 if (AssertMessage)
13209 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013210 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013211 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013212 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013213 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013214 }
Mike Stump11289f42009-09-09 15:08:12 +000013215
Abramo Bagnaraea947882011-03-08 16:41:52 +000013216 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013217 AssertExpr, AssertMessage, RParenLoc,
13218 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013219
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013220 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013221 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013222}
Sebastian Redlf769df52009-03-24 22:27:57 +000013223
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013224/// \brief Perform semantic analysis of the given friend type declaration.
13225///
13226/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013227FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013228 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013229 TypeSourceInfo *TSInfo) {
13230 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13231
13232 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013233 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013234
Richard Smithc8239732011-10-18 21:39:00 +000013235 // C++03 [class.friend]p2:
13236 // An elaborated-type-specifier shall be used in a friend declaration
13237 // for a class.*
13238 //
13239 // * The class-key of the elaborated-type-specifier is required.
13240 if (!ActiveTemplateInstantiations.empty()) {
13241 // Do not complain about the form of friend template types during
13242 // template instantiation; we will already have complained when the
13243 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000013244 } else {
13245 if (!T->isElaboratedTypeSpecifier()) {
13246 // If we evaluated the type to a record type, suggest putting
13247 // a tag in front.
13248 if (const RecordType *RT = T->getAs<RecordType>()) {
13249 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013250
13251 SmallString<16> InsertionText(" ");
13252 InsertionText += RD->getKindName();
13253
Nick Lewycky36722d22013-02-06 05:59:33 +000013254 Diag(TypeRange.getBegin(),
13255 getLangOpts().CPlusPlus11 ?
13256 diag::warn_cxx98_compat_unelaborated_friend_type :
13257 diag::ext_unelaborated_friend_type)
13258 << (unsigned) RD->getTagKind()
13259 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013260 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013261 InsertionText);
13262 } else {
13263 Diag(FriendLoc,
13264 getLangOpts().CPlusPlus11 ?
13265 diag::warn_cxx98_compat_nonclass_type_friend :
13266 diag::ext_nonclass_type_friend)
13267 << T
13268 << TypeRange;
13269 }
13270 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013271 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013272 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013273 diag::warn_cxx98_compat_enum_friend :
13274 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013275 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013276 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013277 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013278
Nick Lewycky36722d22013-02-06 05:59:33 +000013279 // C++11 [class.friend]p3:
13280 // A friend declaration that does not declare a function shall have one
13281 // of the following forms:
13282 // friend elaborated-type-specifier ;
13283 // friend simple-type-specifier ;
13284 // friend typename-specifier ;
13285 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13286 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13287 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013288
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013289 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013290 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013291 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013292 return FriendDecl::Create(Context, CurContext,
13293 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13294 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013295}
13296
John McCallace48cd2010-10-19 01:40:49 +000013297/// Handle a friend tag declaration where the scope specifier was
13298/// templated.
13299Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13300 unsigned TagSpec, SourceLocation TagLoc,
13301 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013302 IdentifierInfo *Name,
13303 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013304 AttributeList *Attr,
13305 MultiTemplateParamsArg TempParamLists) {
13306 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13307
13308 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013309 bool Invalid = false;
13310
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013311 if (TemplateParameterList *TemplateParams =
13312 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013313 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013314 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013315 if (TemplateParams->size() > 0) {
13316 // This is a declaration of a class template.
13317 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013318 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013319
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013320 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13321 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013322 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013323 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013324 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013325 } else {
13326 // The "template<>" header is extraneous.
13327 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13328 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13329 isExplicitSpecialization = true;
13330 }
13331 }
13332
Craig Topperc3ec1492014-05-26 06:22:03 +000013333 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013334
John McCallace48cd2010-10-19 01:40:49 +000013335 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013336 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013337 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013338 isAllExplicitSpecializations = false;
13339 break;
13340 }
13341 }
13342
13343 // FIXME: don't ignore attributes.
13344
13345 // If it's explicit specializations all the way down, just forget
13346 // about the template header and build an appropriate non-templated
13347 // friend. TODO: for source fidelity, remember the headers.
13348 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013349 if (SS.isEmpty()) {
13350 bool Owned = false;
13351 bool IsDependent = false;
13352 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013353 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013354 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013355 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013356 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013357 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013358 /*UnderlyingType=*/TypeResult(),
13359 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013360 }
Richard Smith649c7b062014-01-08 00:56:48 +000013361
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013362 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013363 ElaboratedTypeKeyword Keyword
13364 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013365 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013366 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013367 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013368 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013369
13370 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13371 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013372 DependentNameTypeLoc TL =
13373 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013374 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013375 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013376 TL.setNameLoc(NameLoc);
13377 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013378 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013379 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013380 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013381 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013382 }
13383
13384 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013385 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013386 Friend->setAccess(AS_public);
13387 CurContext->addDecl(Friend);
13388 return Friend;
13389 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013390
13391 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13392
13393
John McCallace48cd2010-10-19 01:40:49 +000013394
13395 // Handle the case of a templated-scope friend class. e.g.
13396 // template <class T> class A<T>::B;
13397 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013398 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13399 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013400 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13401 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13402 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013403 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013404 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013405 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013406 TL.setNameLoc(NameLoc);
13407
13408 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013409 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013410 Friend->setAccess(AS_public);
13411 Friend->setUnsupportedFriend(true);
13412 CurContext->addDecl(Friend);
13413 return Friend;
13414}
13415
13416
John McCall11083da2009-09-16 22:47:08 +000013417/// Handle a friend type declaration. This works in tandem with
13418/// ActOnTag.
13419///
13420/// Notes on friend class templates:
13421///
13422/// We generally treat friend class declarations as if they were
13423/// declaring a class. So, for example, the elaborated type specifier
13424/// in a friend declaration is required to obey the restrictions of a
13425/// class-head (i.e. no typedefs in the scope chain), template
13426/// parameters are required to match up with simple template-ids, &c.
13427/// However, unlike when declaring a template specialization, it's
13428/// okay to refer to a template specialization without an empty
13429/// template parameter declaration, e.g.
13430/// friend class A<T>::B<unsigned>;
13431/// We permit this as a special case; if there are any template
13432/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013433/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013434Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013435 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013436 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013437
13438 assert(DS.isFriendSpecified());
13439 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13440
John McCall11083da2009-09-16 22:47:08 +000013441 // Try to convert the decl specifier to a type. This works for
13442 // friend templates because ActOnTag never produces a ClassTemplateDecl
13443 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013444 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013445 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13446 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013447 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013448 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013449
Douglas Gregor6c110f32010-12-16 01:14:37 +000013450 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013451 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013452
John McCall11083da2009-09-16 22:47:08 +000013453 // This is definitely an error in C++98. It's probably meant to
13454 // be forbidden in C++0x, too, but the specification is just
13455 // poorly written.
13456 //
13457 // The problem is with declarations like the following:
13458 // template <T> friend A<T>::foo;
13459 // where deciding whether a class C is a friend or not now hinges
13460 // on whether there exists an instantiation of A that causes
13461 // 'foo' to equal C. There are restrictions on class-heads
13462 // (which we declare (by fiat) elaborated friend declarations to
13463 // be) that makes this tractable.
13464 //
13465 // FIXME: handle "template <> friend class A<T>;", which
13466 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013467 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013468 Diag(Loc, diag::err_tagless_friend_type_template)
13469 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013470 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013471 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013472
John McCallaa74a0c2009-08-28 07:59:38 +000013473 // C++98 [class.friend]p1: A friend of a class is a function
13474 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013475 // This is fixed in DR77, which just barely didn't make the C++03
13476 // deadline. It's also a very silly restriction that seriously
13477 // affects inner classes and which nobody else seems to implement;
13478 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013479 //
13480 // But note that we could warn about it: it's always useless to
13481 // friend one of your own members (it's not, however, worthless to
13482 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013483
John McCall11083da2009-09-16 22:47:08 +000013484 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013485 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013486 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013487 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013488 TSI,
John McCall11083da2009-09-16 22:47:08 +000013489 DS.getFriendSpecLoc());
13490 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013491 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013492
13493 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013494 return nullptr;
13495
John McCall11083da2009-09-16 22:47:08 +000013496 D->setAccess(AS_public);
13497 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013498
John McCall48871652010-08-21 09:40:31 +000013499 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013500}
13501
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013502NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13503 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013504 const DeclSpec &DS = D.getDeclSpec();
13505
13506 assert(DS.isFriendSpecified());
13507 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13508
13509 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013511
13512 // C++ [class.friend]p1
13513 // A friend of a class is a function or class....
13514 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013515 // It *doesn't* see through dependent types, which is correct
13516 // according to [temp.arg.type]p3:
13517 // If a declaration acquires a function type through a
13518 // type dependent on a template-parameter and this causes
13519 // a declaration that does not use the syntactic form of a
13520 // function declarator to have a function type, the program
13521 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013522 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013523 Diag(Loc, diag::err_unexpected_friend);
13524
13525 // It might be worthwhile to try to recover by creating an
13526 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013527 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013528 }
13529
13530 // C++ [namespace.memdef]p3
13531 // - If a friend declaration in a non-local class first declares a
13532 // class or function, the friend class or function is a member
13533 // of the innermost enclosing namespace.
13534 // - The name of the friend is not found by simple name lookup
13535 // until a matching declaration is provided in that namespace
13536 // scope (either before or after the class declaration granting
13537 // friendship).
13538 // - If a friend function is called, its name may be found by the
13539 // name lookup that considers functions from namespaces and
13540 // classes associated with the types of the function arguments.
13541 // - When looking for a prior declaration of a class or a function
13542 // declared as a friend, scopes outside the innermost enclosing
13543 // namespace scope are not considered.
13544
John McCallde3fd222010-10-12 23:13:28 +000013545 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013546 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13547 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013548 assert(Name);
13549
Douglas Gregor6c110f32010-12-16 01:14:37 +000013550 // Check for unexpanded parameter packs.
13551 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13552 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13553 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013554 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013555
John McCall07e91c02009-08-06 02:15:43 +000013556 // The context we found the declaration in, or in which we should
13557 // create the declaration.
13558 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013559 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013560 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013561 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013562
Richard Smith114394f2013-08-09 04:35:01 +000013563 // There are five cases here.
13564 // - There's no scope specifier and we're in a local class. Only look
13565 // for functions declared in the immediately-enclosing block scope.
13566 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013567 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013568 if ((SS.isInvalid() || !SS.isSet()) &&
13569 (FunctionContainingLocalClass =
13570 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13571 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013572 // If a friend declaration appears in a local class and the name
13573 // specified is an unqualified name, a prior declaration is
13574 // looked up without considering scopes that are outside the
13575 // innermost enclosing non-class scope. For a friend function
13576 // declaration, if there is no prior declaration, the program is
13577 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013578
13579 // Find the innermost enclosing non-class scope. This is the block
13580 // scope containing the local class definition (or for a nested class,
13581 // the outer local class).
13582 DCScope = S->getFnParent();
13583
13584 // Look up the function name in the scope.
13585 Previous.clear(LookupLocalFriendName);
13586 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13587
13588 if (!Previous.empty()) {
13589 // All possible previous declarations must have the same context:
13590 // either they were declared at block scope or they are members of
13591 // one of the enclosing local classes.
13592 DC = Previous.getRepresentativeDecl()->getDeclContext();
13593 } else {
13594 // This is ill-formed, but provide the context that we would have
13595 // declared the function in, if we were permitted to, for error recovery.
13596 DC = FunctionContainingLocalClass;
13597 }
Richard Smith541b38b2013-09-20 01:15:31 +000013598 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013599
13600 // C++ [class.friend]p6:
13601 // A function can be defined in a friend declaration of a class if and
13602 // only if the class is a non-local class (9.8), the function name is
13603 // unqualified, and the function has namespace scope.
13604 if (D.isFunctionDefinition()) {
13605 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13606 }
13607
13608 // - There's no scope specifier, in which case we just go to the
13609 // appropriate scope and look for a function or function template
13610 // there as appropriate.
13611 } else if (SS.isInvalid() || !SS.isSet()) {
13612 // C++11 [namespace.memdef]p3:
13613 // If the name in a friend declaration is neither qualified nor
13614 // a template-id and the declaration is a function or an
13615 // elaborated-type-specifier, the lookup to determine whether
13616 // the entity has been previously declared shall not consider
13617 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013618 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013619
John McCallf7cfb222010-10-13 05:45:15 +000013620 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013621 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013622
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013623 // Skip class contexts. If someone can cite chapter and verse
13624 // for this behavior, that would be nice --- it's what GCC and
13625 // EDG do, and it seems like a reasonable intent, but the spec
13626 // really only says that checks for unqualified existing
13627 // declarations should stop at the nearest enclosing namespace,
13628 // not that they should only consider the nearest enclosing
13629 // namespace.
13630 while (DC->isRecord())
13631 DC = DC->getParent();
13632
13633 DeclContext *LookupDC = DC;
13634 while (LookupDC->isTransparentContext())
13635 LookupDC = LookupDC->getParent();
13636
13637 while (true) {
13638 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013639
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013640 if (!Previous.empty()) {
13641 DC = LookupDC;
13642 break;
John McCallf4776592010-10-14 22:22:28 +000013643 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013644
13645 if (isTemplateId) {
13646 if (isa<TranslationUnitDecl>(LookupDC)) break;
13647 } else {
13648 if (LookupDC->isFileContext()) break;
13649 }
13650 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013651 }
13652
John McCallccbc0322010-10-13 06:22:15 +000013653 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013654
John McCallde3fd222010-10-12 23:13:28 +000013655 // - There's a non-dependent scope specifier, in which case we
13656 // compute it and do a previous lookup there for a function
13657 // or function template.
13658 } else if (!SS.getScopeRep()->isDependent()) {
13659 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013660 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013661
Craig Topperc3ec1492014-05-26 06:22:03 +000013662 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013663
13664 LookupQualifiedName(Previous, DC);
13665
13666 // Ignore things found implicitly in the wrong scope.
13667 // TODO: better diagnostics for this case. Suggesting the right
13668 // qualified scope would be nice...
13669 LookupResult::Filter F = Previous.makeFilter();
13670 while (F.hasNext()) {
13671 NamedDecl *D = F.next();
13672 if (!DC->InEnclosingNamespaceSetOf(
13673 D->getDeclContext()->getRedeclContext()))
13674 F.erase();
13675 }
13676 F.done();
13677
13678 if (Previous.empty()) {
13679 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013680 Diag(Loc, diag::err_qualified_friend_not_found)
13681 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013682 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013683 }
13684
13685 // C++ [class.friend]p1: A friend of a class is a function or
13686 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013687 if (DC->Equals(CurContext))
13688 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013689 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013690 diag::warn_cxx98_compat_friend_is_member :
13691 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013692
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013693 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013694 // C++ [class.friend]p6:
13695 // A function can be defined in a friend declaration of a class if and
13696 // only if the class is a non-local class (9.8), the function name is
13697 // unqualified, and the function has namespace scope.
13698 SemaDiagnosticBuilder DB
13699 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13700
13701 DB << SS.getScopeRep();
13702 if (DC->isFileContext())
13703 DB << FixItHint::CreateRemoval(SS.getRange());
13704 SS.clear();
13705 }
John McCallde3fd222010-10-12 23:13:28 +000013706
13707 // - There's a scope specifier that does not match any template
13708 // parameter lists, in which case we use some arbitrary context,
13709 // create a method or method template, and wait for instantiation.
13710 // - There's a scope specifier that does match some template
13711 // parameter lists, which we don't handle right now.
13712 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013713 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013714 // C++ [class.friend]p6:
13715 // A function can be defined in a friend declaration of a class if and
13716 // only if the class is a non-local class (9.8), the function name is
13717 // unqualified, and the function has namespace scope.
13718 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13719 << SS.getScopeRep();
13720 }
13721
John McCallde3fd222010-10-12 23:13:28 +000013722 DC = CurContext;
13723 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013724 }
David Majnemere14d5302015-09-30 22:07:43 +000013725
John McCallf7cfb222010-10-13 05:45:15 +000013726 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013727 int DiagArg = -1;
13728 switch (D.getName().getKind()) {
13729 case UnqualifiedId::IK_ConstructorTemplateId:
13730 case UnqualifiedId::IK_ConstructorName:
13731 DiagArg = 0;
13732 break;
13733 case UnqualifiedId::IK_DestructorName:
13734 DiagArg = 1;
13735 break;
13736 case UnqualifiedId::IK_ConversionFunctionId:
13737 DiagArg = 2;
13738 break;
13739 case UnqualifiedId::IK_Identifier:
13740 case UnqualifiedId::IK_ImplicitSelfParam:
13741 case UnqualifiedId::IK_LiteralOperatorId:
13742 case UnqualifiedId::IK_OperatorFunctionId:
13743 case UnqualifiedId::IK_TemplateId:
13744 break;
David Majnemere14d5302015-09-30 22:07:43 +000013745 }
John McCall07e91c02009-08-06 02:15:43 +000013746 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013747 if (DiagArg >= 0) {
13748 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013749 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013750 }
John McCall07e91c02009-08-06 02:15:43 +000013751 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013752
Douglas Gregordd847ba2011-11-03 16:37:14 +000013753 // FIXME: This is an egregious hack to cope with cases where the scope stack
13754 // does not contain the declaration context, i.e., in an out-of-line
13755 // definition of a class.
13756 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13757 if (!DCScope) {
13758 FakeDCScope.setEntity(DC);
13759 DCScope = &FakeDCScope;
13760 }
Richard Smith114394f2013-08-09 04:35:01 +000013761
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013762 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013763 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013764 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013765 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013766
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013767 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013768
Richard Smith114394f2013-08-09 04:35:01 +000013769 // If we performed typo correction, we might have added a scope specifier
13770 // and changed the decl context.
13771 DC = ND->getDeclContext();
13772
John McCall759e32b2009-08-31 22:39:49 +000013773 // Add the function declaration to the appropriate lookup tables,
13774 // adjusting the redeclarations list as necessary. We don't
13775 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013776 //
John McCall759e32b2009-08-31 22:39:49 +000013777 // Also update the scope-based lookup if the target context's
13778 // lookup context is in lexical scope.
13779 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013780 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013781 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013782 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013783 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013784 }
John McCallaa74a0c2009-08-28 07:59:38 +000013785
13786 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013787 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013788 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013789 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013790 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013791
John McCalla0a96892012-08-10 03:15:35 +000013792 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013793 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013794 } else {
13795 if (DC->isRecord()) CheckFriendAccess(ND);
13796
John McCall2c2eb122010-10-16 06:59:13 +000013797 FunctionDecl *FD;
13798 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13799 FD = FTD->getTemplatedDecl();
13800 else
13801 FD = cast<FunctionDecl>(ND);
13802
David Majnemer502b0ed2013-06-25 23:09:30 +000013803 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13804 // default argument expression, that declaration shall be a definition
13805 // and shall be the only declaration of the function or function
13806 // template in the translation unit.
13807 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013808 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013809 // if we're in a dependent context. If the function is known to be a
13810 // redeclaration, we will have narrowed Previous down to the right decl.
13811 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013812 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013813 Diag(Previous.getRepresentativeDecl()->getLocation(),
13814 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013815 } else if (!D.isFunctionDefinition())
13816 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13817 }
13818
John McCall2c2eb122010-10-16 06:59:13 +000013819 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013820 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13821 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13822 << SS.getScopeRep() << SS.getRange()
13823 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013824 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013825 }
John McCall2c2eb122010-10-16 06:59:13 +000013826 }
John McCallde3fd222010-10-12 23:13:28 +000013827
John McCall48871652010-08-21 09:40:31 +000013828 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013829}
13830
John McCall48871652010-08-21 09:40:31 +000013831void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13832 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013833
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013834 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013835 if (!Fn) {
13836 Diag(DelLoc, diag::err_deleted_non_function);
13837 return;
13838 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013839
Douglas Gregorec9fd132012-01-14 16:38:05 +000013840 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013841 // Don't consider the implicit declaration we generate for explicit
13842 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013843 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13844 Prev->getPreviousDecl()) &&
13845 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013846 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013847 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13848 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13849 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013850 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013851 // If the declaration wasn't the first, we delete the function anyway for
13852 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013853 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013854 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013855
Nico Rieck9de0a572014-05-29 16:51:19 +000013856 // dllimport/dllexport cannot be deleted.
13857 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13858 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13859 Fn->setInvalidDecl();
13860 }
13861
Richard Smithb4d2a152013-04-02 19:38:47 +000013862 if (Fn->isDeleted())
13863 return;
13864
13865 // See if we're deleting a function which is already known to override a
13866 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013867 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013868 bool IssuedDiagnostic = false;
13869 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13870 E = MD->end_overridden_methods();
13871 I != E; ++I) {
13872 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13873 if (!IssuedDiagnostic) {
13874 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13875 IssuedDiagnostic = true;
13876 }
13877 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13878 }
13879 }
Richard Smithf3cec652016-10-31 18:18:29 +000013880 // If this function was implicitly deleted because it was defaulted,
13881 // explain why it was deleted.
13882 if (IssuedDiagnostic && MD->isDefaulted())
13883 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13884 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000013885 }
13886
Richard Smithb63b6ee2014-01-22 01:43:19 +000013887 // C++11 [basic.start.main]p3:
13888 // A program that defines main as deleted [...] is ill-formed.
13889 if (Fn->isMain())
13890 Diag(DelLoc, diag::err_deleted_main);
13891
Eric Fiselier525a3512016-10-31 23:07:15 +000013892 // C++11 [dcl.fct.def.delete]p4:
13893 // A deleted function is implicitly inline.
13894 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013895 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013896}
Sebastian Redl4c018662009-04-27 21:33:24 +000013897
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013898void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013899 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013900
13901 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013902 if (MD->getParent()->isDependentType()) {
13903 MD->setDefaulted();
13904 MD->setExplicitlyDefaulted();
13905 return;
13906 }
13907
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013908 CXXSpecialMember Member = getSpecialMember(MD);
13909 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013910 if (!MD->isInvalidDecl())
13911 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013912 return;
13913 }
13914
13915 MD->setDefaulted();
13916 MD->setExplicitlyDefaulted();
13917
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013918 // If this definition appears within the record, do the checking when
13919 // the record is complete.
13920 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013921 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013922 // Ask the template instantiation pattern that actually had the
13923 // '= default' on it.
13924 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013925
Richard Smith3901dfe2013-03-27 00:22:47 +000013926 // If the method was defaulted on its first declaration, we will have
13927 // already performed the checking in CheckCompletedCXXClass. Such a
13928 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013929 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013930 return;
13931
Richard Smithd3b5c9082012-07-27 04:22:15 +000013932 CheckExplicitlyDefaultedSpecialMember(MD);
13933
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013934 if (!MD->isInvalidDecl())
13935 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013936 } else {
13937 Diag(DefaultLoc, diag::err_default_special_members);
13938 }
13939}
13940
Sebastian Redl4c018662009-04-27 21:33:24 +000013941static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013942 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013943 if (!SubStmt)
13944 continue;
13945 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013946 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000013947 diag::err_return_in_constructor_handler);
13948 if (!isa<Expr>(SubStmt))
13949 SearchForReturnInStmt(Self, SubStmt);
13950 }
13951}
13952
13953void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13954 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13955 CXXCatchStmt *Handler = TryBlock->getHandler(I);
13956 SearchForReturnInStmt(*this, Handler);
13957 }
13958}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013959
David Blaikie68f71a32013-01-18 23:03:15 +000013960bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000013961 const CXXMethodDecl *Old) {
13962 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13963 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13964
13965 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13966
13967 // If the calling conventions match, everything is fine
13968 if (NewCC == OldCC)
13969 return false;
13970
Hans Wennborg2545efe2013-12-11 17:42:11 +000013971 // If the calling conventions mismatch because the new function is static,
13972 // suppress the calling convention mismatch error; the error about static
13973 // function override (err_static_overrides_virtual from
13974 // Sema::CheckFunctionDeclaration) is more clear.
13975 if (New->getStorageClass() == SC_Static)
13976 return false;
13977
Reid Kleckner78af0702013-08-27 23:08:25 +000013978 Diag(New->getLocation(),
13979 diag::err_conflicting_overriding_cc_attributes)
13980 << New->getDeclName() << New->getType() << Old->getType();
13981 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13982 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000013983}
13984
Mike Stump11289f42009-09-09 15:08:12 +000013985bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013986 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000013987 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13988 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013989
Chandler Carruth284bb2e2010-02-15 11:53:20 +000013990 if (Context.hasSameType(NewTy, OldTy) ||
13991 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013992 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013993
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013994 // Check if the return types are covariant
13995 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000013996
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013997 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013998 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13999 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014000 NewClassTy = NewPT->getPointeeType();
14001 OldClassTy = OldPT->getPointeeType();
14002 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014003 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14004 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14005 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14006 NewClassTy = NewRT->getPointeeType();
14007 OldClassTy = OldRT->getPointeeType();
14008 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014009 }
14010 }
Mike Stump11289f42009-09-09 15:08:12 +000014011
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014012 // The return types aren't either both pointers or references to a class type.
14013 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014014 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014015 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014016 << New->getDeclName() << NewTy << OldTy
14017 << New->getReturnTypeSourceRange();
14018 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14019 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014020
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014021 return true;
14022 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014023
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014024 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014025 // C++14 [class.virtual]p8:
14026 // If the class type in the covariant return type of D::f differs from
14027 // that of B::f, the class type in the return type of D::f shall be
14028 // complete at the point of declaration of D::f or shall be the class
14029 // type D.
14030 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14031 if (!RT->isBeingDefined() &&
14032 RequireCompleteType(New->getLocation(), NewClassTy,
14033 diag::err_covariant_return_incomplete,
14034 New->getDeclName()))
14035 return true;
14036 }
14037
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014038 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014039 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014040 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14041 << New->getDeclName() << NewTy << OldTy
14042 << New->getReturnTypeSourceRange();
14043 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14044 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014045 return true;
14046 }
Mike Stump11289f42009-09-09 15:08:12 +000014047
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014048 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014049 if (CheckDerivedToBaseConversion(
14050 NewClassTy, OldClassTy,
14051 diag::err_covariant_return_inaccessible_base,
14052 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14053 New->getLocation(), New->getReturnTypeSourceRange(),
14054 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014055 // FIXME: this note won't trigger for delayed access control
14056 // diagnostics, and it's impossible to get an undelayed error
14057 // here from access control during the original parse because
14058 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014059 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14060 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014061 return true;
14062 }
14063 }
Mike Stump11289f42009-09-09 15:08:12 +000014064
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014065 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014066 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014067 Diag(New->getLocation(),
14068 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014069 << New->getDeclName() << NewTy << OldTy
14070 << New->getReturnTypeSourceRange();
14071 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14072 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014073 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014074 }
Mike Stump11289f42009-09-09 15:08:12 +000014075
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014076
14077 // The new class type must have the same or less qualifiers as the old type.
14078 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14079 Diag(New->getLocation(),
14080 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014081 << New->getDeclName() << NewTy << OldTy
14082 << New->getReturnTypeSourceRange();
14083 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14084 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014085 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014086 }
Mike Stump11289f42009-09-09 15:08:12 +000014087
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014088 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014089}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014090
Douglas Gregor21920e372009-12-01 17:24:26 +000014091/// \brief Mark the given method pure.
14092///
14093/// \param Method the method to be marked pure.
14094///
14095/// \param InitRange the source range that covers the "0" initializer.
14096bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014097 SourceLocation EndLoc = InitRange.getEnd();
14098 if (EndLoc.isValid())
14099 Method->setRangeEnd(EndLoc);
14100
Douglas Gregor21920e372009-12-01 17:24:26 +000014101 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14102 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014103 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014104 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014105
14106 if (!Method->isInvalidDecl())
14107 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14108 << Method->getDeclName() << InitRange;
14109 return true;
14110}
14111
Richard Smith9ba0fec2015-06-30 01:28:56 +000014112void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14113 if (D->getFriendObjectKind())
14114 Diag(D->getLocation(), diag::err_pure_friend);
14115 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14116 CheckPureMethod(M, ZeroLoc);
14117 else
14118 Diag(D->getLocation(), diag::err_illegal_initializer);
14119}
14120
Douglas Gregor926410d2012-02-21 02:22:07 +000014121/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014122static bool isStaticDataMember(const Decl *D) {
14123 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14124 return Var->isStaticDataMember();
14125
14126 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014127}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014128
John McCall1f4ee7b2009-12-19 09:28:58 +000014129/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14130/// an initializer for the out-of-line declaration 'Dcl'. The scope
14131/// is a fresh scope pushed for just this purpose.
14132///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014133/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14134/// static data member of class X, names should be looked up in the scope of
14135/// class X.
John McCall48871652010-08-21 09:40:31 +000014136void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014137 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014138 if (!D || D->isInvalidDecl())
14139 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014140
Richard Smitha2302242013-12-05 07:51:02 +000014141 // We will always have a nested name specifier here, but this declaration
14142 // might not be out of line if the specifier names the current namespace:
14143 // extern int n;
14144 // int ::n = 0;
14145 if (D->isOutOfLine())
14146 EnterDeclaratorContext(S, D->getDeclContext());
14147
Douglas Gregor926410d2012-02-21 02:22:07 +000014148 // If we are parsing the initializer for a static data member, push a
14149 // new expression evaluation context that is associated with this static
14150 // data member.
14151 if (isStaticDataMember(D))
14152 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014153}
14154
14155/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014156/// initializer for the out-of-line declaration 'D'.
14157void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014158 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014159 if (!D || D->isInvalidDecl())
14160 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014161
Douglas Gregor926410d2012-02-21 02:22:07 +000014162 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014163 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014164
Richard Smitha2302242013-12-05 07:51:02 +000014165 if (D->isOutOfLine())
14166 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014167}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014168
14169/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14170/// C++ if/switch/while/for statement.
14171/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014172DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014173 // C++ 6.4p2:
14174 // The declarator shall not specify a function or an array.
14175 // The type-specifier-seq shall not contain typedef and shall not declare a
14176 // new class or enumeration.
14177 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14178 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014179
14180 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014181 if (!Dcl)
14182 return true;
14183
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014184 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14185 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014186 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014187 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014188 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014189
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014190 return Dcl;
14191}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014192
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014193void Sema::LoadExternalVTableUses() {
14194 if (!ExternalSource)
14195 return;
14196
14197 SmallVector<ExternalVTableUse, 4> VTables;
14198 ExternalSource->ReadUsedVTables(VTables);
14199 SmallVector<VTableUse, 4> NewUses;
14200 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14201 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14202 = VTablesUsed.find(VTables[I].Record);
14203 // Even if a definition wasn't required before, it may be required now.
14204 if (Pos != VTablesUsed.end()) {
14205 if (!Pos->second && VTables[I].DefinitionRequired)
14206 Pos->second = true;
14207 continue;
14208 }
14209
14210 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14211 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14212 }
14213
14214 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14215}
14216
Douglas Gregor88d292c2010-05-13 16:44:06 +000014217void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14218 bool DefinitionRequired) {
14219 // Ignore any vtable uses in unevaluated operands or for classes that do
14220 // not have a vtable.
14221 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014222 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014223 return;
14224
Douglas Gregor88d292c2010-05-13 16:44:06 +000014225 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014226 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014227 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14228 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14229 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14230 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014231 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014232 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014233 // list, since we may have already processed the first entry.
14234 if (DefinitionRequired && !Pos.first->second) {
14235 Pos.first->second = true;
14236 } else {
14237 // Otherwise, we can early exit.
14238 return;
14239 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014240 } else {
14241 // The Microsoft ABI requires that we perform the destructor body
14242 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14243 // the deleting destructor is emitted with the vtable, not with the
14244 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014245 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014246 CXXDestructorDecl *DD = Class->getDestructor();
14247 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14248 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14249 // If this is an out-of-line declaration, marking it referenced will
14250 // not do anything. Manually call CheckDestructor to look up operator
14251 // delete().
14252 ContextRAII SavedContext(*this, DD);
14253 CheckDestructor(DD);
14254 } else {
14255 MarkFunctionReferenced(Loc, Class->getDestructor());
14256 }
Hans Wennborg34804352016-04-13 20:21:15 +000014257 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014258 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014259 }
14260
14261 // Local classes need to have their virtual members marked
14262 // immediately. For all other classes, we mark their virtual members
14263 // at the end of the translation unit.
14264 if (Class->isLocalClass())
14265 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014266 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014267 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014268}
14269
Douglas Gregor88d292c2010-05-13 16:44:06 +000014270bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014271 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014272 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014273 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014274
Douglas Gregor88d292c2010-05-13 16:44:06 +000014275 // Note: The VTableUses vector could grow as a result of marking
14276 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014277 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014278 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014279 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014280 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014281 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014282 if (!Class)
14283 continue;
14284
14285 SourceLocation Loc = VTableUses[I].second;
14286
Richard Smithd3b5c9082012-07-27 04:22:15 +000014287 bool DefineVTable = true;
14288
Douglas Gregor88d292c2010-05-13 16:44:06 +000014289 // If this class has a key function, but that key function is
14290 // defined in another translation unit, we don't need to emit the
14291 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014292 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014293 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014294 // The key function is in another translation unit.
14295 DefineVTable = false;
14296 TemplateSpecializationKind TSK =
14297 KeyFunction->getTemplateSpecializationKind();
14298 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14299 TSK != TSK_ImplicitInstantiation &&
14300 "Instantiations don't have key functions");
14301 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014302 } else if (!KeyFunction) {
14303 // If we have a class with no key function that is the subject
14304 // of an explicit instantiation declaration, suppress the
14305 // vtable; it will live with the explicit instantiation
14306 // definition.
14307 bool IsExplicitInstantiationDeclaration
14308 = Class->getTemplateSpecializationKind()
14309 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014310 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014311 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014312 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014313 if (TSK == TSK_ExplicitInstantiationDeclaration)
14314 IsExplicitInstantiationDeclaration = true;
14315 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14316 IsExplicitInstantiationDeclaration = false;
14317 break;
14318 }
14319 }
14320
14321 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014322 DefineVTable = false;
14323 }
14324
14325 // The exception specifications for all virtual members may be needed even
14326 // if we are not providing an authoritative form of the vtable in this TU.
14327 // We may choose to emit it available_externally anyway.
14328 if (!DefineVTable) {
14329 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14330 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014331 }
14332
14333 // Mark all of the virtual members of this class as referenced, so
14334 // that we can build a vtable. Then, tell the AST consumer that a
14335 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014336 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014337 MarkVirtualMembersReferenced(Loc, Class);
14338 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014339 if (VTablesUsed[Canonical])
14340 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014341
14342 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000014343 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000014344 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014345 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000014346 if (!KeyFunction ||
14347 (KeyFunction->hasBody(KeyFunctionDef) &&
14348 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000014349 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14350 TSK_ExplicitInstantiationDefinition
14351 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14352 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014353 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014354 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014355 VTableUses.clear();
14356
Douglas Gregor97509692011-04-22 22:25:37 +000014357 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014358}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014359
Richard Smithd3b5c9082012-07-27 04:22:15 +000014360void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14361 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014362 for (const auto *I : RD->methods())
14363 if (I->isVirtual() && !I->isPure())
14364 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014365}
14366
Rafael Espindola5b334082010-03-26 00:36:59 +000014367void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14368 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014369 // Mark all functions which will appear in RD's vtable as used.
14370 CXXFinalOverriderMap FinalOverriders;
14371 RD->getFinalOverriders(FinalOverriders);
14372 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14373 E = FinalOverriders.end();
14374 I != E; ++I) {
14375 for (OverridingMethods::const_iterator OI = I->second.begin(),
14376 OE = I->second.end();
14377 OI != OE; ++OI) {
14378 assert(OI->second.size() > 0 && "no final overrider");
14379 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014380
Richard Smith4ff9ff92012-07-07 06:59:51 +000014381 // C++ [basic.def.odr]p2:
14382 // [...] A virtual member function is used if it is not pure. [...]
14383 if (!Overrider->isPure())
14384 MarkFunctionReferenced(Loc, Overrider);
14385 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014386 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014387
14388 // Only classes that have virtual bases need a VTT.
14389 if (RD->getNumVBases() == 0)
14390 return;
14391
Aaron Ballman574705e2014-03-13 15:41:46 +000014392 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014393 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014394 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014395 if (Base->getNumVBases() == 0)
14396 continue;
14397 MarkVirtualMembersReferenced(Loc, Base);
14398 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014399}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014400
14401/// SetIvarInitializers - This routine builds initialization ASTs for the
14402/// Objective-C implementation whose ivars need be initialized.
14403void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014404 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014405 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014406 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014407 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014408 CollectIvarsToConstructOrDestruct(OID, ivars);
14409 if (ivars.empty())
14410 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014411 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014412 for (unsigned i = 0; i < ivars.size(); i++) {
14413 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014414 if (Field->isInvalidDecl())
14415 continue;
14416
Alexis Hunt1d792652011-01-08 20:30:50 +000014417 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014418 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14419 InitializationKind InitKind =
14420 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014421
14422 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14423 ExprResult MemberInit =
14424 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014425 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014426 // Note, MemberInit could actually come back empty if no initialization
14427 // is required (e.g., because it would call a trivial default constructor)
14428 if (!MemberInit.get() || MemberInit.isInvalid())
14429 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014430
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014431 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014432 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14433 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014434 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014435 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014436 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014437
14438 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014439 if (const RecordType *RecordTy =
14440 Context.getBaseElementType(Field->getType())
14441 ->getAs<RecordType>()) {
14442 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014443 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014444 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014445 CheckDestructorAccess(Field->getLocation(), Destructor,
14446 PDiag(diag::err_access_dtor_ivar)
14447 << Context.getBaseElementType(Field->getType()));
14448 }
14449 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014450 }
14451 ObjCImplementation->setIvarInitializers(Context,
14452 AllToInit.data(), AllToInit.size());
14453 }
14454}
Alexis Hunt6118d662011-05-04 05:57:24 +000014455
Alexis Hunt27a761d2011-05-04 23:29:54 +000014456static
14457void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14458 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14459 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14460 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14461 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014462 if (Ctor->isInvalidDecl())
14463 return;
14464
Richard Smith802c4b72012-08-23 06:16:52 +000014465 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14466
14467 // Target may not be determinable yet, for instance if this is a dependent
14468 // call in an uninstantiated template.
14469 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014470 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014471 (void)Target->hasBody(FNTarget);
14472 Target = const_cast<CXXConstructorDecl*>(
14473 cast_or_null<CXXConstructorDecl>(FNTarget));
14474 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014475
14476 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14477 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014478 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014479
David Blaikie82e95a32014-11-19 07:49:47 +000014480 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014481 return;
14482
14483 // We know that beyond here, we aren't chaining into a cycle.
14484 if (!Target || !Target->isDelegatingConstructor() ||
14485 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014486 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014487 Current.clear();
14488 // We've hit a cycle.
14489 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14490 Current.count(TCanonical)) {
14491 // If we haven't diagnosed this cycle yet, do so now.
14492 if (!Invalid.count(TCanonical)) {
14493 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014494 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014495 << Ctor;
14496
Richard Smith802c4b72012-08-23 06:16:52 +000014497 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014498 if (TCanonical != Canonical)
14499 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14500
14501 CXXConstructorDecl *C = Target;
14502 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014503 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014504 (void)C->getTargetConstructor()->hasBody(FNTarget);
14505 assert(FNTarget && "Ctor cycle through bodiless function");
14506
Richard Smith802c4b72012-08-23 06:16:52 +000014507 C = const_cast<CXXConstructorDecl*>(
14508 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014509 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14510 }
14511 }
14512
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014513 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014514 Current.clear();
14515 } else {
14516 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14517 }
14518}
14519
14520
Alexis Hunt6118d662011-05-04 05:57:24 +000014521void Sema::CheckDelegatingCtorCycles() {
14522 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14523
Douglas Gregorbae31202011-07-27 21:57:17 +000014524 for (DelegatingCtorDeclsType::iterator
14525 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014526 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014527 I != E; ++I)
14528 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014529
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014530 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14531 CE = Invalid.end();
14532 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014533 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014534}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014535
Douglas Gregor3024f072012-04-16 07:05:22 +000014536namespace {
14537 /// \brief AST visitor that finds references to the 'this' expression.
14538 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14539 Sema &S;
14540
14541 public:
14542 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14543
14544 bool VisitCXXThisExpr(CXXThisExpr *E) {
14545 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14546 << E->isImplicit();
14547 return false;
14548 }
14549 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014550}
Douglas Gregor3024f072012-04-16 07:05:22 +000014551
14552bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14553 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14554 if (!TSInfo)
14555 return false;
14556
14557 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014558 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014559 if (!ProtoTL)
14560 return false;
14561
14562 // C++11 [expr.prim.general]p3:
14563 // [The expression this] shall not appear before the optional
14564 // cv-qualifier-seq and it shall not appear within the declaration of a
14565 // static member function (although its type and value category are defined
14566 // within a static member function as they are within a non-static member
14567 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014568 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014569 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014570 FindCXXThisExpr Finder(*this);
14571
14572 // If the return type came after the cv-qualifier-seq, check it now.
14573 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014574 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014575 return true;
14576
14577 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014578 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14579 return true;
14580
14581 return checkThisInStaticMemberFunctionAttributes(Method);
14582}
14583
14584bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14585 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14586 if (!TSInfo)
14587 return false;
14588
14589 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014590 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014591 if (!ProtoTL)
14592 return false;
14593
David Blaikie6adc78e2013-02-18 22:06:02 +000014594 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014595 FindCXXThisExpr Finder(*this);
14596
Douglas Gregor3024f072012-04-16 07:05:22 +000014597 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014598 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014599 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014600 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014601 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014602 case EST_DynamicNone:
14603 case EST_MSAny:
14604 case EST_None:
14605 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014606
Douglas Gregor3024f072012-04-16 07:05:22 +000014607 case EST_ComputedNoexcept:
14608 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14609 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014610
Douglas Gregor3024f072012-04-16 07:05:22 +000014611 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014612 for (const auto &E : Proto->exceptions()) {
14613 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014614 return true;
14615 }
14616 break;
14617 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014618
14619 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014620}
14621
14622bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14623 FindCXXThisExpr Finder(*this);
14624
14625 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014626 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014627 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014628 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014629 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014630 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014631 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014632 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014633 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014634 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014635 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014636 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014637 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014638 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014639 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014640 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014641 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014642 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014643 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014644 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014645 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014646 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014647 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014648 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014649 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014650 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014651 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014652 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014653 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014654 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014655 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014656
14657 if (Arg && !Finder.TraverseStmt(Arg))
14658 return true;
14659
14660 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14661 if (!Finder.TraverseStmt(Args[I]))
14662 return true;
14663 }
14664 }
14665
14666 return false;
14667}
14668
Richard Smith2e321552014-11-12 02:00:47 +000014669void Sema::checkExceptionSpecification(
14670 bool IsTopLevel, ExceptionSpecificationType EST,
14671 ArrayRef<ParsedType> DynamicExceptions,
14672 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14673 SmallVectorImpl<QualType> &Exceptions,
14674 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014675 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014676 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014677 if (EST == EST_Dynamic) {
14678 Exceptions.reserve(DynamicExceptions.size());
14679 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14680 // FIXME: Preserve type source info.
14681 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14682
Richard Smith2e321552014-11-12 02:00:47 +000014683 if (IsTopLevel) {
14684 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14685 collectUnexpandedParameterPacks(ET, Unexpanded);
14686 if (!Unexpanded.empty()) {
14687 DiagnoseUnexpandedParameterPacks(
14688 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14689 Unexpanded);
14690 continue;
14691 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014692 }
14693
14694 // Check that the type is valid for an exception spec, and
14695 // drop it if not.
14696 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14697 Exceptions.push_back(ET);
14698 }
Richard Smith8acb4282014-07-31 21:57:55 +000014699 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014700 return;
14701 }
Richard Smith8acb4282014-07-31 21:57:55 +000014702
Douglas Gregor433e0532012-04-16 18:27:27 +000014703 if (EST == EST_ComputedNoexcept) {
14704 // If an error occurred, there's no expression here.
14705 if (NoexceptExpr) {
14706 assert((NoexceptExpr->isTypeDependent() ||
14707 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14708 Context.BoolTy) &&
14709 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014710 if (IsTopLevel && NoexceptExpr &&
14711 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014712 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014713 return;
14714 }
Richard Smith8acb4282014-07-31 21:57:55 +000014715
Douglas Gregor433e0532012-04-16 18:27:27 +000014716 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014717 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014718 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014719 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014720 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014721 }
14722 return;
14723 }
14724}
14725
Richard Smith0b3a4622014-11-13 20:01:57 +000014726void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14727 ExceptionSpecificationType EST,
14728 SourceRange SpecificationRange,
14729 ArrayRef<ParsedType> DynamicExceptions,
14730 ArrayRef<SourceRange> DynamicExceptionRanges,
14731 Expr *NoexceptExpr) {
14732 if (!MethodD)
14733 return;
14734
14735 // Dig out the method we're referring to.
14736 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14737 MethodD = FunTmpl->getTemplatedDecl();
14738
14739 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14740 if (!Method)
14741 return;
14742
14743 // Check the exception specification.
14744 llvm::SmallVector<QualType, 4> Exceptions;
14745 FunctionProtoType::ExceptionSpecInfo ESI;
14746 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14747 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14748 ESI);
14749
14750 // Update the exception specification on the function type.
14751 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14752
14753 if (Method->isStatic())
14754 checkThisInStaticMemberFunctionExceptionSpec(Method);
14755
14756 if (Method->isVirtual()) {
14757 // Check overrides, which we previously had to delay.
14758 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14759 OEnd = Method->end_overridden_methods();
14760 O != OEnd; ++O)
14761 CheckOverridingFunctionExceptionSpec(Method, *O);
14762 }
14763}
14764
John McCall5e77d762013-04-16 07:28:30 +000014765/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14766///
14767MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14768 SourceLocation DeclStart,
14769 Declarator &D, Expr *BitWidth,
14770 InClassInitStyle InitStyle,
14771 AccessSpecifier AS,
14772 AttributeList *MSPropertyAttr) {
14773 IdentifierInfo *II = D.getIdentifier();
14774 if (!II) {
14775 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014776 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014777 }
14778 SourceLocation Loc = D.getIdentifierLoc();
14779
14780 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14781 QualType T = TInfo->getType();
14782 if (getLangOpts().CPlusPlus) {
14783 CheckExtraCXXDefaultArguments(D);
14784
14785 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14786 UPPC_DataMemberType)) {
14787 D.setInvalidType();
14788 T = Context.IntTy;
14789 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14790 }
14791 }
14792
14793 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14794
Richard Smith62f19e72016-06-25 00:15:56 +000014795 if (D.getDeclSpec().isInlineSpecified())
14796 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14797 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014798 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14799 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14800 diag::err_invalid_thread)
14801 << DeclSpec::getSpecifierName(TSCS);
14802
14803 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014804 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014805 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14806 LookupName(Previous, S);
14807 switch (Previous.getResultKind()) {
14808 case LookupResult::Found:
14809 case LookupResult::FoundUnresolvedValue:
14810 PrevDecl = Previous.getAsSingle<NamedDecl>();
14811 break;
14812
14813 case LookupResult::FoundOverloaded:
14814 PrevDecl = Previous.getRepresentativeDecl();
14815 break;
14816
14817 case LookupResult::NotFound:
14818 case LookupResult::NotFoundInCurrentInstantiation:
14819 case LookupResult::Ambiguous:
14820 break;
14821 }
14822
14823 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14824 // Maybe we will complain about the shadowed template parameter.
14825 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14826 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014827 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014828 }
14829
14830 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014831 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014832
14833 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014834 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014835 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14836 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014837 ProcessDeclAttributes(TUScope, NewPD, D);
14838 NewPD->setAccess(AS);
14839
14840 if (NewPD->isInvalidDecl())
14841 Record->setInvalidDecl();
14842
14843 if (D.getDeclSpec().isModulePrivateSpecified())
14844 NewPD->setModulePrivate();
14845
14846 if (NewPD->isInvalidDecl() && PrevDecl) {
14847 // Don't introduce NewFD into scope; there's already something
14848 // with the same name in the same scope.
14849 } else if (II) {
14850 PushOnScopeChains(NewPD, S);
14851 } else
14852 Record->addDecl(NewPD);
14853
14854 return NewPD;
14855}