blob: d793daf9d826408ce3a166066525eb554ed2f32f [file] [log] [blame]
Chris Lattner3d1cee32008-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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
395 if (getLangOptions().Microsoft) {
396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
John McCalld226f652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +00001020 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith7a614d82011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
Richard Smith1ab0d902011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001083
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001099 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Sebastian Redla11f42f2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redl669d5d72008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregor922fff22010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor37b372b2009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001147 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Sean Hunte4246a62011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001151 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001153 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001174 }
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chris Lattner8b963ef2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Douglas Gregor37b372b2009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187
Anders Carlssonaae5af22011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001194 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001203 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001205 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001206
Douglas Gregorf5251602011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001214
Douglas Gregor10bd3682008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001216
Douglas Gregor021c3b32009-03-11 23:00:04 +00001217 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001228
Richard Smith483b9f32011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCallb25b2952011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001234}
1235
Richard Smith7a614d82011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237/// in-class initializer for a non-static C++ class member. Such parsing
1238/// is deferred until the class is complete.
1239void
1240Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1241 Expr *InitExpr) {
1242 FieldDecl *FD = cast<FieldDecl>(D);
1243
1244 if (!InitExpr) {
1245 FD->setInvalidDecl();
1246 FD->removeInClassInitializer();
1247 return;
1248 }
1249
1250 ExprResult Init = InitExpr;
1251 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1252 // FIXME: if there is no EqualLoc, this is list-initialization.
1253 Init = PerformCopyInitialization(
1254 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1255 if (Init.isInvalid()) {
1256 FD->setInvalidDecl();
1257 return;
1258 }
1259
1260 CheckImplicitConversions(Init.get(), EqualLoc);
1261 }
1262
1263 // C++0x [class.base.init]p7:
1264 // The initialization of each base and member constitutes a
1265 // full-expression.
1266 Init = MaybeCreateExprWithCleanups(Init);
1267 if (Init.isInvalid()) {
1268 FD->setInvalidDecl();
1269 return;
1270 }
1271
1272 InitExpr = Init.release();
1273
1274 FD->setInClassInitializer(InitExpr);
1275}
1276
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001277/// \brief Find the direct and/or virtual base specifiers that
1278/// correspond to the given base type, for use in base initialization
1279/// within a constructor.
1280static bool FindBaseInitializer(Sema &SemaRef,
1281 CXXRecordDecl *ClassDecl,
1282 QualType BaseType,
1283 const CXXBaseSpecifier *&DirectBaseSpec,
1284 const CXXBaseSpecifier *&VirtualBaseSpec) {
1285 // First, check for a direct base class.
1286 DirectBaseSpec = 0;
1287 for (CXXRecordDecl::base_class_const_iterator Base
1288 = ClassDecl->bases_begin();
1289 Base != ClassDecl->bases_end(); ++Base) {
1290 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1291 // We found a direct base of this type. That's what we're
1292 // initializing.
1293 DirectBaseSpec = &*Base;
1294 break;
1295 }
1296 }
1297
1298 // Check for a virtual base class.
1299 // FIXME: We might be able to short-circuit this if we know in advance that
1300 // there are no virtual bases.
1301 VirtualBaseSpec = 0;
1302 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1303 // We haven't found a base yet; search the class hierarchy for a
1304 // virtual base class.
1305 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1306 /*DetectVirtual=*/false);
1307 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1308 BaseType, Paths)) {
1309 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1310 Path != Paths.end(); ++Path) {
1311 if (Path->back().Base->isVirtual()) {
1312 VirtualBaseSpec = Path->back().Base;
1313 break;
1314 }
1315 }
1316 }
1317 }
1318
1319 return DirectBaseSpec || VirtualBaseSpec;
1320}
1321
Douglas Gregor7ad83902008-11-05 04:29:56 +00001322/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001323MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001324Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001325 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001326 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001327 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001328 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001329 SourceLocation IdLoc,
1330 SourceLocation LParenLoc,
1331 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001332 SourceLocation RParenLoc,
1333 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001334 if (!ConstructorD)
1335 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001337 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001338
1339 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001340 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001341 if (!Constructor) {
1342 // The user wrote a constructor initializer on a function that is
1343 // not a C++ constructor. Ignore the error for now, because we may
1344 // have more member initializers coming; we'll diagnose it just
1345 // once in ActOnMemInitializers.
1346 return true;
1347 }
1348
1349 CXXRecordDecl *ClassDecl = Constructor->getParent();
1350
1351 // C++ [class.base.init]p2:
1352 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001353 // constructor's class and, if not found in that scope, are looked
1354 // up in the scope containing the constructor's definition.
1355 // [Note: if the constructor's class contains a member with the
1356 // same name as a direct or virtual base class of the class, a
1357 // mem-initializer-id naming the member or base class and composed
1358 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001359 // mem-initializer-id for the hidden base class may be specified
1360 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001361 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001362 // Look for a member, first.
1363 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001364 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001365 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001366 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001367 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001368
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001369 if (Member) {
1370 if (EllipsisLoc.isValid())
1371 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1372 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1373
Francois Pichet00eb3f92010-12-04 09:14:42 +00001374 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001375 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001376 }
1377
Francois Pichet00eb3f92010-12-04 09:14:42 +00001378 // Handle anonymous union case.
1379 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001380 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1381 if (EllipsisLoc.isValid())
1382 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1383 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1384
Francois Pichet00eb3f92010-12-04 09:14:42 +00001385 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1386 NumArgs, IdLoc,
1387 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001388 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001389 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001390 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001391 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001392 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001393 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001394
1395 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001396 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001397 } else {
1398 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1399 LookupParsedName(R, S, &SS);
1400
1401 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1402 if (!TyD) {
1403 if (R.isAmbiguous()) return true;
1404
John McCallfd225442010-04-09 19:01:14 +00001405 // We don't want access-control diagnostics here.
1406 R.suppressDiagnostics();
1407
Douglas Gregor7a886e12010-01-19 06:46:48 +00001408 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1409 bool NotUnknownSpecialization = false;
1410 DeclContext *DC = computeDeclContext(SS, false);
1411 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1412 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1413
1414 if (!NotUnknownSpecialization) {
1415 // When the scope specifier can refer to a member of an unknown
1416 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001417 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1418 SS.getWithLocInContext(Context),
1419 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001420 if (BaseType.isNull())
1421 return true;
1422
Douglas Gregor7a886e12010-01-19 06:46:48 +00001423 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001424 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001425 }
1426 }
1427
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001428 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001429 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00001430 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001431 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1432 ClassDecl, false, CTC_NoKeywords))) {
1433 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1434 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1435 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001436 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001437 // We have found a non-static data member with a similar
1438 // name to what was typed; complain and initialize that
1439 // member.
1440 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001441 << MemberOrBase << true << CorrectedQuotedStr
1442 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001443 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001444 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001445
1446 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1447 LParenLoc, RParenLoc);
1448 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001449 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001450 const CXXBaseSpecifier *DirectBaseSpec;
1451 const CXXBaseSpecifier *VirtualBaseSpec;
1452 if (FindBaseInitializer(*this, ClassDecl,
1453 Context.getTypeDeclType(Type),
1454 DirectBaseSpec, VirtualBaseSpec)) {
1455 // We have found a direct or virtual base class with a
1456 // similar name to what was typed; complain and initialize
1457 // that base class.
1458 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001459 << MemberOrBase << false << CorrectedQuotedStr
1460 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001461
1462 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1463 : VirtualBaseSpec;
1464 Diag(BaseSpec->getSourceRange().getBegin(),
1465 diag::note_base_class_specified_here)
1466 << BaseSpec->getType()
1467 << BaseSpec->getSourceRange();
1468
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001469 TyD = Type;
1470 }
1471 }
1472 }
1473
Douglas Gregor7a886e12010-01-19 06:46:48 +00001474 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001475 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1476 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1477 return true;
1478 }
John McCall2b194412009-12-21 10:41:20 +00001479 }
1480
Douglas Gregor7a886e12010-01-19 06:46:48 +00001481 if (BaseType.isNull()) {
1482 BaseType = Context.getTypeDeclType(TyD);
1483 if (SS.isSet()) {
1484 NestedNameSpecifier *Qualifier =
1485 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001486
Douglas Gregor7a886e12010-01-19 06:46:48 +00001487 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001488 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001489 }
John McCall2b194412009-12-21 10:41:20 +00001490 }
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
John McCalla93c9342009-12-07 02:54:59 +00001493 if (!TInfo)
1494 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001495
John McCalla93c9342009-12-07 02:54:59 +00001496 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001497 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001498}
1499
John McCallb4190042009-11-04 23:02:40 +00001500/// Checks an initializer expression for use of uninitialized fields, such as
1501/// containing the field that is being initialized. Returns true if there is an
1502/// uninitialized field was used an updates the SourceLocation parameter; false
1503/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001504static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001505 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001506 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001507 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1508
Nick Lewycky43ad1822010-06-15 07:32:55 +00001509 if (isa<CallExpr>(S)) {
1510 // Do not descend into function calls or constructors, as the use
1511 // of an uninitialized field may be valid. One would have to inspect
1512 // the contents of the function/ctor to determine if it is safe or not.
1513 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1514 // may be safe, depending on what the function/ctor does.
1515 return false;
1516 }
1517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1518 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001519
1520 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1521 // The member expression points to a static data member.
1522 assert(VD->isStaticDataMember() &&
1523 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001524 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001525 return false;
1526 }
1527
1528 if (isa<EnumConstantDecl>(RhsField)) {
1529 // The member expression points to an enum.
1530 return false;
1531 }
1532
John McCallb4190042009-11-04 23:02:40 +00001533 if (RhsField == LhsField) {
1534 // Initializing a field with itself. Throw a warning.
1535 // But wait; there are exceptions!
1536 // Exception #1: The field may not belong to this record.
1537 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001538 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001539 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1540 // Even though the field matches, it does not belong to this record.
1541 return false;
1542 }
1543 // None of the exceptions triggered; return true to indicate an
1544 // uninitialized field was used.
1545 *L = ME->getMemberLoc();
1546 return true;
1547 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001548 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001549 // sizeof/alignof doesn't reference contents, do not warn.
1550 return false;
1551 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1552 // address-of doesn't reference contents (the pointer may be dereferenced
1553 // in the same expression but it would be rare; and weird).
1554 if (UOE->getOpcode() == UO_AddrOf)
1555 return false;
John McCallb4190042009-11-04 23:02:40 +00001556 }
John McCall7502c1d2011-02-13 04:07:26 +00001557 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001558 if (!*it) {
1559 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001560 continue;
1561 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001562 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1563 return true;
John McCallb4190042009-11-04 23:02:40 +00001564 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001565 return false;
John McCallb4190042009-11-04 23:02:40 +00001566}
1567
John McCallf312b1e2010-08-26 23:41:50 +00001568MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001569Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001570 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001571 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001572 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001573 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1574 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1575 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001576 "Member must be a FieldDecl or IndirectFieldDecl");
1577
Douglas Gregor464b2f02010-11-05 22:21:31 +00001578 if (Member->isInvalidDecl())
1579 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001580
John McCallb4190042009-11-04 23:02:40 +00001581 // Diagnose value-uses of fields to initialize themselves, e.g.
1582 // foo(foo)
1583 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001584 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001585 for (unsigned i = 0; i < NumArgs; ++i) {
1586 SourceLocation L;
1587 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1588 // FIXME: Return true in the case when other fields are used before being
1589 // uninitialized. For example, let this field be the i'th field. When
1590 // initializing the i'th field, throw a warning if any of the >= i'th
1591 // fields are used, as they are not yet initialized.
1592 // Right now we are only handling the case where the i'th field uses
1593 // itself in its initializer.
1594 Diag(L, diag::warn_field_is_uninit);
1595 }
1596 }
1597
Eli Friedman59c04372009-07-29 19:44:27 +00001598 bool HasDependentArg = false;
1599 for (unsigned i = 0; i < NumArgs; i++)
1600 HasDependentArg |= Args[i]->isTypeDependent();
1601
Chandler Carruth894aed92010-12-06 09:23:57 +00001602 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001603 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001604 // Can't check initialization for a member of dependent type or when
1605 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001606 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001607 RParenLoc,
1608 Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001609
John McCallf85e1932011-06-15 23:02:42 +00001610 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001611 } else {
1612 // Initialize the member.
1613 InitializedEntity MemberEntity =
1614 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1615 : InitializedEntity::InitializeMember(IndirectMember, 0);
1616 InitializationKind Kind =
1617 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001618
Chandler Carruth894aed92010-12-06 09:23:57 +00001619 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1620
1621 ExprResult MemberInit =
1622 InitSeq.Perform(*this, MemberEntity, Kind,
1623 MultiExprArg(*this, Args, NumArgs), 0);
1624 if (MemberInit.isInvalid())
1625 return true;
1626
1627 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1628
1629 // C++0x [class.base.init]p7:
1630 // The initialization of each base and member constitutes a
1631 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001632 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001633 if (MemberInit.isInvalid())
1634 return true;
1635
1636 // If we are in a dependent context, template instantiation will
1637 // perform this type-checking again. Just save the arguments that we
1638 // received in a ParenListExpr.
1639 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1640 // of the information that we have about the member
1641 // initializer. However, deconstructing the ASTs is a dicey process,
1642 // and this approach is far more likely to get the corner cases right.
1643 if (CurContext->isDependentContext())
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001644 Init = new (Context) ParenListExpr(
1645 Context, LParenLoc, Args, NumArgs, RParenLoc,
1646 Member->getType().getNonReferenceType());
Chandler Carruth894aed92010-12-06 09:23:57 +00001647 else
1648 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001649 }
1650
Chandler Carruth894aed92010-12-06 09:23:57 +00001651 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001652 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001653 IdLoc, LParenLoc, Init,
1654 RParenLoc);
1655 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001656 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001657 IdLoc, LParenLoc, Init,
1658 RParenLoc);
1659 }
Eli Friedman59c04372009-07-29 19:44:27 +00001660}
1661
John McCallf312b1e2010-08-26 23:41:50 +00001662MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001663Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1664 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001665 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001666 SourceLocation LParenLoc,
1667 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001668 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001669 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1670 if (!LangOpts.CPlusPlus0x)
1671 return Diag(Loc, diag::err_delegation_0x_only)
1672 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001673
Sean Hunt41717662011-02-26 19:13:13 +00001674 // Initialize the object.
1675 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1676 QualType(ClassDecl->getTypeForDecl(), 0));
1677 InitializationKind Kind =
1678 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1679
1680 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1681
1682 ExprResult DelegationInit =
1683 InitSeq.Perform(*this, DelegationEntity, Kind,
1684 MultiExprArg(*this, Args, NumArgs), 0);
1685 if (DelegationInit.isInvalid())
1686 return true;
1687
1688 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001689 CXXConstructorDecl *Constructor
1690 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001691 assert(Constructor && "Delegating constructor with no target?");
1692
1693 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1694
1695 // C++0x [class.base.init]p7:
1696 // The initialization of each base and member constitutes a
1697 // full-expression.
1698 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1699 if (DelegationInit.isInvalid())
1700 return true;
1701
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001702 assert(!CurContext->isDependentContext());
Sean Hunt41717662011-02-26 19:13:13 +00001703 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1704 DelegationInit.takeAs<Expr>(),
1705 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001706}
1707
1708MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001709Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001710 Expr **Args, unsigned NumArgs,
1711 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001712 CXXRecordDecl *ClassDecl,
1713 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001714 bool HasDependentArg = false;
1715 for (unsigned i = 0; i < NumArgs; i++)
1716 HasDependentArg |= Args[i]->isTypeDependent();
1717
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001718 SourceLocation BaseLoc
1719 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1720
1721 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1722 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1723 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1724
1725 // C++ [class.base.init]p2:
1726 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001727 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001728 // of that class, the mem-initializer is ill-formed. A
1729 // mem-initializer-list can initialize a base class using any
1730 // name that denotes that base class type.
1731 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1732
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001733 if (EllipsisLoc.isValid()) {
1734 // This is a pack expansion.
1735 if (!BaseType->containsUnexpandedParameterPack()) {
1736 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1737 << SourceRange(BaseLoc, RParenLoc);
1738
1739 EllipsisLoc = SourceLocation();
1740 }
1741 } else {
1742 // Check for any unexpanded parameter packs.
1743 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1744 return true;
1745
1746 for (unsigned I = 0; I != NumArgs; ++I)
1747 if (DiagnoseUnexpandedParameterPack(Args[I]))
1748 return true;
1749 }
1750
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001751 // Check for direct and virtual base classes.
1752 const CXXBaseSpecifier *DirectBaseSpec = 0;
1753 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1754 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001755 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1756 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001757 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1758 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001759
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001760 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1761 VirtualBaseSpec);
1762
1763 // C++ [base.class.init]p2:
1764 // Unless the mem-initializer-id names a nonstatic data member of the
1765 // constructor's class or a direct or virtual base of that class, the
1766 // mem-initializer is ill-formed.
1767 if (!DirectBaseSpec && !VirtualBaseSpec) {
1768 // If the class has any dependent bases, then it's possible that
1769 // one of those types will resolve to the same type as
1770 // BaseType. Therefore, just treat this as a dependent base
1771 // class initialization. FIXME: Should we try to check the
1772 // initialization anyway? It seems odd.
1773 if (ClassDecl->hasAnyDependentBases())
1774 Dependent = true;
1775 else
1776 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1777 << BaseType << Context.getTypeDeclType(ClassDecl)
1778 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1779 }
1780 }
1781
1782 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001783 // Can't check initialization for a base of dependent type or when
1784 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001785 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001786 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001787 RParenLoc, BaseType));
Eli Friedman59c04372009-07-29 19:44:27 +00001788
John McCallf85e1932011-06-15 23:02:42 +00001789 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Sean Huntcbb67482011-01-08 20:30:50 +00001791 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001792 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001793 LParenLoc,
1794 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001795 RParenLoc,
1796 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001797 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001798
1799 // C++ [base.class.init]p2:
1800 // If a mem-initializer-id is ambiguous because it designates both
1801 // a direct non-virtual base class and an inherited virtual base
1802 // class, the mem-initializer is ill-formed.
1803 if (DirectBaseSpec && VirtualBaseSpec)
1804 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001805 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001806
1807 CXXBaseSpecifier *BaseSpec
1808 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1809 if (!BaseSpec)
1810 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1811
1812 // Initialize the base.
1813 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001814 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001815 InitializationKind Kind =
1816 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1817
1818 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1819
John McCall60d7b3a2010-08-24 06:29:42 +00001820 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001821 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001822 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001823 if (BaseInit.isInvalid())
1824 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001825
1826 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001827
1828 // C++0x [class.base.init]p7:
1829 // The initialization of each base and member constitutes a
1830 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001831 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001832 if (BaseInit.isInvalid())
1833 return true;
1834
1835 // If we are in a dependent context, template instantiation will
1836 // perform this type-checking again. Just save the arguments that we
1837 // received in a ParenListExpr.
1838 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1839 // of the information that we have about the base
1840 // initializer. However, deconstructing the ASTs is a dicey process,
1841 // and this approach is far more likely to get the corner cases right.
1842 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001843 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001844 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimek0d9106f2011-06-22 20:02:16 +00001845 RParenLoc, BaseType));
Sean Huntcbb67482011-01-08 20:30:50 +00001846 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001847 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001848 LParenLoc,
1849 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001850 RParenLoc,
1851 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001852 }
1853
Sean Huntcbb67482011-01-08 20:30:50 +00001854 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001855 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001856 LParenLoc,
1857 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001858 RParenLoc,
1859 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001860}
1861
Anders Carlssone5ef7402010-04-23 03:10:23 +00001862/// ImplicitInitializerKind - How an implicit base or member initializer should
1863/// initialize its base or member.
1864enum ImplicitInitializerKind {
1865 IIK_Default,
1866 IIK_Copy,
1867 IIK_Move
1868};
1869
Anders Carlssondefefd22010-04-23 02:00:02 +00001870static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001871BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001872 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001873 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001874 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001875 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001876 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001877 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1878 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001879
John McCall60d7b3a2010-08-24 06:29:42 +00001880 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001881
1882 switch (ImplicitInitKind) {
1883 case IIK_Default: {
1884 InitializationKind InitKind
1885 = InitializationKind::CreateDefault(Constructor->getLocation());
1886 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1887 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001888 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001889 break;
1890 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001891
Anders Carlssone5ef7402010-04-23 03:10:23 +00001892 case IIK_Copy: {
1893 ParmVarDecl *Param = Constructor->getParamDecl(0);
1894 QualType ParamType = Param->getType().getNonReferenceType();
1895
1896 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001897 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001898 Constructor->getLocation(), ParamType,
1899 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001900
Anders Carlssonc7957502010-04-24 22:02:54 +00001901 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001902 QualType ArgTy =
1903 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1904 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001905
1906 CXXCastPath BasePath;
1907 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001908 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1909 CK_UncheckedDerivedToBase,
1910 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001911
Anders Carlssone5ef7402010-04-23 03:10:23 +00001912 InitializationKind InitKind
1913 = InitializationKind::CreateDirect(Constructor->getLocation(),
1914 SourceLocation(), SourceLocation());
1915 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1916 &CopyCtorArg, 1);
1917 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001918 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001919 break;
1920 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001921
Anders Carlssone5ef7402010-04-23 03:10:23 +00001922 case IIK_Move:
1923 assert(false && "Unhandled initializer kind!");
1924 }
John McCall9ae2f072010-08-23 23:25:46 +00001925
Douglas Gregor53c374f2010-12-07 00:41:46 +00001926 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001927 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001928 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001929
Anders Carlssondefefd22010-04-23 02:00:02 +00001930 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001931 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001932 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1933 SourceLocation()),
1934 BaseSpec->isVirtual(),
1935 SourceLocation(),
1936 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001937 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001938 SourceLocation());
1939
Anders Carlssondefefd22010-04-23 02:00:02 +00001940 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001941}
1942
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001943static bool
1944BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001945 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001946 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001947 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001948 if (Field->isInvalidDecl())
1949 return true;
1950
Chandler Carruthf186b542010-06-29 23:50:44 +00001951 SourceLocation Loc = Constructor->getLocation();
1952
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001953 if (ImplicitInitKind == IIK_Copy) {
1954 ParmVarDecl *Param = Constructor->getParamDecl(0);
1955 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00001956
1957 // Suppress copying zero-width bitfields.
1958 if (const Expr *Width = Field->getBitWidth())
1959 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1960 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001961
1962 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001963 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001964 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001965
1966 // Build a reference to this field within the parameter.
1967 CXXScopeSpec SS;
1968 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1969 Sema::LookupMemberName);
1970 MemberLookup.addDecl(Field, AS_public);
1971 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001972 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001973 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001974 ParamType, Loc,
1975 /*IsArrow=*/false,
1976 SS,
1977 /*FirstQualifierInScope=*/0,
1978 MemberLookup,
1979 /*TemplateArgs=*/0);
1980 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001981 return true;
1982
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001983 // When the field we are copying is an array, create index variables for
1984 // each dimension of the array. We use these index variables to subscript
1985 // the source array, and other clients (e.g., CodeGen) will perform the
1986 // necessary iteration with these index variables.
1987 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1988 QualType BaseType = Field->getType();
1989 QualType SizeType = SemaRef.Context.getSizeType();
1990 while (const ConstantArrayType *Array
1991 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1992 // Create the iteration variable for this array index.
1993 IdentifierInfo *IterationVarName = 0;
1994 {
1995 llvm::SmallString<8> Str;
1996 llvm::raw_svector_ostream OS(Str);
1997 OS << "__i" << IndexVariables.size();
1998 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1999 }
2000 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002001 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002002 IterationVarName, SizeType,
2003 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002004 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002005 IndexVariables.push_back(IterationVar);
2006
2007 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002008 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002009 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002010 assert(!IterationVarRef.isInvalid() &&
2011 "Reference to invented variable cannot fail!");
2012
2013 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002014 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002015 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002016 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002017 Loc);
2018 if (CopyCtorArg.isInvalid())
2019 return true;
2020
2021 BaseType = Array->getElementType();
2022 }
2023
2024 // Construct the entity that we will be initializing. For an array, this
2025 // will be first element in the array, which may require several levels
2026 // of array-subscript entities.
2027 llvm::SmallVector<InitializedEntity, 4> Entities;
2028 Entities.reserve(1 + IndexVariables.size());
2029 Entities.push_back(InitializedEntity::InitializeMember(Field));
2030 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2031 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2032 0,
2033 Entities.back()));
2034
2035 // Direct-initialize to use the copy constructor.
2036 InitializationKind InitKind =
2037 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2038
2039 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2040 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2041 &CopyCtorArgE, 1);
2042
John McCall60d7b3a2010-08-24 06:29:42 +00002043 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002044 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002045 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002046 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002047 if (MemberInit.isInvalid())
2048 return true;
2049
2050 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00002051 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002052 MemberInit.takeAs<Expr>(), Loc,
2053 IndexVariables.data(),
2054 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002055 return false;
2056 }
2057
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002058 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2059
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002060 QualType FieldBaseElementType =
2061 SemaRef.Context.getBaseElementType(Field->getType());
2062
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002063 if (FieldBaseElementType->isRecordType()) {
2064 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002065 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002066 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002067
2068 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002069 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002070 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002071
Douglas Gregor53c374f2010-12-07 00:41:46 +00002072 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002073 if (MemberInit.isInvalid())
2074 return true;
2075
2076 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002077 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00002078 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002079 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00002080 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002081 return false;
2082 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002083
Sean Hunt1f2f3842011-05-17 00:19:05 +00002084 if (!Field->getParent()->isUnion()) {
2085 if (FieldBaseElementType->isReferenceType()) {
2086 SemaRef.Diag(Constructor->getLocation(),
2087 diag::err_uninitialized_member_in_ctor)
2088 << (int)Constructor->isImplicit()
2089 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2090 << 0 << Field->getDeclName();
2091 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2092 return true;
2093 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002094
Sean Hunt1f2f3842011-05-17 00:19:05 +00002095 if (FieldBaseElementType.isConstQualified()) {
2096 SemaRef.Diag(Constructor->getLocation(),
2097 diag::err_uninitialized_member_in_ctor)
2098 << (int)Constructor->isImplicit()
2099 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2100 << 1 << Field->getDeclName();
2101 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2102 return true;
2103 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002104 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002105
John McCallf85e1932011-06-15 23:02:42 +00002106 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2107 FieldBaseElementType->isObjCRetainableType() &&
2108 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2109 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2110 // Instant objects:
2111 // Default-initialize Objective-C pointers to NULL.
2112 CXXMemberInit
2113 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2114 Loc, Loc,
2115 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2116 Loc);
2117 return false;
2118 }
2119
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002120 // Nothing to initialize.
2121 CXXMemberInit = 0;
2122 return false;
2123}
John McCallf1860e52010-05-20 23:23:51 +00002124
2125namespace {
2126struct BaseAndFieldInfo {
2127 Sema &S;
2128 CXXConstructorDecl *Ctor;
2129 bool AnyErrorsInInits;
2130 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002131 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2132 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002133
2134 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2135 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2136 // FIXME: Handle implicit move constructors.
2137 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2138 IIK = IIK_Copy;
2139 else
2140 IIK = IIK_Default;
2141 }
2142};
2143}
2144
Richard Smith7a614d82011-06-11 17:19:42 +00002145static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallf1860e52010-05-20 23:23:51 +00002146 FieldDecl *Top, FieldDecl *Field) {
2147
Chandler Carruthe861c602010-06-30 02:59:29 +00002148 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002149 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002150 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002151 return false;
2152 }
2153
Richard Smith7a614d82011-06-11 17:19:42 +00002154 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2155 // has a brace-or-equal-initializer, the entity is initialized as specified
2156 // in [dcl.init].
2157 if (Field->hasInClassInitializer()) {
2158 Info.AllToInit.push_back(
2159 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2160 SourceLocation(),
2161 SourceLocation(), 0,
2162 SourceLocation()));
2163 return false;
2164 }
2165
John McCallf1860e52010-05-20 23:23:51 +00002166 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2167 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2168 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002169 CXXRecordDecl *FieldClassDecl
2170 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002171
2172 // Even though union members never have non-trivial default
2173 // constructions in C++03, we still build member initializers for aggregate
2174 // record types which can be union members, and C++0x allows non-trivial
2175 // default constructors for union members, so we ensure that only one
2176 // member is initialized for these.
2177 if (FieldClassDecl->isUnion()) {
2178 // First check for an explicit initializer for one field.
2179 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2180 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002181 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002182 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002183
2184 // Once we've initialized a field of an anonymous union, the union
2185 // field in the class is also initialized, so exit immediately.
2186 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002187 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith7a614d82011-06-11 17:19:42 +00002188 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002189 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002190 }
2191 }
2192
Douglas Gregore7003b72011-07-13 02:14:02 +00002193 // FIXME: C++0x unrestricted unions might call a default constructor here.
2194 return false;
Chandler Carruthe861c602010-06-30 02:59:29 +00002195 } else {
2196 // For structs, we simply descend through to initialize all members where
2197 // necessary.
2198 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2199 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith7a614d82011-06-11 17:19:42 +00002200 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruthe861c602010-06-30 02:59:29 +00002201 return true;
2202 }
2203 }
John McCallf1860e52010-05-20 23:23:51 +00002204 }
2205
2206 // Don't try to build an implicit initializer if there were semantic
2207 // errors in any of the initializers (and therefore we might be
2208 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002209 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002210 return false;
2211
Sean Huntcbb67482011-01-08 20:30:50 +00002212 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002213 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2214 return true;
John McCallf1860e52010-05-20 23:23:51 +00002215
Francois Pichet00eb3f92010-12-04 09:14:42 +00002216 if (Init)
2217 Info.AllToInit.push_back(Init);
2218
John McCallf1860e52010-05-20 23:23:51 +00002219 return false;
2220}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002221
2222bool
2223Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2224 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002225 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002226 Constructor->setNumCtorInitializers(1);
2227 CXXCtorInitializer **initializer =
2228 new (Context) CXXCtorInitializer*[1];
2229 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2230 Constructor->setCtorInitializers(initializer);
2231
Sean Huntb76af9c2011-05-03 23:05:34 +00002232 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2233 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2234 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2235 }
2236
Sean Huntc1598702011-05-05 00:05:47 +00002237 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002238
Sean Hunt059ce0d2011-05-01 07:04:31 +00002239 return false;
2240}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002241
John McCallb77115d2011-06-17 00:18:42 +00002242bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2243 CXXCtorInitializer **Initializers,
2244 unsigned NumInitializers,
2245 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002246 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002247 // Just store the initializers as written, they will be checked during
2248 // instantiation.
2249 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002250 Constructor->setNumCtorInitializers(NumInitializers);
2251 CXXCtorInitializer **baseOrMemberInitializers =
2252 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002253 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002254 NumInitializers * sizeof(CXXCtorInitializer*));
2255 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002256 }
2257
2258 return false;
2259 }
2260
John McCallf1860e52010-05-20 23:23:51 +00002261 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002262
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002263 // We need to build the initializer AST according to order of construction
2264 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002265 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002266 if (!ClassDecl)
2267 return true;
2268
Eli Friedman80c30da2009-11-09 19:20:36 +00002269 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002271 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002272 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002273
2274 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002275 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002276 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002277 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002278 }
2279
Anders Carlsson711f34a2010-04-21 19:52:01 +00002280 // Keep track of the direct virtual bases.
2281 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2282 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2283 E = ClassDecl->bases_end(); I != E; ++I) {
2284 if (I->isVirtual())
2285 DirectVBases.insert(I);
2286 }
2287
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002288 // Push virtual bases before others.
2289 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2290 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2291
Sean Huntcbb67482011-01-08 20:30:50 +00002292 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002293 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2294 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002295 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002296 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002297 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002298 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002299 VBase, IsInheritedVirtualBase,
2300 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002301 HadError = true;
2302 continue;
2303 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002304
John McCallf1860e52010-05-20 23:23:51 +00002305 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002306 }
2307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
John McCallf1860e52010-05-20 23:23:51 +00002309 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002310 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2311 E = ClassDecl->bases_end(); Base != E; ++Base) {
2312 // Virtuals are in the virtual base list and already constructed.
2313 if (Base->isVirtual())
2314 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Sean Huntcbb67482011-01-08 20:30:50 +00002316 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002317 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2318 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002319 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002320 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002321 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002322 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002323 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002324 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002325 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002326 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002327
John McCallf1860e52010-05-20 23:23:51 +00002328 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002329 }
2330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
John McCallf1860e52010-05-20 23:23:51 +00002332 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002333 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002334 E = ClassDecl->field_end(); Field != E; ++Field) {
2335 if ((*Field)->getType()->isIncompleteArrayType()) {
2336 assert(ClassDecl->hasFlexibleArrayMember() &&
2337 "Incomplete array type is not valid");
2338 continue;
2339 }
Richard Smith7a614d82011-06-11 17:19:42 +00002340 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002341 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002342 }
Mike Stump1eb44332009-09-09 15:08:12 +00002343
John McCallf1860e52010-05-20 23:23:51 +00002344 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002345 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002346 Constructor->setNumCtorInitializers(NumInitializers);
2347 CXXCtorInitializer **baseOrMemberInitializers =
2348 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002349 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002350 NumInitializers * sizeof(CXXCtorInitializer*));
2351 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002352
John McCallef027fe2010-03-16 21:39:52 +00002353 // Constructors implicitly reference the base and member
2354 // destructors.
2355 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2356 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002357 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002358
2359 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002360}
2361
Eli Friedman6347f422009-07-21 19:28:10 +00002362static void *GetKeyForTopLevelField(FieldDecl *Field) {
2363 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002364 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002365 if (RT->getDecl()->isAnonymousStructOrUnion())
2366 return static_cast<void *>(RT->getDecl());
2367 }
2368 return static_cast<void *>(Field);
2369}
2370
Anders Carlssonea356fb2010-04-02 05:42:15 +00002371static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002372 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002373}
2374
Anders Carlssonea356fb2010-04-02 05:42:15 +00002375static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002376 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002377 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002378 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002379
Eli Friedman6347f422009-07-21 19:28:10 +00002380 // For fields injected into the class via declaration of an anonymous union,
2381 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002382 FieldDecl *Field = Member->getAnyMember();
2383
John McCall3c3ccdb2010-04-10 09:28:51 +00002384 // If the field is a member of an anonymous struct or union, our key
2385 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002386 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002387 if (RD->isAnonymousStructOrUnion()) {
2388 while (true) {
2389 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2390 if (Parent->isAnonymousStructOrUnion())
2391 RD = Parent;
2392 else
2393 break;
2394 }
2395
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002396 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002397 }
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002399 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002400}
2401
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002402static void
2403DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002404 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002405 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002406 unsigned NumInits) {
2407 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002408 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002410 // Don't check initializers order unless the warning is enabled at the
2411 // location of at least one initializer.
2412 bool ShouldCheckOrder = false;
2413 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002414 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002415 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2416 Init->getSourceLocation())
2417 != Diagnostic::Ignored) {
2418 ShouldCheckOrder = true;
2419 break;
2420 }
2421 }
2422 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002423 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002424
John McCalld6ca8da2010-04-10 07:37:23 +00002425 // Build the list of bases and members in the order that they'll
2426 // actually be initialized. The explicit initializers should be in
2427 // this same order but may be missing things.
2428 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Anders Carlsson071d6102010-04-02 03:38:04 +00002430 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2431
John McCalld6ca8da2010-04-10 07:37:23 +00002432 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002433 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002434 ClassDecl->vbases_begin(),
2435 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002436 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002437
John McCalld6ca8da2010-04-10 07:37:23 +00002438 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002439 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002440 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002441 if (Base->isVirtual())
2442 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002443 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002444 }
Mike Stump1eb44332009-09-09 15:08:12 +00002445
John McCalld6ca8da2010-04-10 07:37:23 +00002446 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002447 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2448 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002449 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002450
John McCalld6ca8da2010-04-10 07:37:23 +00002451 unsigned NumIdealInits = IdealInitKeys.size();
2452 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002453
Sean Huntcbb67482011-01-08 20:30:50 +00002454 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002455 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002456 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002457 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002458
2459 // Scan forward to try to find this initializer in the idealized
2460 // initializers list.
2461 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2462 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002463 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002464
2465 // If we didn't find this initializer, it must be because we
2466 // scanned past it on a previous iteration. That can only
2467 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002468 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002469 Sema::SemaDiagnosticBuilder D =
2470 SemaRef.Diag(PrevInit->getSourceLocation(),
2471 diag::warn_initializer_out_of_order);
2472
Francois Pichet00eb3f92010-12-04 09:14:42 +00002473 if (PrevInit->isAnyMemberInitializer())
2474 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002475 else
2476 D << 1 << PrevInit->getBaseClassInfo()->getType();
2477
Francois Pichet00eb3f92010-12-04 09:14:42 +00002478 if (Init->isAnyMemberInitializer())
2479 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002480 else
2481 D << 1 << Init->getBaseClassInfo()->getType();
2482
2483 // Move back to the initializer's location in the ideal list.
2484 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2485 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002486 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002487
2488 assert(IdealIndex != NumIdealInits &&
2489 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002490 }
John McCalld6ca8da2010-04-10 07:37:23 +00002491
2492 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002493 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002494}
2495
John McCall3c3ccdb2010-04-10 09:28:51 +00002496namespace {
2497bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002498 CXXCtorInitializer *Init,
2499 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002500 if (!PrevInit) {
2501 PrevInit = Init;
2502 return false;
2503 }
2504
2505 if (FieldDecl *Field = Init->getMember())
2506 S.Diag(Init->getSourceLocation(),
2507 diag::err_multiple_mem_initialization)
2508 << Field->getDeclName()
2509 << Init->getSourceRange();
2510 else {
John McCallf4c73712011-01-19 06:33:43 +00002511 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002512 assert(BaseClass && "neither field nor base");
2513 S.Diag(Init->getSourceLocation(),
2514 diag::err_multiple_base_initialization)
2515 << QualType(BaseClass, 0)
2516 << Init->getSourceRange();
2517 }
2518 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2519 << 0 << PrevInit->getSourceRange();
2520
2521 return true;
2522}
2523
Sean Huntcbb67482011-01-08 20:30:50 +00002524typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002525typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2526
2527bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002528 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002529 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002530 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002531 RecordDecl *Parent = Field->getParent();
2532 if (!Parent->isAnonymousStructOrUnion())
2533 return false;
2534
2535 NamedDecl *Child = Field;
2536 do {
2537 if (Parent->isUnion()) {
2538 UnionEntry &En = Unions[Parent];
2539 if (En.first && En.first != Child) {
2540 S.Diag(Init->getSourceLocation(),
2541 diag::err_multiple_mem_union_initialization)
2542 << Field->getDeclName()
2543 << Init->getSourceRange();
2544 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2545 << 0 << En.second->getSourceRange();
2546 return true;
2547 } else if (!En.first) {
2548 En.first = Child;
2549 En.second = Init;
2550 }
2551 }
2552
2553 Child = Parent;
2554 Parent = cast<RecordDecl>(Parent->getDeclContext());
2555 } while (Parent->isAnonymousStructOrUnion());
2556
2557 return false;
2558}
2559}
2560
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002561/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002562void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002563 SourceLocation ColonLoc,
2564 MemInitTy **meminits, unsigned NumMemInits,
2565 bool AnyErrors) {
2566 if (!ConstructorDecl)
2567 return;
2568
2569 AdjustDeclIfTemplate(ConstructorDecl);
2570
2571 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002572 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002573
2574 if (!Constructor) {
2575 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2576 return;
2577 }
2578
Sean Huntcbb67482011-01-08 20:30:50 +00002579 CXXCtorInitializer **MemInits =
2580 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002581
2582 // Mapping for the duplicate initializers check.
2583 // For member initializers, this is keyed with a FieldDecl*.
2584 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002585 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002586
2587 // Mapping for the inconsistent anonymous-union initializers check.
2588 RedundantUnionMap MemberUnions;
2589
Anders Carlssonea356fb2010-04-02 05:42:15 +00002590 bool HadError = false;
2591 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002592 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002593
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002594 // Set the source order index.
2595 Init->setSourceOrder(i);
2596
Francois Pichet00eb3f92010-12-04 09:14:42 +00002597 if (Init->isAnyMemberInitializer()) {
2598 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002599 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2600 CheckRedundantUnionInit(*this, Init, MemberUnions))
2601 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002602 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002603 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2604 if (CheckRedundantInit(*this, Init, Members[Key]))
2605 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002606 } else {
2607 assert(Init->isDelegatingInitializer());
2608 // This must be the only initializer
2609 if (i != 0 || NumMemInits > 1) {
2610 Diag(MemInits[0]->getSourceLocation(),
2611 diag::err_delegating_initializer_alone)
2612 << MemInits[0]->getSourceRange();
2613 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002614 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002615 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002616 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002617 // Return immediately as the initializer is set.
2618 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002619 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002620 }
2621
Anders Carlssonea356fb2010-04-02 05:42:15 +00002622 if (HadError)
2623 return;
2624
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002625 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002626
Sean Huntcbb67482011-01-08 20:30:50 +00002627 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002628}
2629
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002630void
John McCallef027fe2010-03-16 21:39:52 +00002631Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2632 CXXRecordDecl *ClassDecl) {
2633 // Ignore dependent contexts.
2634 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002635 return;
John McCall58e6f342010-03-16 05:22:47 +00002636
2637 // FIXME: all the access-control diagnostics are positioned on the
2638 // field/base declaration. That's probably good; that said, the
2639 // user might reasonably want to know why the destructor is being
2640 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002641
Anders Carlsson9f853df2009-11-17 04:44:12 +00002642 // Non-static data members.
2643 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2644 E = ClassDecl->field_end(); I != E; ++I) {
2645 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002646 if (Field->isInvalidDecl())
2647 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002648 QualType FieldType = Context.getBaseElementType(Field->getType());
2649
2650 const RecordType* RT = FieldType->getAs<RecordType>();
2651 if (!RT)
2652 continue;
2653
2654 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002655 if (FieldClassDecl->isInvalidDecl())
2656 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002657 if (FieldClassDecl->hasTrivialDestructor())
2658 continue;
2659
Douglas Gregordb89f282010-07-01 22:47:18 +00002660 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002661 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002662 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002663 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002664 << Field->getDeclName()
2665 << FieldType);
2666
John McCallef027fe2010-03-16 21:39:52 +00002667 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002668 }
2669
John McCall58e6f342010-03-16 05:22:47 +00002670 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2671
Anders Carlsson9f853df2009-11-17 04:44:12 +00002672 // Bases.
2673 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2674 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002675 // Bases are always records in a well-formed non-dependent class.
2676 const RecordType *RT = Base->getType()->getAs<RecordType>();
2677
2678 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002679 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002680 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002681
John McCall58e6f342010-03-16 05:22:47 +00002682 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002683 // If our base class is invalid, we probably can't get its dtor anyway.
2684 if (BaseClassDecl->isInvalidDecl())
2685 continue;
2686 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002687 if (BaseClassDecl->hasTrivialDestructor())
2688 continue;
John McCall58e6f342010-03-16 05:22:47 +00002689
Douglas Gregordb89f282010-07-01 22:47:18 +00002690 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002691 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002692
2693 // FIXME: caret should be on the start of the class name
2694 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002695 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002696 << Base->getType()
2697 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002698
John McCallef027fe2010-03-16 21:39:52 +00002699 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002700 }
2701
2702 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002703 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2704 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002705
2706 // Bases are always records in a well-formed non-dependent class.
2707 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2708
2709 // Ignore direct virtual bases.
2710 if (DirectVirtualBases.count(RT))
2711 continue;
2712
John McCall58e6f342010-03-16 05:22:47 +00002713 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002714 // If our base class is invalid, we probably can't get its dtor anyway.
2715 if (BaseClassDecl->isInvalidDecl())
2716 continue;
2717 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002718 if (BaseClassDecl->hasTrivialDestructor())
2719 continue;
John McCall58e6f342010-03-16 05:22:47 +00002720
Douglas Gregordb89f282010-07-01 22:47:18 +00002721 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002722 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002723 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002724 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002725 << VBase->getType());
2726
John McCallef027fe2010-03-16 21:39:52 +00002727 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002728 }
2729}
2730
John McCalld226f652010-08-21 09:40:31 +00002731void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002732 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002733 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Mike Stump1eb44332009-09-09 15:08:12 +00002735 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002736 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002737 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002738}
2739
Mike Stump1eb44332009-09-09 15:08:12 +00002740bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002741 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002742 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002743 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002744 else
John McCall94c3b562010-08-18 09:41:07 +00002745 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002746}
2747
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002748bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002749 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002750 if (!getLangOptions().CPlusPlus)
2751 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Anders Carlsson11f21a02009-03-23 19:10:31 +00002753 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002754 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Ted Kremenek6217b802009-07-29 21:53:49 +00002756 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002757 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002758 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002759 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002761 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002762 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002763 }
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Ted Kremenek6217b802009-07-29 21:53:49 +00002765 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002766 if (!RT)
2767 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002768
John McCall86ff3082010-02-04 22:26:26 +00002769 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002770
John McCall94c3b562010-08-18 09:41:07 +00002771 // We can't answer whether something is abstract until it has a
2772 // definition. If it's currently being defined, we'll walk back
2773 // over all the declarations when we have a full definition.
2774 const CXXRecordDecl *Def = RD->getDefinition();
2775 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002776 return false;
2777
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002778 if (!RD->isAbstract())
2779 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002781 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002782 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002783
John McCall94c3b562010-08-18 09:41:07 +00002784 return true;
2785}
2786
2787void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2788 // Check if we've already emitted the list of pure virtual functions
2789 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002790 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002791 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002793 CXXFinalOverriderMap FinalOverriders;
2794 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002796 // Keep a set of seen pure methods so we won't diagnose the same method
2797 // more than once.
2798 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2799
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002800 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2801 MEnd = FinalOverriders.end();
2802 M != MEnd;
2803 ++M) {
2804 for (OverridingMethods::iterator SO = M->second.begin(),
2805 SOEnd = M->second.end();
2806 SO != SOEnd; ++SO) {
2807 // C++ [class.abstract]p4:
2808 // A class is abstract if it contains or inherits at least one
2809 // pure virtual function for which the final overrider is pure
2810 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002812 //
2813 if (SO->second.size() != 1)
2814 continue;
2815
2816 if (!SO->second.front().Method->isPure())
2817 continue;
2818
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002819 if (!SeenPureMethods.insert(SO->second.front().Method))
2820 continue;
2821
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002822 Diag(SO->second.front().Method->getLocation(),
2823 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002824 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002825 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002826 }
2827
2828 if (!PureVirtualClassDiagSet)
2829 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2830 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002831}
2832
Anders Carlsson8211eff2009-03-24 01:19:16 +00002833namespace {
John McCall94c3b562010-08-18 09:41:07 +00002834struct AbstractUsageInfo {
2835 Sema &S;
2836 CXXRecordDecl *Record;
2837 CanQualType AbstractType;
2838 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002839
John McCall94c3b562010-08-18 09:41:07 +00002840 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2841 : S(S), Record(Record),
2842 AbstractType(S.Context.getCanonicalType(
2843 S.Context.getTypeDeclType(Record))),
2844 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002845
John McCall94c3b562010-08-18 09:41:07 +00002846 void DiagnoseAbstractType() {
2847 if (Invalid) return;
2848 S.DiagnoseAbstractType(Record);
2849 Invalid = true;
2850 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002851
John McCall94c3b562010-08-18 09:41:07 +00002852 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2853};
2854
2855struct CheckAbstractUsage {
2856 AbstractUsageInfo &Info;
2857 const NamedDecl *Ctx;
2858
2859 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2860 : Info(Info), Ctx(Ctx) {}
2861
2862 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2863 switch (TL.getTypeLocClass()) {
2864#define ABSTRACT_TYPELOC(CLASS, PARENT)
2865#define TYPELOC(CLASS, PARENT) \
2866 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2867#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002868 }
John McCall94c3b562010-08-18 09:41:07 +00002869 }
Mike Stump1eb44332009-09-09 15:08:12 +00002870
John McCall94c3b562010-08-18 09:41:07 +00002871 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2872 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2873 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002874 if (!TL.getArg(I))
2875 continue;
2876
John McCall94c3b562010-08-18 09:41:07 +00002877 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2878 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002879 }
John McCall94c3b562010-08-18 09:41:07 +00002880 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002881
John McCall94c3b562010-08-18 09:41:07 +00002882 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2883 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2884 }
Mike Stump1eb44332009-09-09 15:08:12 +00002885
John McCall94c3b562010-08-18 09:41:07 +00002886 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2887 // Visit the type parameters from a permissive context.
2888 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2889 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2890 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2891 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2892 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2893 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002894 }
John McCall94c3b562010-08-18 09:41:07 +00002895 }
Mike Stump1eb44332009-09-09 15:08:12 +00002896
John McCall94c3b562010-08-18 09:41:07 +00002897 // Visit pointee types from a permissive context.
2898#define CheckPolymorphic(Type) \
2899 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2900 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2901 }
2902 CheckPolymorphic(PointerTypeLoc)
2903 CheckPolymorphic(ReferenceTypeLoc)
2904 CheckPolymorphic(MemberPointerTypeLoc)
2905 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002906
John McCall94c3b562010-08-18 09:41:07 +00002907 /// Handle all the types we haven't given a more specific
2908 /// implementation for above.
2909 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2910 // Every other kind of type that we haven't called out already
2911 // that has an inner type is either (1) sugar or (2) contains that
2912 // inner type in some way as a subobject.
2913 if (TypeLoc Next = TL.getNextTypeLoc())
2914 return Visit(Next, Sel);
2915
2916 // If there's no inner type and we're in a permissive context,
2917 // don't diagnose.
2918 if (Sel == Sema::AbstractNone) return;
2919
2920 // Check whether the type matches the abstract type.
2921 QualType T = TL.getType();
2922 if (T->isArrayType()) {
2923 Sel = Sema::AbstractArrayType;
2924 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002925 }
John McCall94c3b562010-08-18 09:41:07 +00002926 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2927 if (CT != Info.AbstractType) return;
2928
2929 // It matched; do some magic.
2930 if (Sel == Sema::AbstractArrayType) {
2931 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2932 << T << TL.getSourceRange();
2933 } else {
2934 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2935 << Sel << T << TL.getSourceRange();
2936 }
2937 Info.DiagnoseAbstractType();
2938 }
2939};
2940
2941void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2942 Sema::AbstractDiagSelID Sel) {
2943 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2944}
2945
2946}
2947
2948/// Check for invalid uses of an abstract type in a method declaration.
2949static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2950 CXXMethodDecl *MD) {
2951 // No need to do the check on definitions, which require that
2952 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002953 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002954 return;
2955
2956 // For safety's sake, just ignore it if we don't have type source
2957 // information. This should never happen for non-implicit methods,
2958 // but...
2959 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2960 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2961}
2962
2963/// Check for invalid uses of an abstract type within a class definition.
2964static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2965 CXXRecordDecl *RD) {
2966 for (CXXRecordDecl::decl_iterator
2967 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2968 Decl *D = *I;
2969 if (D->isImplicit()) continue;
2970
2971 // Methods and method templates.
2972 if (isa<CXXMethodDecl>(D)) {
2973 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2974 } else if (isa<FunctionTemplateDecl>(D)) {
2975 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2976 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2977
2978 // Fields and static variables.
2979 } else if (isa<FieldDecl>(D)) {
2980 FieldDecl *FD = cast<FieldDecl>(D);
2981 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2982 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2983 } else if (isa<VarDecl>(D)) {
2984 VarDecl *VD = cast<VarDecl>(D);
2985 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2986 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2987
2988 // Nested classes and class templates.
2989 } else if (isa<CXXRecordDecl>(D)) {
2990 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2991 } else if (isa<ClassTemplateDecl>(D)) {
2992 CheckAbstractClassUsage(Info,
2993 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2994 }
2995 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002996}
2997
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002998/// \brief Perform semantic checks on a class definition that has been
2999/// completing, introducing implicitly-declared members, checking for
3000/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003001void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003002 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003003 return;
3004
John McCall94c3b562010-08-18 09:41:07 +00003005 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3006 AbstractUsageInfo Info(*this, Record);
3007 CheckAbstractClassUsage(Info, Record);
3008 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003009
3010 // If this is not an aggregate type and has no user-declared constructor,
3011 // complain about any non-static data members of reference or const scalar
3012 // type, since they will never get initializers.
3013 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3014 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3015 bool Complained = false;
3016 for (RecordDecl::field_iterator F = Record->field_begin(),
3017 FEnd = Record->field_end();
3018 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003019 if (F->hasInClassInitializer())
3020 continue;
3021
Douglas Gregor325e5932010-04-15 00:00:53 +00003022 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003023 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003024 if (!Complained) {
3025 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3026 << Record->getTagKind() << Record;
3027 Complained = true;
3028 }
3029
3030 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3031 << F->getType()->isReferenceType()
3032 << F->getDeclName();
3033 }
3034 }
3035 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003036
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003037 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003038 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003039
3040 if (Record->getIdentifier()) {
3041 // C++ [class.mem]p13:
3042 // If T is the name of a class, then each of the following shall have a
3043 // name different from T:
3044 // - every member of every anonymous union that is a member of class T.
3045 //
3046 // C++ [class.mem]p14:
3047 // In addition, if class T has a user-declared constructor (12.1), every
3048 // non-static data member of class T shall have a name different from T.
3049 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003050 R.first != R.second; ++R.first) {
3051 NamedDecl *D = *R.first;
3052 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3053 isa<IndirectFieldDecl>(D)) {
3054 Diag(D->getLocation(), diag::err_member_name_of_class)
3055 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003056 break;
3057 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003058 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003059 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003060
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003061 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003062 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003063 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003064 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003065 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3066 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3067 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003068
3069 // See if a method overloads virtual methods in a base
3070 /// class without overriding any.
3071 if (!Record->isDependentType()) {
3072 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3073 MEnd = Record->method_end();
3074 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003075 if (!(*M)->isStatic())
3076 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003077 }
3078 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003079
3080 // Declare inherited constructors. We do this eagerly here because:
3081 // - The standard requires an eager diagnostic for conflicting inherited
3082 // constructors from different classes.
3083 // - The lazy declaration of the other implicit constructors is so as to not
3084 // waste space and performance on classes that are not meant to be
3085 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3086 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003087 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003088
Sean Hunteb88ae52011-05-23 21:07:59 +00003089 if (!Record->isDependentType())
3090 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003091}
3092
3093void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003094 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3095 ME = Record->method_end();
3096 MI != ME; ++MI) {
3097 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3098 switch (getSpecialMember(*MI)) {
3099 case CXXDefaultConstructor:
3100 CheckExplicitlyDefaultedDefaultConstructor(
3101 cast<CXXConstructorDecl>(*MI));
3102 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003103
Sean Huntcb45a0f2011-05-12 22:46:25 +00003104 case CXXDestructor:
3105 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3106 break;
3107
3108 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003109 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3110 break;
3111
Sean Huntcb45a0f2011-05-12 22:46:25 +00003112 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003113 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003114 break;
3115
Sean Hunt82713172011-05-25 23:16:36 +00003116 case CXXMoveConstructor:
3117 case CXXMoveAssignment:
3118 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3119 break;
3120
Sean Huntcb45a0f2011-05-12 22:46:25 +00003121 default:
Sean Hunt2b188082011-05-14 05:23:28 +00003122 // FIXME: Do moves once they exist
Sean Huntcb45a0f2011-05-12 22:46:25 +00003123 llvm_unreachable("non-special member explicitly defaulted!");
3124 }
Sean Hunt001cad92011-05-10 00:49:42 +00003125 }
3126 }
3127
Sean Hunt001cad92011-05-10 00:49:42 +00003128}
3129
3130void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3131 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3132
3133 // Whether this was the first-declared instance of the constructor.
3134 // This affects whether we implicitly add an exception spec (and, eventually,
3135 // constexpr). It is also ill-formed to explicitly default a constructor such
3136 // that it would be deleted. (C++0x [decl.fct.def.default])
3137 bool First = CD == CD->getCanonicalDecl();
3138
Sean Hunt49634cf2011-05-13 06:10:58 +00003139 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003140 if (CD->getNumParams() != 0) {
3141 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3142 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003143 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003144 }
3145
3146 ImplicitExceptionSpecification Spec
3147 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3148 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003149 if (EPI.ExceptionSpecType == EST_Delayed) {
3150 // Exception specification depends on some deferred part of the class. We'll
3151 // try again when the class's definition has been fully processed.
3152 return;
3153 }
Sean Hunt001cad92011-05-10 00:49:42 +00003154 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3155 *ExceptionType = Context.getFunctionType(
3156 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3157
3158 if (CtorType->hasExceptionSpec()) {
3159 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003160 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003161 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003162 PDiag(),
3163 ExceptionType, SourceLocation(),
3164 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003165 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003166 }
3167 } else if (First) {
3168 // We set the declaration to have the computed exception spec here.
3169 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003170 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003171 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3172 }
Sean Huntca46d132011-05-12 03:51:48 +00003173
Sean Hunt49634cf2011-05-13 06:10:58 +00003174 if (HadError) {
3175 CD->setInvalidDecl();
3176 return;
3177 }
3178
Sean Huntca46d132011-05-12 03:51:48 +00003179 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003180 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003181 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003182 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003183 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003184 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003185 CD->setInvalidDecl();
3186 }
3187 }
3188}
3189
3190void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3191 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3192
3193 // Whether this was the first-declared instance of the constructor.
3194 bool First = CD == CD->getCanonicalDecl();
3195
3196 bool HadError = false;
3197 if (CD->getNumParams() != 1) {
3198 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3199 << CD->getSourceRange();
3200 HadError = true;
3201 }
3202
3203 ImplicitExceptionSpecification Spec(Context);
3204 bool Const;
3205 llvm::tie(Spec, Const) =
3206 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3207
3208 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3209 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3210 *ExceptionType = Context.getFunctionType(
3211 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3212
3213 // Check for parameter type matching.
3214 // This is a copy ctor so we know it's a cv-qualified reference to T.
3215 QualType ArgType = CtorType->getArgType(0);
3216 if (ArgType->getPointeeType().isVolatileQualified()) {
3217 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3218 HadError = true;
3219 }
3220 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3221 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3222 HadError = true;
3223 }
3224
3225 if (CtorType->hasExceptionSpec()) {
3226 if (CheckEquivalentExceptionSpec(
3227 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003228 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003229 PDiag(),
3230 ExceptionType, SourceLocation(),
3231 CtorType, CD->getLocation())) {
3232 HadError = true;
3233 }
3234 } else if (First) {
3235 // We set the declaration to have the computed exception spec here.
3236 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003237 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003238 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3239 }
3240
3241 if (HadError) {
3242 CD->setInvalidDecl();
3243 return;
3244 }
3245
3246 if (ShouldDeleteCopyConstructor(CD)) {
3247 if (First) {
3248 CD->setDeletedAsWritten();
3249 } else {
3250 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003251 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003252 CD->setInvalidDecl();
3253 }
Sean Huntca46d132011-05-12 03:51:48 +00003254 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003255}
Sean Hunt001cad92011-05-10 00:49:42 +00003256
Sean Hunt2b188082011-05-14 05:23:28 +00003257void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3258 assert(MD->isExplicitlyDefaulted());
3259
3260 // Whether this was the first-declared instance of the operator
3261 bool First = MD == MD->getCanonicalDecl();
3262
3263 bool HadError = false;
3264 if (MD->getNumParams() != 1) {
3265 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3266 << MD->getSourceRange();
3267 HadError = true;
3268 }
3269
3270 QualType ReturnType =
3271 MD->getType()->getAs<FunctionType>()->getResultType();
3272 if (!ReturnType->isLValueReferenceType() ||
3273 !Context.hasSameType(
3274 Context.getCanonicalType(ReturnType->getPointeeType()),
3275 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3276 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3277 HadError = true;
3278 }
3279
3280 ImplicitExceptionSpecification Spec(Context);
3281 bool Const;
3282 llvm::tie(Spec, Const) =
3283 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3284
3285 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3286 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3287 *ExceptionType = Context.getFunctionType(
3288 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3289
Sean Hunt2b188082011-05-14 05:23:28 +00003290 QualType ArgType = OperType->getArgType(0);
Sean Huntbe631222011-05-17 20:44:43 +00003291 if (!ArgType->isReferenceType()) {
3292 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003293 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003294 } else {
3295 if (ArgType->getPointeeType().isVolatileQualified()) {
3296 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3297 HadError = true;
3298 }
3299 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3300 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3301 HadError = true;
3302 }
Sean Hunt2b188082011-05-14 05:23:28 +00003303 }
Sean Huntbe631222011-05-17 20:44:43 +00003304
Sean Hunt2b188082011-05-14 05:23:28 +00003305 if (OperType->getTypeQuals()) {
3306 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3307 HadError = true;
3308 }
3309
3310 if (OperType->hasExceptionSpec()) {
3311 if (CheckEquivalentExceptionSpec(
3312 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003313 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003314 PDiag(),
3315 ExceptionType, SourceLocation(),
3316 OperType, MD->getLocation())) {
3317 HadError = true;
3318 }
3319 } else if (First) {
3320 // We set the declaration to have the computed exception spec here.
3321 // We duplicate the one parameter type.
3322 EPI.RefQualifier = OperType->getRefQualifier();
3323 EPI.ExtInfo = OperType->getExtInfo();
3324 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3325 }
3326
3327 if (HadError) {
3328 MD->setInvalidDecl();
3329 return;
3330 }
3331
3332 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3333 if (First) {
3334 MD->setDeletedAsWritten();
3335 } else {
3336 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003337 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003338 MD->setInvalidDecl();
3339 }
3340 }
3341}
3342
Sean Huntcb45a0f2011-05-12 22:46:25 +00003343void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3344 assert(DD->isExplicitlyDefaulted());
3345
3346 // Whether this was the first-declared instance of the destructor.
3347 bool First = DD == DD->getCanonicalDecl();
3348
3349 ImplicitExceptionSpecification Spec
3350 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3351 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3352 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3353 *ExceptionType = Context.getFunctionType(
3354 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3355
3356 if (DtorType->hasExceptionSpec()) {
3357 if (CheckEquivalentExceptionSpec(
3358 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003359 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003360 PDiag(),
3361 ExceptionType, SourceLocation(),
3362 DtorType, DD->getLocation())) {
3363 DD->setInvalidDecl();
3364 return;
3365 }
3366 } else if (First) {
3367 // We set the declaration to have the computed exception spec here.
3368 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003369 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003370 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3371 }
3372
3373 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003374 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003375 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003376 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003377 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003378 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003379 DD->setInvalidDecl();
3380 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003381 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003382}
3383
Sean Huntcdee3fe2011-05-11 22:34:38 +00003384bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3385 CXXRecordDecl *RD = CD->getParent();
3386 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003387 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003388 return false;
3389
Sean Hunt71a682f2011-05-18 03:41:58 +00003390 SourceLocation Loc = CD->getLocation();
3391
Sean Huntcdee3fe2011-05-11 22:34:38 +00003392 // Do access control from the constructor
3393 ContextRAII CtorContext(*this, CD);
3394
3395 bool Union = RD->isUnion();
3396 bool AllConst = true;
3397
Sean Huntcdee3fe2011-05-11 22:34:38 +00003398 // We do this because we should never actually use an anonymous
3399 // union's constructor.
3400 if (Union && RD->isAnonymousStructOrUnion())
3401 return false;
3402
3403 // FIXME: We should put some diagnostic logic right into this function.
3404
3405 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003406 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003407
3408 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3409 BE = RD->bases_end();
3410 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003411 // We'll handle this one later
3412 if (BI->isVirtual())
3413 continue;
3414
Sean Huntcdee3fe2011-05-11 22:34:38 +00003415 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3416 assert(BaseDecl && "base isn't a CXXRecordDecl");
3417
3418 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003419 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003420 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3421 if (BaseDtor->isDeleted())
3422 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003423 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003424 AR_accessible)
3425 return true;
3426
Sean Huntcdee3fe2011-05-11 22:34:38 +00003427 // -- any [direct base class either] has no default constructor or
3428 // overload resolution as applied to [its] default constructor
3429 // results in an ambiguity or in a function that is deleted or
3430 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003431 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3432 if (!BaseDefault || BaseDefault->isDeleted())
3433 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003434
Sean Huntb320e0c2011-06-10 03:50:41 +00003435 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3436 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003437 return true;
3438 }
3439
3440 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3441 BE = RD->vbases_end();
3442 BI != BE; ++BI) {
3443 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3444 assert(BaseDecl && "base isn't a CXXRecordDecl");
3445
3446 // -- any [virtual base class] has a type with a destructor that is
3447 // delete or inaccessible from the defaulted default constructor
3448 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3449 if (BaseDtor->isDeleted())
3450 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003451 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003452 AR_accessible)
3453 return true;
3454
3455 // -- any [virtual base class either] has no default constructor or
3456 // overload resolution as applied to [its] default constructor
3457 // results in an ambiguity or in a function that is deleted or
3458 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003459 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3460 if (!BaseDefault || BaseDefault->isDeleted())
3461 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003462
Sean Huntb320e0c2011-06-10 03:50:41 +00003463 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3464 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003465 return true;
3466 }
3467
3468 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3469 FE = RD->field_end();
3470 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003471 if (FI->isInvalidDecl())
3472 continue;
3473
Sean Huntcdee3fe2011-05-11 22:34:38 +00003474 QualType FieldType = Context.getBaseElementType(FI->getType());
3475 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003476
Sean Huntcdee3fe2011-05-11 22:34:38 +00003477 // -- any non-static data member with no brace-or-equal-initializer is of
3478 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003479 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003480 return true;
3481
3482 // -- X is a union and all its variant members are of const-qualified type
3483 // (or array thereof)
3484 if (Union && !FieldType.isConstQualified())
3485 AllConst = false;
3486
3487 if (FieldRecord) {
3488 // -- X is a union-like class that has a variant member with a non-trivial
3489 // default constructor
3490 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3491 return true;
3492
3493 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3494 if (FieldDtor->isDeleted())
3495 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003496 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003497 AR_accessible)
3498 return true;
3499
3500 // -- any non-variant non-static data member of const-qualified type (or
3501 // array thereof) with no brace-or-equal-initializer does not have a
3502 // user-provided default constructor
3503 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003504 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003505 !FieldRecord->hasUserProvidedDefaultConstructor())
3506 return true;
3507
3508 if (!Union && FieldRecord->isUnion() &&
3509 FieldRecord->isAnonymousStructOrUnion()) {
3510 // We're okay to reuse AllConst here since we only care about the
3511 // value otherwise if we're in a union.
3512 AllConst = true;
3513
3514 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3515 UE = FieldRecord->field_end();
3516 UI != UE; ++UI) {
3517 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3518 CXXRecordDecl *UnionFieldRecord =
3519 UnionFieldType->getAsCXXRecordDecl();
3520
3521 if (!UnionFieldType.isConstQualified())
3522 AllConst = false;
3523
3524 if (UnionFieldRecord &&
3525 !UnionFieldRecord->hasTrivialDefaultConstructor())
3526 return true;
3527 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003528
Sean Huntcdee3fe2011-05-11 22:34:38 +00003529 if (AllConst)
3530 return true;
3531
3532 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003533 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003534 continue;
3535 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003536
Richard Smith7a614d82011-06-11 17:19:42 +00003537 // -- any non-static data member with no brace-or-equal-initializer has
3538 // class type M (or array thereof) and either M has no default
3539 // constructor or overload resolution as applied to M's default
3540 // constructor results in an ambiguity or in a function that is deleted
3541 // or inaccessible from the defaulted default constructor.
3542 if (!FI->hasInClassInitializer()) {
3543 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3544 if (!FieldDefault || FieldDefault->isDeleted())
3545 return true;
3546 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3547 PDiag()) != AR_accessible)
3548 return true;
3549 }
3550 } else if (!Union && FieldType.isConstQualified() &&
3551 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003552 // -- any non-variant non-static data member of const-qualified type (or
3553 // array thereof) with no brace-or-equal-initializer does not have a
3554 // user-provided default constructor
3555 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003556 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003557 }
3558
3559 if (Union && AllConst)
3560 return true;
3561
3562 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003563}
3564
Sean Hunt49634cf2011-05-13 06:10:58 +00003565bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003566 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003567 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003568 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt49634cf2011-05-13 06:10:58 +00003569 return false;
3570
Sean Hunt71a682f2011-05-18 03:41:58 +00003571 SourceLocation Loc = CD->getLocation();
3572
Sean Hunt49634cf2011-05-13 06:10:58 +00003573 // Do access control from the constructor
3574 ContextRAII CtorContext(*this, CD);
3575
Sean Huntc530d172011-06-10 04:44:37 +00003576 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003577
Sean Hunt2b188082011-05-14 05:23:28 +00003578 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3579 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003580 unsigned ArgQuals =
3581 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3582 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003583
3584 // We do this because we should never actually use an anonymous
3585 // union's constructor.
3586 if (Union && RD->isAnonymousStructOrUnion())
3587 return false;
3588
3589 // FIXME: We should put some diagnostic logic right into this function.
3590
3591 // C++0x [class.copy]/11
3592 // A defaulted [copy] constructor for class X is defined as delete if X has:
3593
3594 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3595 BE = RD->bases_end();
3596 BI != BE; ++BI) {
3597 // We'll handle this one later
3598 if (BI->isVirtual())
3599 continue;
3600
3601 QualType BaseType = BI->getType();
3602 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3603 assert(BaseDecl && "base isn't a CXXRecordDecl");
3604
3605 // -- any [direct base class] of a type with a destructor that is deleted or
3606 // inaccessible from the defaulted constructor
3607 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3608 if (BaseDtor->isDeleted())
3609 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003610 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003611 AR_accessible)
3612 return true;
3613
3614 // -- a [direct base class] B that cannot be [copied] because overload
3615 // resolution, as applied to B's [copy] constructor, results in an
3616 // ambiguity or a function that is deleted or inaccessible from the
3617 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003618 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003619 if (!BaseCtor || BaseCtor->isDeleted())
3620 return true;
3621 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3622 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003623 return true;
3624 }
3625
3626 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3627 BE = RD->vbases_end();
3628 BI != BE; ++BI) {
3629 QualType BaseType = BI->getType();
3630 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3631 assert(BaseDecl && "base isn't a CXXRecordDecl");
3632
Sean Huntb320e0c2011-06-10 03:50:41 +00003633 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003634 // inaccessible from the defaulted constructor
3635 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3636 if (BaseDtor->isDeleted())
3637 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003638 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003639 AR_accessible)
3640 return true;
3641
3642 // -- a [virtual base class] B that cannot be [copied] because overload
3643 // resolution, as applied to B's [copy] constructor, results in an
3644 // ambiguity or a function that is deleted or inaccessible from the
3645 // defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003646 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003647 if (!BaseCtor || BaseCtor->isDeleted())
3648 return true;
3649 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3650 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003651 return true;
3652 }
3653
3654 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3655 FE = RD->field_end();
3656 FI != FE; ++FI) {
3657 QualType FieldType = Context.getBaseElementType(FI->getType());
3658
3659 // -- for a copy constructor, a non-static data member of rvalue reference
3660 // type
3661 if (FieldType->isRValueReferenceType())
3662 return true;
3663
3664 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3665
3666 if (FieldRecord) {
3667 // This is an anonymous union
3668 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3669 // Anonymous unions inside unions do not variant members create
3670 if (!Union) {
3671 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3672 UE = FieldRecord->field_end();
3673 UI != UE; ++UI) {
3674 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3675 CXXRecordDecl *UnionFieldRecord =
3676 UnionFieldType->getAsCXXRecordDecl();
3677
3678 // -- a variant member with a non-trivial [copy] constructor and X
3679 // is a union-like class
3680 if (UnionFieldRecord &&
3681 !UnionFieldRecord->hasTrivialCopyConstructor())
3682 return true;
3683 }
3684 }
3685
3686 // Don't try to initalize an anonymous union
3687 continue;
3688 } else {
3689 // -- a variant member with a non-trivial [copy] constructor and X is a
3690 // union-like class
3691 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3692 return true;
3693
3694 // -- any [non-static data member] of a type with a destructor that is
3695 // deleted or inaccessible from the defaulted constructor
3696 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3697 if (FieldDtor->isDeleted())
3698 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003699 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003700 AR_accessible)
3701 return true;
3702 }
Sean Huntc530d172011-06-10 04:44:37 +00003703
3704 // -- a [non-static data member of class type (or array thereof)] B that
3705 // cannot be [copied] because overload resolution, as applied to B's
3706 // [copy] constructor, results in an ambiguity or a function that is
3707 // deleted or inaccessible from the defaulted constructor
Sean Hunt661c67a2011-06-21 23:42:56 +00003708 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3709 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003710 if (!FieldCtor || FieldCtor->isDeleted())
3711 return true;
3712 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3713 PDiag()) != AR_accessible)
3714 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00003715 }
Sean Hunt49634cf2011-05-13 06:10:58 +00003716 }
3717
3718 return false;
3719}
3720
Sean Hunt7f410192011-05-14 05:23:24 +00003721bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3722 CXXRecordDecl *RD = MD->getParent();
3723 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003724 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00003725 return false;
3726
Sean Hunt71a682f2011-05-18 03:41:58 +00003727 SourceLocation Loc = MD->getLocation();
3728
Sean Hunt7f410192011-05-14 05:23:24 +00003729 // Do access control from the constructor
3730 ContextRAII MethodContext(*this, MD);
3731
3732 bool Union = RD->isUnion();
3733
Sean Hunt661c67a2011-06-21 23:42:56 +00003734 unsigned ArgQuals =
3735 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3736 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00003737
3738 // We do this because we should never actually use an anonymous
3739 // union's constructor.
3740 if (Union && RD->isAnonymousStructOrUnion())
3741 return false;
3742
Sean Hunt7f410192011-05-14 05:23:24 +00003743 // FIXME: We should put some diagnostic logic right into this function.
3744
3745 // C++0x [class.copy]/11
3746 // A defaulted [copy] assignment operator for class X is defined as deleted
3747 // if X has:
3748
3749 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3750 BE = RD->bases_end();
3751 BI != BE; ++BI) {
3752 // We'll handle this one later
3753 if (BI->isVirtual())
3754 continue;
3755
3756 QualType BaseType = BI->getType();
3757 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3758 assert(BaseDecl && "base isn't a CXXRecordDecl");
3759
3760 // -- a [direct base class] B that cannot be [copied] because overload
3761 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003762 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00003763 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00003764 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3765 0);
3766 if (!CopyOper || CopyOper->isDeleted())
3767 return true;
3768 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00003769 return true;
3770 }
3771
3772 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3773 BE = RD->vbases_end();
3774 BI != BE; ++BI) {
3775 QualType BaseType = BI->getType();
3776 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3777 assert(BaseDecl && "base isn't a CXXRecordDecl");
3778
Sean Hunt7f410192011-05-14 05:23:24 +00003779 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00003780 // resolution, as applied to B's [copy] assignment operator, results in
3781 // an ambiguity or a function that is deleted or inaccessible from the
3782 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00003783 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3784 0);
3785 if (!CopyOper || CopyOper->isDeleted())
3786 return true;
3787 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00003788 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00003789 }
3790
3791 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3792 FE = RD->field_end();
3793 FI != FE; ++FI) {
3794 QualType FieldType = Context.getBaseElementType(FI->getType());
3795
3796 // -- a non-static data member of reference type
3797 if (FieldType->isReferenceType())
3798 return true;
3799
3800 // -- a non-static data member of const non-class type (or array thereof)
3801 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3802 return true;
3803
3804 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3805
3806 if (FieldRecord) {
3807 // This is an anonymous union
3808 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3809 // Anonymous unions inside unions do not variant members create
3810 if (!Union) {
3811 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3812 UE = FieldRecord->field_end();
3813 UI != UE; ++UI) {
3814 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3815 CXXRecordDecl *UnionFieldRecord =
3816 UnionFieldType->getAsCXXRecordDecl();
3817
3818 // -- a variant member with a non-trivial [copy] assignment operator
3819 // and X is a union-like class
3820 if (UnionFieldRecord &&
3821 !UnionFieldRecord->hasTrivialCopyAssignment())
3822 return true;
3823 }
3824 }
3825
3826 // Don't try to initalize an anonymous union
3827 continue;
3828 // -- a variant member with a non-trivial [copy] assignment operator
3829 // and X is a union-like class
3830 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3831 return true;
3832 }
Sean Hunt7f410192011-05-14 05:23:24 +00003833
Sean Hunt661c67a2011-06-21 23:42:56 +00003834 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3835 false, 0);
3836 if (!CopyOper || CopyOper->isDeleted())
3837 return false;
3838 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3839 return false;
Sean Hunt2b188082011-05-14 05:23:28 +00003840 }
Sean Hunt7f410192011-05-14 05:23:24 +00003841 }
3842
3843 return false;
3844}
3845
Sean Huntcb45a0f2011-05-12 22:46:25 +00003846bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3847 CXXRecordDecl *RD = DD->getParent();
3848 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00003849 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00003850 return false;
3851
Sean Hunt71a682f2011-05-18 03:41:58 +00003852 SourceLocation Loc = DD->getLocation();
3853
Sean Huntcb45a0f2011-05-12 22:46:25 +00003854 // Do access control from the destructor
3855 ContextRAII CtorContext(*this, DD);
3856
3857 bool Union = RD->isUnion();
3858
Sean Hunt49634cf2011-05-13 06:10:58 +00003859 // We do this because we should never actually use an anonymous
3860 // union's destructor.
3861 if (Union && RD->isAnonymousStructOrUnion())
3862 return false;
3863
Sean Huntcb45a0f2011-05-12 22:46:25 +00003864 // C++0x [class.dtor]p5
3865 // A defaulted destructor for a class X is defined as deleted if:
3866 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3867 BE = RD->bases_end();
3868 BI != BE; ++BI) {
3869 // We'll handle this one later
3870 if (BI->isVirtual())
3871 continue;
3872
3873 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3874 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3875 assert(BaseDtor && "base has no destructor");
3876
3877 // -- any direct or virtual base class has a deleted destructor or
3878 // a destructor that is inaccessible from the defaulted destructor
3879 if (BaseDtor->isDeleted())
3880 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003881 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003882 AR_accessible)
3883 return true;
3884 }
3885
3886 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3887 BE = RD->vbases_end();
3888 BI != BE; ++BI) {
3889 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3890 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3891 assert(BaseDtor && "base has no destructor");
3892
3893 // -- any direct or virtual base class has a deleted destructor or
3894 // a destructor that is inaccessible from the defaulted destructor
3895 if (BaseDtor->isDeleted())
3896 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003897 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003898 AR_accessible)
3899 return true;
3900 }
3901
3902 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3903 FE = RD->field_end();
3904 FI != FE; ++FI) {
3905 QualType FieldType = Context.getBaseElementType(FI->getType());
3906 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3907 if (FieldRecord) {
3908 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3909 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3910 UE = FieldRecord->field_end();
3911 UI != UE; ++UI) {
3912 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3913 CXXRecordDecl *UnionFieldRecord =
3914 UnionFieldType->getAsCXXRecordDecl();
3915
3916 // -- X is a union-like class that has a variant member with a non-
3917 // trivial destructor.
3918 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3919 return true;
3920 }
3921 // Technically we are supposed to do this next check unconditionally.
3922 // But that makes absolutely no sense.
3923 } else {
3924 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3925
3926 // -- any of the non-static data members has class type M (or array
3927 // thereof) and M has a deleted destructor or a destructor that is
3928 // inaccessible from the defaulted destructor
3929 if (FieldDtor->isDeleted())
3930 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003931 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003932 AR_accessible)
3933 return true;
3934
3935 // -- X is a union-like class that has a variant member with a non-
3936 // trivial destructor.
3937 if (Union && !FieldDtor->isTrivial())
3938 return true;
3939 }
3940 }
3941 }
3942
3943 if (DD->isVirtual()) {
3944 FunctionDecl *OperatorDelete = 0;
3945 DeclarationName Name =
3946 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00003947 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003948 false))
3949 return true;
3950 }
3951
3952
3953 return false;
3954}
3955
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003956/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00003957namespace {
3958 struct FindHiddenVirtualMethodData {
3959 Sema *S;
3960 CXXMethodDecl *Method;
3961 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3962 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3963 };
3964}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003965
3966/// \brief Member lookup function that determines whether a given C++
3967/// method overloads virtual methods in a base class without overriding any,
3968/// to be used with CXXRecordDecl::lookupInBases().
3969static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3970 CXXBasePath &Path,
3971 void *UserData) {
3972 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3973
3974 FindHiddenVirtualMethodData &Data
3975 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3976
3977 DeclarationName Name = Data.Method->getDeclName();
3978 assert(Name.getNameKind() == DeclarationName::Identifier);
3979
3980 bool foundSameNameMethod = false;
3981 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3982 for (Path.Decls = BaseRecord->lookup(Name);
3983 Path.Decls.first != Path.Decls.second;
3984 ++Path.Decls.first) {
3985 NamedDecl *D = *Path.Decls.first;
3986 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00003987 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003988 foundSameNameMethod = true;
3989 // Interested only in hidden virtual methods.
3990 if (!MD->isVirtual())
3991 continue;
3992 // If the method we are checking overrides a method from its base
3993 // don't warn about the other overloaded methods.
3994 if (!Data.S->IsOverload(Data.Method, MD, false))
3995 return true;
3996 // Collect the overload only if its hidden.
3997 if (!Data.OverridenAndUsingBaseMethods.count(MD))
3998 overloadedMethods.push_back(MD);
3999 }
4000 }
4001
4002 if (foundSameNameMethod)
4003 Data.OverloadedMethods.append(overloadedMethods.begin(),
4004 overloadedMethods.end());
4005 return foundSameNameMethod;
4006}
4007
4008/// \brief See if a method overloads virtual methods in a base class without
4009/// overriding any.
4010void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4011 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4012 MD->getLocation()) == Diagnostic::Ignored)
4013 return;
4014 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4015 return;
4016
4017 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4018 /*bool RecordPaths=*/false,
4019 /*bool DetectVirtual=*/false);
4020 FindHiddenVirtualMethodData Data;
4021 Data.Method = MD;
4022 Data.S = this;
4023
4024 // Keep the base methods that were overriden or introduced in the subclass
4025 // by 'using' in a set. A base method not in this set is hidden.
4026 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4027 res.first != res.second; ++res.first) {
4028 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4029 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4030 E = MD->end_overridden_methods();
4031 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004032 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004033 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4034 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004035 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004036 }
4037
4038 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4039 !Data.OverloadedMethods.empty()) {
4040 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4041 << MD << (Data.OverloadedMethods.size() > 1);
4042
4043 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4044 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4045 Diag(overloadedMD->getLocation(),
4046 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4047 }
4048 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004049}
4050
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004051void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004052 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004053 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004054 SourceLocation RBrac,
4055 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004056 if (!TagDecl)
4057 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Douglas Gregor42af25f2009-05-11 19:58:34 +00004059 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004060
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004061 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004062 // strict aliasing violation!
4063 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004064 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004065
Douglas Gregor23c94db2010-07-02 17:43:08 +00004066 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004067 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004068}
4069
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004070/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4071/// special functions, such as the default constructor, copy
4072/// constructor, or destructor, to the given C++ class (C++
4073/// [special]p1). This routine can only be executed just before the
4074/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004075void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004076 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004077 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004078
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004079 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004080 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004081
Douglas Gregora376d102010-07-02 21:50:04 +00004082 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4083 ++ASTContext::NumImplicitCopyAssignmentOperators;
4084
4085 // If we have a dynamic class, then the copy assignment operator may be
4086 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4087 // it shows up in the right place in the vtable and that we diagnose
4088 // problems with the implicit exception specification.
4089 if (ClassDecl->isDynamicClass())
4090 DeclareImplicitCopyAssignment(ClassDecl);
4091 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004092
Douglas Gregor4923aa22010-07-02 20:37:36 +00004093 if (!ClassDecl->hasUserDeclaredDestructor()) {
4094 ++ASTContext::NumImplicitDestructors;
4095
4096 // If we have a dynamic class, then the destructor may be virtual, so we
4097 // have to declare the destructor immediately. This ensures that, e.g., it
4098 // shows up in the right place in the vtable and that we diagnose problems
4099 // with the implicit exception specification.
4100 if (ClassDecl->isDynamicClass())
4101 DeclareImplicitDestructor(ClassDecl);
4102 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004103}
4104
Francois Pichet8387e2a2011-04-22 22:18:13 +00004105void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4106 if (!D)
4107 return;
4108
4109 int NumParamList = D->getNumTemplateParameterLists();
4110 for (int i = 0; i < NumParamList; i++) {
4111 TemplateParameterList* Params = D->getTemplateParameterList(i);
4112 for (TemplateParameterList::iterator Param = Params->begin(),
4113 ParamEnd = Params->end();
4114 Param != ParamEnd; ++Param) {
4115 NamedDecl *Named = cast<NamedDecl>(*Param);
4116 if (Named->getDeclName()) {
4117 S->AddDecl(Named);
4118 IdResolver.AddDecl(Named);
4119 }
4120 }
4121 }
4122}
4123
John McCalld226f652010-08-21 09:40:31 +00004124void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004125 if (!D)
4126 return;
4127
4128 TemplateParameterList *Params = 0;
4129 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4130 Params = Template->getTemplateParameters();
4131 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4132 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4133 Params = PartialSpec->getTemplateParameters();
4134 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004135 return;
4136
Douglas Gregor6569d682009-05-27 23:11:45 +00004137 for (TemplateParameterList::iterator Param = Params->begin(),
4138 ParamEnd = Params->end();
4139 Param != ParamEnd; ++Param) {
4140 NamedDecl *Named = cast<NamedDecl>(*Param);
4141 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004142 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004143 IdResolver.AddDecl(Named);
4144 }
4145 }
4146}
4147
John McCalld226f652010-08-21 09:40:31 +00004148void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004149 if (!RecordD) return;
4150 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004151 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004152 PushDeclContext(S, Record);
4153}
4154
John McCalld226f652010-08-21 09:40:31 +00004155void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004156 if (!RecordD) return;
4157 PopDeclContext();
4158}
4159
Douglas Gregor72b505b2008-12-16 21:30:33 +00004160/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4161/// parsing a top-level (non-nested) C++ class, and we are now
4162/// parsing those parts of the given Method declaration that could
4163/// not be parsed earlier (C++ [class.mem]p2), such as default
4164/// arguments. This action should enter the scope of the given
4165/// Method declaration as if we had just parsed the qualified method
4166/// name. However, it should not bring the parameters into scope;
4167/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004168void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004169}
4170
4171/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4172/// C++ method declaration. We're (re-)introducing the given
4173/// function parameter into scope for use in parsing later parts of
4174/// the method declaration. For example, we could see an
4175/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004176void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004177 if (!ParamD)
4178 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004179
John McCalld226f652010-08-21 09:40:31 +00004180 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004181
4182 // If this parameter has an unparsed default argument, clear it out
4183 // to make way for the parsed default argument.
4184 if (Param->hasUnparsedDefaultArg())
4185 Param->setDefaultArg(0);
4186
John McCalld226f652010-08-21 09:40:31 +00004187 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004188 if (Param->getDeclName())
4189 IdResolver.AddDecl(Param);
4190}
4191
4192/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4193/// processing the delayed method declaration for Method. The method
4194/// declaration is now considered finished. There may be a separate
4195/// ActOnStartOfFunctionDef action later (not necessarily
4196/// immediately!) for this method, if it was also defined inside the
4197/// class body.
John McCalld226f652010-08-21 09:40:31 +00004198void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004199 if (!MethodD)
4200 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004201
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004202 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004203
John McCalld226f652010-08-21 09:40:31 +00004204 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004205
4206 // Now that we have our default arguments, check the constructor
4207 // again. It could produce additional diagnostics or affect whether
4208 // the class has implicitly-declared destructors, among other
4209 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004210 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4211 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004212
4213 // Check the default arguments, which we may have added.
4214 if (!Method->isInvalidDecl())
4215 CheckCXXDefaultArguments(Method);
4216}
4217
Douglas Gregor42a552f2008-11-05 20:51:48 +00004218/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004219/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004220/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004221/// emit diagnostics and set the invalid bit to true. In any case, the type
4222/// will be updated to reflect a well-formed type for the constructor and
4223/// returned.
4224QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004225 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004226 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004227
4228 // C++ [class.ctor]p3:
4229 // A constructor shall not be virtual (10.3) or static (9.4). A
4230 // constructor can be invoked for a const, volatile or const
4231 // volatile object. A constructor shall not be declared const,
4232 // volatile, or const volatile (9.3.2).
4233 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004234 if (!D.isInvalidType())
4235 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4236 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4237 << SourceRange(D.getIdentifierLoc());
4238 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004239 }
John McCalld931b082010-08-26 03:08:43 +00004240 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004241 if (!D.isInvalidType())
4242 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4243 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4244 << SourceRange(D.getIdentifierLoc());
4245 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004246 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004247 }
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004249 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004250 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004251 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004252 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4253 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004254 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004255 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4256 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004257 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004258 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4259 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004260 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004261 }
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Douglas Gregorc938c162011-01-26 05:01:58 +00004263 // C++0x [class.ctor]p4:
4264 // A constructor shall not be declared with a ref-qualifier.
4265 if (FTI.hasRefQualifier()) {
4266 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4267 << FTI.RefQualifierIsLValueRef
4268 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4269 D.setInvalidType();
4270 }
4271
Douglas Gregor42a552f2008-11-05 20:51:48 +00004272 // Rebuild the function type "R" without any type qualifiers (in
4273 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004274 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004275 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004276 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4277 return R;
4278
4279 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4280 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004281 EPI.RefQualifier = RQ_None;
4282
Chris Lattner65401802009-04-25 08:28:21 +00004283 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004284 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004285}
4286
Douglas Gregor72b505b2008-12-16 21:30:33 +00004287/// CheckConstructor - Checks a fully-formed constructor for
4288/// well-formedness, issuing any diagnostics required. Returns true if
4289/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004290void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004291 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004292 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4293 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004294 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004295
4296 // C++ [class.copy]p3:
4297 // A declaration of a constructor for a class X is ill-formed if
4298 // its first parameter is of type (optionally cv-qualified) X and
4299 // either there are no other parameters or else all other
4300 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004301 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004302 ((Constructor->getNumParams() == 1) ||
4303 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004304 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4305 Constructor->getTemplateSpecializationKind()
4306 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004307 QualType ParamType = Constructor->getParamDecl(0)->getType();
4308 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4309 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004310 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004311 const char *ConstRef
4312 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4313 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004314 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004315 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004316
4317 // FIXME: Rather that making the constructor invalid, we should endeavor
4318 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004319 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004320 }
4321 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004322}
4323
John McCall15442822010-08-04 01:04:25 +00004324/// CheckDestructor - Checks a fully-formed destructor definition for
4325/// well-formedness, issuing any diagnostics required. Returns true
4326/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004327bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004328 CXXRecordDecl *RD = Destructor->getParent();
4329
4330 if (Destructor->isVirtual()) {
4331 SourceLocation Loc;
4332
4333 if (!Destructor->isImplicit())
4334 Loc = Destructor->getLocation();
4335 else
4336 Loc = RD->getLocation();
4337
4338 // If we have a virtual destructor, look up the deallocation function
4339 FunctionDecl *OperatorDelete = 0;
4340 DeclarationName Name =
4341 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004342 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004343 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004344
4345 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004346
4347 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004348 }
Anders Carlsson37909802009-11-30 21:24:50 +00004349
4350 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004351}
4352
Mike Stump1eb44332009-09-09 15:08:12 +00004353static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004354FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4355 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4356 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004357 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004358}
4359
Douglas Gregor42a552f2008-11-05 20:51:48 +00004360/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4361/// the well-formednes of the destructor declarator @p D with type @p
4362/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004363/// emit diagnostics and set the declarator to invalid. Even if this happens,
4364/// will be updated to reflect a well-formed type for the destructor and
4365/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004366QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004367 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004368 // C++ [class.dtor]p1:
4369 // [...] A typedef-name that names a class is a class-name
4370 // (7.1.3); however, a typedef-name that names a class shall not
4371 // be used as the identifier in the declarator for a destructor
4372 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004373 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004374 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004375 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004376 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004377 else if (const TemplateSpecializationType *TST =
4378 DeclaratorType->getAs<TemplateSpecializationType>())
4379 if (TST->isTypeAlias())
4380 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4381 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004382
4383 // C++ [class.dtor]p2:
4384 // A destructor is used to destroy objects of its class type. A
4385 // destructor takes no parameters, and no return type can be
4386 // specified for it (not even void). The address of a destructor
4387 // shall not be taken. A destructor shall not be static. A
4388 // destructor can be invoked for a const, volatile or const
4389 // volatile object. A destructor shall not be declared const,
4390 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004391 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004392 if (!D.isInvalidType())
4393 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4394 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004395 << SourceRange(D.getIdentifierLoc())
4396 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4397
John McCalld931b082010-08-26 03:08:43 +00004398 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004399 }
Chris Lattner65401802009-04-25 08:28:21 +00004400 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004401 // Destructors don't have return types, but the parser will
4402 // happily parse something like:
4403 //
4404 // class X {
4405 // float ~X();
4406 // };
4407 //
4408 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004409 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4410 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4411 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004412 }
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004414 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004415 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004416 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004417 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4418 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004419 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004420 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4421 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004422 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004423 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4424 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004425 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004426 }
4427
Douglas Gregorc938c162011-01-26 05:01:58 +00004428 // C++0x [class.dtor]p2:
4429 // A destructor shall not be declared with a ref-qualifier.
4430 if (FTI.hasRefQualifier()) {
4431 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4432 << FTI.RefQualifierIsLValueRef
4433 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4434 D.setInvalidType();
4435 }
4436
Douglas Gregor42a552f2008-11-05 20:51:48 +00004437 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004438 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004439 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4440
4441 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004442 FTI.freeArgs();
4443 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004444 }
4445
Mike Stump1eb44332009-09-09 15:08:12 +00004446 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004447 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004448 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004449 D.setInvalidType();
4450 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004451
4452 // Rebuild the function type "R" without any type qualifiers or
4453 // parameters (in case any of the errors above fired) and with
4454 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004455 // types.
John McCalle23cf432010-12-14 08:05:40 +00004456 if (!D.isInvalidType())
4457 return R;
4458
Douglas Gregord92ec472010-07-01 05:10:53 +00004459 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004460 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4461 EPI.Variadic = false;
4462 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004463 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004464 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004465}
4466
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004467/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4468/// well-formednes of the conversion function declarator @p D with
4469/// type @p R. If there are any errors in the declarator, this routine
4470/// will emit diagnostics and return true. Otherwise, it will return
4471/// false. Either way, the type @p R will be updated to reflect a
4472/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004473void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004474 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004475 // C++ [class.conv.fct]p1:
4476 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004477 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004478 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004479 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004480 if (!D.isInvalidType())
4481 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4482 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4483 << SourceRange(D.getIdentifierLoc());
4484 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004485 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004486 }
John McCalla3f81372010-04-13 00:04:31 +00004487
4488 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4489
Chris Lattner6e475012009-04-25 08:35:12 +00004490 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004491 // Conversion functions don't have return types, but the parser will
4492 // happily parse something like:
4493 //
4494 // class X {
4495 // float operator bool();
4496 // };
4497 //
4498 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004499 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4500 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4501 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004502 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004503 }
4504
John McCalla3f81372010-04-13 00:04:31 +00004505 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4506
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004507 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004508 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004509 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4510
4511 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004512 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004513 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004514 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004515 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004516 D.setInvalidType();
4517 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004518
John McCalla3f81372010-04-13 00:04:31 +00004519 // Diagnose "&operator bool()" and other such nonsense. This
4520 // is actually a gcc extension which we don't support.
4521 if (Proto->getResultType() != ConvType) {
4522 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4523 << Proto->getResultType();
4524 D.setInvalidType();
4525 ConvType = Proto->getResultType();
4526 }
4527
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004528 // C++ [class.conv.fct]p4:
4529 // The conversion-type-id shall not represent a function type nor
4530 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004531 if (ConvType->isArrayType()) {
4532 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4533 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004534 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004535 } else if (ConvType->isFunctionType()) {
4536 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4537 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004538 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004539 }
4540
4541 // Rebuild the function type "R" without any parameters (in case any
4542 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00004543 // return type.
John McCalle23cf432010-12-14 08:05:40 +00004544 if (D.isInvalidType())
4545 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004546
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004547 // C++0x explicit conversion operators.
4548 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00004549 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004550 diag::warn_explicit_conversion_functions)
4551 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004552}
4553
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004554/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4555/// the declaration of the given C++ conversion function. This routine
4556/// is responsible for recording the conversion function in the C++
4557/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00004558Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004559 assert(Conversion && "Expected to receive a conversion function declaration");
4560
Douglas Gregor9d350972008-12-12 08:25:50 +00004561 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004562
4563 // Make sure we aren't redeclaring the conversion function.
4564 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004565
4566 // C++ [class.conv.fct]p1:
4567 // [...] A conversion function is never used to convert a
4568 // (possibly cv-qualified) object to the (possibly cv-qualified)
4569 // same object type (or a reference to it), to a (possibly
4570 // cv-qualified) base class of that type (or a reference to it),
4571 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004572 // FIXME: Suppress this warning if the conversion function ends up being a
4573 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004574 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004575 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004576 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004577 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004578 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4579 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004580 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004581 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004582 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4583 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004584 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004585 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004586 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004587 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004588 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004589 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004590 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004591 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004592 }
4593
Douglas Gregore80622f2010-09-29 04:25:11 +00004594 if (FunctionTemplateDecl *ConversionTemplate
4595 = Conversion->getDescribedFunctionTemplate())
4596 return ConversionTemplate;
4597
John McCalld226f652010-08-21 09:40:31 +00004598 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004599}
4600
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004601//===----------------------------------------------------------------------===//
4602// Namespace Handling
4603//===----------------------------------------------------------------------===//
4604
John McCallea318642010-08-26 09:15:37 +00004605
4606
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004607/// ActOnStartNamespaceDef - This is called at the start of a namespace
4608/// definition.
John McCalld226f652010-08-21 09:40:31 +00004609Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004610 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004611 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004612 SourceLocation IdentLoc,
4613 IdentifierInfo *II,
4614 SourceLocation LBrace,
4615 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004616 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4617 // For anonymous namespace, take the location of the left brace.
4618 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004619 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004620 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004621 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004622
4623 Scope *DeclRegionScope = NamespcScope->getParent();
4624
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004625 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4626
John McCall90f14502010-12-10 02:59:44 +00004627 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4628 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004629
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004630 if (II) {
4631 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004632 // The identifier in an original-namespace-definition shall not
4633 // have been previously defined in the declarative region in
4634 // which the original-namespace-definition appears. The
4635 // identifier in an original-namespace-definition is the name of
4636 // the namespace. Subsequently in that declarative region, it is
4637 // treated as an original-namespace-name.
4638 //
4639 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004640 // look through using directives, just look for any ordinary names.
4641
4642 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4643 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4644 Decl::IDNS_Namespace;
4645 NamedDecl *PrevDecl = 0;
4646 for (DeclContext::lookup_result R
4647 = CurContext->getRedeclContext()->lookup(II);
4648 R.first != R.second; ++R.first) {
4649 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4650 PrevDecl = *R.first;
4651 break;
4652 }
4653 }
4654
Douglas Gregor44b43212008-12-11 16:49:14 +00004655 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4656 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004657 if (Namespc->isInline() != OrigNS->isInline()) {
4658 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004659 if (OrigNS->isInline()) {
4660 // The user probably just forgot the 'inline', so suggest that it
4661 // be added back.
4662 Diag(Namespc->getLocation(),
4663 diag::warn_inline_namespace_reopened_noninline)
4664 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4665 } else {
4666 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4667 << Namespc->isInline();
4668 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004669 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004670
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004671 // Recover by ignoring the new namespace's inline status.
4672 Namespc->setInline(OrigNS->isInline());
4673 }
4674
Douglas Gregor44b43212008-12-11 16:49:14 +00004675 // Attach this namespace decl to the chain of extended namespace
4676 // definitions.
4677 OrigNS->setNextNamespace(Namespc);
4678 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004679
Mike Stump1eb44332009-09-09 15:08:12 +00004680 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004681 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004682 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004683 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004684 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004685 } else if (PrevDecl) {
4686 // This is an invalid name redefinition.
4687 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4688 << Namespc->getDeclName();
4689 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4690 Namespc->setInvalidDecl();
4691 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004692 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004693 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004694 // This is the first "real" definition of the namespace "std", so update
4695 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004696 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004697 // We had already defined a dummy namespace "std". Link this new
4698 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004699 StdNS->setNextNamespace(Namespc);
4700 StdNS->setLocation(IdentLoc);
4701 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004702 }
4703
4704 // Make our StdNamespace cache point at the first real definition of the
4705 // "std" namespace.
4706 StdNamespace = Namespc;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004707
4708 // Add this instance of "std" to the set of known namespaces
4709 KnownNamespaces[Namespc] = false;
4710 } else if (!Namespc->isInline()) {
4711 // Since this is an "original" namespace, add it to the known set of
4712 // namespaces if it is not an inline namespace.
4713 KnownNamespaces[Namespc] = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004714 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004715
4716 PushOnScopeChains(Namespc, DeclRegionScope);
4717 } else {
John McCall9aeed322009-10-01 00:25:31 +00004718 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004719 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004720
4721 // Link the anonymous namespace into its parent.
4722 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004723 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004724 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4725 PrevDecl = TU->getAnonymousNamespace();
4726 TU->setAnonymousNamespace(Namespc);
4727 } else {
4728 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4729 PrevDecl = ND->getAnonymousNamespace();
4730 ND->setAnonymousNamespace(Namespc);
4731 }
4732
4733 // Link the anonymous namespace with its previous declaration.
4734 if (PrevDecl) {
4735 assert(PrevDecl->isAnonymousNamespace());
4736 assert(!PrevDecl->getNextNamespace());
4737 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4738 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004739
4740 if (Namespc->isInline() != PrevDecl->isInline()) {
4741 // inline-ness must match
4742 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4743 << Namespc->isInline();
4744 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4745 Namespc->setInvalidDecl();
4746 // Recover by ignoring the new namespace's inline status.
4747 Namespc->setInline(PrevDecl->isInline());
4748 }
John McCall5fdd7642009-12-16 02:06:49 +00004749 }
John McCall9aeed322009-10-01 00:25:31 +00004750
Douglas Gregora4181472010-03-24 00:46:35 +00004751 CurContext->addDecl(Namespc);
4752
John McCall9aeed322009-10-01 00:25:31 +00004753 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4754 // behaves as if it were replaced by
4755 // namespace unique { /* empty body */ }
4756 // using namespace unique;
4757 // namespace unique { namespace-body }
4758 // where all occurrences of 'unique' in a translation unit are
4759 // replaced by the same identifier and this identifier differs
4760 // from all other identifiers in the entire program.
4761
4762 // We just create the namespace with an empty name and then add an
4763 // implicit using declaration, just like the standard suggests.
4764 //
4765 // CodeGen enforces the "universally unique" aspect by giving all
4766 // declarations semantically contained within an anonymous
4767 // namespace internal linkage.
4768
John McCall5fdd7642009-12-16 02:06:49 +00004769 if (!PrevDecl) {
4770 UsingDirectiveDecl* UD
4771 = UsingDirectiveDecl::Create(Context, CurContext,
4772 /* 'using' */ LBrace,
4773 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004774 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004775 /* identifier */ SourceLocation(),
4776 Namespc,
4777 /* Ancestor */ CurContext);
4778 UD->setImplicit();
4779 CurContext->addDecl(UD);
4780 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004781 }
4782
4783 // Although we could have an invalid decl (i.e. the namespace name is a
4784 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004785 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4786 // for the namespace has the declarations that showed up in that particular
4787 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004788 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004789 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004790}
4791
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004792/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4793/// is a namespace alias, returns the namespace it points to.
4794static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4795 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4796 return AD->getNamespace();
4797 return dyn_cast_or_null<NamespaceDecl>(D);
4798}
4799
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004800/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4801/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004802void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004803 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4804 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004805 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004806 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004807 if (Namespc->hasAttr<VisibilityAttr>())
4808 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004809}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004810
John McCall384aff82010-08-25 07:42:41 +00004811CXXRecordDecl *Sema::getStdBadAlloc() const {
4812 return cast_or_null<CXXRecordDecl>(
4813 StdBadAlloc.get(Context.getExternalSource()));
4814}
4815
4816NamespaceDecl *Sema::getStdNamespace() const {
4817 return cast_or_null<NamespaceDecl>(
4818 StdNamespace.get(Context.getExternalSource()));
4819}
4820
Douglas Gregor66992202010-06-29 17:53:46 +00004821/// \brief Retrieve the special "std" namespace, which may require us to
4822/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004823NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004824 if (!StdNamespace) {
4825 // The "std" namespace has not yet been defined, so build one implicitly.
4826 StdNamespace = NamespaceDecl::Create(Context,
4827 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004828 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004829 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004830 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004831 }
4832
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004833 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004834}
4835
Douglas Gregor9172aa62011-03-26 22:25:30 +00004836/// \brief Determine whether a using statement is in a context where it will be
4837/// apply in all contexts.
4838static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4839 switch (CurContext->getDeclKind()) {
4840 case Decl::TranslationUnit:
4841 return true;
4842 case Decl::LinkageSpec:
4843 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4844 default:
4845 return false;
4846 }
4847}
4848
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004849static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
4850 CXXScopeSpec &SS,
4851 SourceLocation IdentLoc,
4852 IdentifierInfo *Ident) {
4853 R.clear();
4854 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
4855 R.getLookupKind(), Sc, &SS, NULL,
4856 false, S.CTC_NoKeywords, NULL)) {
4857 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
4858 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
4859 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
4860 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
4861 if (DeclContext *DC = S.computeDeclContext(SS, false))
4862 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
4863 << Ident << DC << CorrectedQuotedStr << SS.getRange()
4864 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4865 else
4866 S.Diag(IdentLoc, diag::err_using_directive_suggest)
4867 << Ident << CorrectedQuotedStr
4868 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4869
4870 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
4871 diag::note_namespace_defined_here) << CorrectedQuotedStr;
4872
4873 Ident = Corrected.getCorrectionAsIdentifierInfo();
4874 R.addDecl(Corrected.getCorrectionDecl());
4875 return true;
4876 }
4877 R.setLookupName(Ident);
4878 }
4879 return false;
4880}
4881
John McCalld226f652010-08-21 09:40:31 +00004882Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004883 SourceLocation UsingLoc,
4884 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004885 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004886 SourceLocation IdentLoc,
4887 IdentifierInfo *NamespcName,
4888 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004889 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4890 assert(NamespcName && "Invalid NamespcName.");
4891 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004892
4893 // This can only happen along a recovery path.
4894 while (S->getFlags() & Scope::TemplateParamScope)
4895 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004896 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004897
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004898 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004899 NestedNameSpecifier *Qualifier = 0;
4900 if (SS.isSet())
4901 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4902
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004903 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004904 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4905 LookupParsedName(R, S, &SS);
4906 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004907 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004908
Douglas Gregor66992202010-06-29 17:53:46 +00004909 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004910 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00004911 // Allow "using namespace std;" or "using namespace ::std;" even if
4912 // "std" hasn't been defined yet, for GCC compatibility.
4913 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4914 NamespcName->isStr("std")) {
4915 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004916 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004917 R.resolveKind();
4918 }
4919 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00004920 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00004921 }
4922
John McCallf36e02d2009-10-09 21:13:30 +00004923 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004924 NamedDecl *Named = R.getFoundDecl();
4925 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4926 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004927 // C++ [namespace.udir]p1:
4928 // A using-directive specifies that the names in the nominated
4929 // namespace can be used in the scope in which the
4930 // using-directive appears after the using-directive. During
4931 // unqualified name lookup (3.4.1), the names appear as if they
4932 // were declared in the nearest enclosing namespace which
4933 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00004934 // namespace. [Note: in this context, "contains" means "contains
4935 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004936
4937 // Find enclosing context containing both using-directive and
4938 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004939 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004940 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4941 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4942 CommonAncestor = CommonAncestor->getParent();
4943
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004944 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00004945 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004946 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004947
Douglas Gregor9172aa62011-03-26 22:25:30 +00004948 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00004949 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00004950 Diag(IdentLoc, diag::warn_using_directive_in_header);
4951 }
4952
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004953 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004954 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00004955 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00004956 }
4957
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004958 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00004959 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004960}
4961
4962void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4963 // If scope has associated entity, then using directive is at namespace
4964 // or translation unit scope. We add UsingDirectiveDecls, into
4965 // it's lookup structure.
4966 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004967 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004968 else
4969 // Otherwise it is block-sope. using-directives will affect lookup
4970 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00004971 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00004972}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004973
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004974
John McCalld226f652010-08-21 09:40:31 +00004975Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00004976 AccessSpecifier AS,
4977 bool HasUsingKeyword,
4978 SourceLocation UsingLoc,
4979 CXXScopeSpec &SS,
4980 UnqualifiedId &Name,
4981 AttributeList *AttrList,
4982 bool IsTypeName,
4983 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004984 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00004985
Douglas Gregor12c118a2009-11-04 16:30:06 +00004986 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00004987 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004988 case UnqualifiedId::IK_Identifier:
4989 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00004990 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00004991 case UnqualifiedId::IK_ConversionFunctionId:
4992 break;
4993
4994 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00004995 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00004996 // C++0x inherited constructors.
4997 if (getLangOptions().CPlusPlus0x) break;
4998
Douglas Gregor12c118a2009-11-04 16:30:06 +00004999 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5000 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005001 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005002
5003 case UnqualifiedId::IK_DestructorName:
5004 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5005 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005006 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005007
5008 case UnqualifiedId::IK_TemplateId:
5009 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5010 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005011 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005012 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005013
5014 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5015 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005016 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005017 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005018
John McCall60fa3cf2009-12-11 02:10:03 +00005019 // Warn about using declarations.
5020 // TODO: store that the declaration was written without 'using' and
5021 // talk about access decls instead of using decls in the
5022 // diagnostics.
5023 if (!HasUsingKeyword) {
5024 UsingLoc = Name.getSourceRange().getBegin();
5025
5026 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005027 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005028 }
5029
Douglas Gregor56c04582010-12-16 00:46:58 +00005030 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5031 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5032 return 0;
5033
John McCall9488ea12009-11-17 05:59:44 +00005034 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005035 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005036 /* IsInstantiation */ false,
5037 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005038 if (UD)
5039 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005040
John McCalld226f652010-08-21 09:40:31 +00005041 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005042}
5043
Douglas Gregor09acc982010-07-07 23:08:52 +00005044/// \brief Determine whether a using declaration considers the given
5045/// declarations as "equivalent", e.g., if they are redeclarations of
5046/// the same entity or are both typedefs of the same type.
5047static bool
5048IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5049 bool &SuppressRedeclaration) {
5050 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5051 SuppressRedeclaration = false;
5052 return true;
5053 }
5054
Richard Smith162e1c12011-04-15 14:24:37 +00005055 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5056 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005057 SuppressRedeclaration = true;
5058 return Context.hasSameType(TD1->getUnderlyingType(),
5059 TD2->getUnderlyingType());
5060 }
5061
5062 return false;
5063}
5064
5065
John McCall9f54ad42009-12-10 09:41:52 +00005066/// Determines whether to create a using shadow decl for a particular
5067/// decl, given the set of decls existing prior to this using lookup.
5068bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5069 const LookupResult &Previous) {
5070 // Diagnose finding a decl which is not from a base class of the
5071 // current class. We do this now because there are cases where this
5072 // function will silently decide not to build a shadow decl, which
5073 // will pre-empt further diagnostics.
5074 //
5075 // We don't need to do this in C++0x because we do the check once on
5076 // the qualifier.
5077 //
5078 // FIXME: diagnose the following if we care enough:
5079 // struct A { int foo; };
5080 // struct B : A { using A::foo; };
5081 // template <class T> struct C : A {};
5082 // template <class T> struct D : C<T> { using B::foo; } // <---
5083 // This is invalid (during instantiation) in C++03 because B::foo
5084 // resolves to the using decl in B, which is not a base class of D<T>.
5085 // We can't diagnose it immediately because C<T> is an unknown
5086 // specialization. The UsingShadowDecl in D<T> then points directly
5087 // to A::foo, which will look well-formed when we instantiate.
5088 // The right solution is to not collapse the shadow-decl chain.
5089 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5090 DeclContext *OrigDC = Orig->getDeclContext();
5091
5092 // Handle enums and anonymous structs.
5093 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5094 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5095 while (OrigRec->isAnonymousStructOrUnion())
5096 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5097
5098 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5099 if (OrigDC == CurContext) {
5100 Diag(Using->getLocation(),
5101 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005102 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005103 Diag(Orig->getLocation(), diag::note_using_decl_target);
5104 return true;
5105 }
5106
Douglas Gregordc355712011-02-25 00:36:19 +00005107 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005108 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005109 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005110 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005111 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005112 Diag(Orig->getLocation(), diag::note_using_decl_target);
5113 return true;
5114 }
5115 }
5116
5117 if (Previous.empty()) return false;
5118
5119 NamedDecl *Target = Orig;
5120 if (isa<UsingShadowDecl>(Target))
5121 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5122
John McCalld7533ec2009-12-11 02:33:26 +00005123 // If the target happens to be one of the previous declarations, we
5124 // don't have a conflict.
5125 //
5126 // FIXME: but we might be increasing its access, in which case we
5127 // should redeclare it.
5128 NamedDecl *NonTag = 0, *Tag = 0;
5129 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5130 I != E; ++I) {
5131 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005132 bool Result;
5133 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5134 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005135
5136 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5137 }
5138
John McCall9f54ad42009-12-10 09:41:52 +00005139 if (Target->isFunctionOrFunctionTemplate()) {
5140 FunctionDecl *FD;
5141 if (isa<FunctionTemplateDecl>(Target))
5142 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5143 else
5144 FD = cast<FunctionDecl>(Target);
5145
5146 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005147 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005148 case Ovl_Overload:
5149 return false;
5150
5151 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005152 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005153 break;
5154
5155 // We found a decl with the exact signature.
5156 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005157 // If we're in a record, we want to hide the target, so we
5158 // return true (without a diagnostic) to tell the caller not to
5159 // build a shadow decl.
5160 if (CurContext->isRecord())
5161 return true;
5162
5163 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005164 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005165 break;
5166 }
5167
5168 Diag(Target->getLocation(), diag::note_using_decl_target);
5169 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5170 return true;
5171 }
5172
5173 // Target is not a function.
5174
John McCall9f54ad42009-12-10 09:41:52 +00005175 if (isa<TagDecl>(Target)) {
5176 // No conflict between a tag and a non-tag.
5177 if (!Tag) return false;
5178
John McCall41ce66f2009-12-10 19:51:03 +00005179 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005180 Diag(Target->getLocation(), diag::note_using_decl_target);
5181 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5182 return true;
5183 }
5184
5185 // No conflict between a tag and a non-tag.
5186 if (!NonTag) return false;
5187
John McCall41ce66f2009-12-10 19:51:03 +00005188 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005189 Diag(Target->getLocation(), diag::note_using_decl_target);
5190 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5191 return true;
5192}
5193
John McCall9488ea12009-11-17 05:59:44 +00005194/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005195UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005196 UsingDecl *UD,
5197 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005198
5199 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005200 NamedDecl *Target = Orig;
5201 if (isa<UsingShadowDecl>(Target)) {
5202 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5203 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005204 }
5205
5206 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005207 = UsingShadowDecl::Create(Context, CurContext,
5208 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005209 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005210
5211 Shadow->setAccess(UD->getAccess());
5212 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5213 Shadow->setInvalidDecl();
5214
John McCall9488ea12009-11-17 05:59:44 +00005215 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005216 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005217 else
John McCall604e7f12009-12-08 07:46:18 +00005218 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005219
John McCall604e7f12009-12-08 07:46:18 +00005220
John McCall9f54ad42009-12-10 09:41:52 +00005221 return Shadow;
5222}
John McCall604e7f12009-12-08 07:46:18 +00005223
John McCall9f54ad42009-12-10 09:41:52 +00005224/// Hides a using shadow declaration. This is required by the current
5225/// using-decl implementation when a resolvable using declaration in a
5226/// class is followed by a declaration which would hide or override
5227/// one or more of the using decl's targets; for example:
5228///
5229/// struct Base { void foo(int); };
5230/// struct Derived : Base {
5231/// using Base::foo;
5232/// void foo(int);
5233/// };
5234///
5235/// The governing language is C++03 [namespace.udecl]p12:
5236///
5237/// When a using-declaration brings names from a base class into a
5238/// derived class scope, member functions in the derived class
5239/// override and/or hide member functions with the same name and
5240/// parameter types in a base class (rather than conflicting).
5241///
5242/// There are two ways to implement this:
5243/// (1) optimistically create shadow decls when they're not hidden
5244/// by existing declarations, or
5245/// (2) don't create any shadow decls (or at least don't make them
5246/// visible) until we've fully parsed/instantiated the class.
5247/// The problem with (1) is that we might have to retroactively remove
5248/// a shadow decl, which requires several O(n) operations because the
5249/// decl structures are (very reasonably) not designed for removal.
5250/// (2) avoids this but is very fiddly and phase-dependent.
5251void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005252 if (Shadow->getDeclName().getNameKind() ==
5253 DeclarationName::CXXConversionFunctionName)
5254 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5255
John McCall9f54ad42009-12-10 09:41:52 +00005256 // Remove it from the DeclContext...
5257 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005258
John McCall9f54ad42009-12-10 09:41:52 +00005259 // ...and the scope, if applicable...
5260 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005261 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005262 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005263 }
5264
John McCall9f54ad42009-12-10 09:41:52 +00005265 // ...and the using decl.
5266 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5267
5268 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005269 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005270}
5271
John McCall7ba107a2009-11-18 02:36:19 +00005272/// Builds a using declaration.
5273///
5274/// \param IsInstantiation - Whether this call arises from an
5275/// instantiation of an unresolved using declaration. We treat
5276/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005277NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5278 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005279 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005280 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005281 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005282 bool IsInstantiation,
5283 bool IsTypeName,
5284 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005285 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005286 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005287 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005288
Anders Carlsson550b14b2009-08-28 05:49:21 +00005289 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005290
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005291 if (SS.isEmpty()) {
5292 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005293 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005294 }
Mike Stump1eb44332009-09-09 15:08:12 +00005295
John McCall9f54ad42009-12-10 09:41:52 +00005296 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005297 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005298 ForRedeclaration);
5299 Previous.setHideTags(false);
5300 if (S) {
5301 LookupName(Previous, S);
5302
5303 // It is really dumb that we have to do this.
5304 LookupResult::Filter F = Previous.makeFilter();
5305 while (F.hasNext()) {
5306 NamedDecl *D = F.next();
5307 if (!isDeclInScope(D, CurContext, S))
5308 F.erase();
5309 }
5310 F.done();
5311 } else {
5312 assert(IsInstantiation && "no scope in non-instantiation");
5313 assert(CurContext->isRecord() && "scope not record in instantiation");
5314 LookupQualifiedName(Previous, CurContext);
5315 }
5316
John McCall9f54ad42009-12-10 09:41:52 +00005317 // Check for invalid redeclarations.
5318 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5319 return 0;
5320
5321 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005322 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5323 return 0;
5324
John McCallaf8e6ed2009-11-12 03:15:40 +00005325 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005326 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005327 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005328 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005329 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005330 // FIXME: not all declaration name kinds are legal here
5331 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5332 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005333 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005334 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005335 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005336 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5337 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005338 }
John McCalled976492009-12-04 22:46:56 +00005339 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005340 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5341 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005342 }
John McCalled976492009-12-04 22:46:56 +00005343 D->setAccess(AS);
5344 CurContext->addDecl(D);
5345
5346 if (!LookupContext) return D;
5347 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005348
John McCall77bb1aa2010-05-01 00:40:08 +00005349 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005350 UD->setInvalidDecl();
5351 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005352 }
5353
Sebastian Redlf677ea32011-02-05 19:23:19 +00005354 // Constructor inheriting using decls get special treatment.
5355 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005356 if (CheckInheritedConstructorUsingDecl(UD))
5357 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005358 return UD;
5359 }
5360
5361 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005362
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005363 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005364 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005365
John McCall604e7f12009-12-08 07:46:18 +00005366 // Unlike most lookups, we don't always want to hide tag
5367 // declarations: tag names are visible through the using declaration
5368 // even if hidden by ordinary names, *except* in a dependent context
5369 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005370 if (!IsInstantiation)
5371 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005372
John McCalla24dc2e2009-11-17 02:14:36 +00005373 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005374
John McCallf36e02d2009-10-09 21:13:30 +00005375 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005376 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005377 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005378 UD->setInvalidDecl();
5379 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005380 }
5381
John McCalled976492009-12-04 22:46:56 +00005382 if (R.isAmbiguous()) {
5383 UD->setInvalidDecl();
5384 return UD;
5385 }
Mike Stump1eb44332009-09-09 15:08:12 +00005386
John McCall7ba107a2009-11-18 02:36:19 +00005387 if (IsTypeName) {
5388 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005389 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005390 Diag(IdentLoc, diag::err_using_typename_non_type);
5391 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5392 Diag((*I)->getUnderlyingDecl()->getLocation(),
5393 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005394 UD->setInvalidDecl();
5395 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005396 }
5397 } else {
5398 // If we asked for a non-typename and we got a type, error out,
5399 // but only if this is an instantiation of an unresolved using
5400 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005401 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005402 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5403 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005404 UD->setInvalidDecl();
5405 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005406 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005407 }
5408
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005409 // C++0x N2914 [namespace.udecl]p6:
5410 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005411 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005412 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5413 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005414 UD->setInvalidDecl();
5415 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005416 }
Mike Stump1eb44332009-09-09 15:08:12 +00005417
John McCall9f54ad42009-12-10 09:41:52 +00005418 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5419 if (!CheckUsingShadowDecl(UD, *I, Previous))
5420 BuildUsingShadowDecl(S, UD, *I);
5421 }
John McCall9488ea12009-11-17 05:59:44 +00005422
5423 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005424}
5425
Sebastian Redlf677ea32011-02-05 19:23:19 +00005426/// Additional checks for a using declaration referring to a constructor name.
5427bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5428 if (UD->isTypeName()) {
5429 // FIXME: Cannot specify typename when specifying constructor
5430 return true;
5431 }
5432
Douglas Gregordc355712011-02-25 00:36:19 +00005433 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005434 assert(SourceType &&
5435 "Using decl naming constructor doesn't have type in scope spec.");
5436 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5437
5438 // Check whether the named type is a direct base class.
5439 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5440 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5441 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5442 BaseIt != BaseE; ++BaseIt) {
5443 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5444 if (CanonicalSourceType == BaseType)
5445 break;
5446 }
5447
5448 if (BaseIt == BaseE) {
5449 // Did not find SourceType in the bases.
5450 Diag(UD->getUsingLocation(),
5451 diag::err_using_decl_constructor_not_in_direct_base)
5452 << UD->getNameInfo().getSourceRange()
5453 << QualType(SourceType, 0) << TargetClass;
5454 return true;
5455 }
5456
5457 BaseIt->setInheritConstructors();
5458
5459 return false;
5460}
5461
John McCall9f54ad42009-12-10 09:41:52 +00005462/// Checks that the given using declaration is not an invalid
5463/// redeclaration. Note that this is checking only for the using decl
5464/// itself, not for any ill-formedness among the UsingShadowDecls.
5465bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5466 bool isTypeName,
5467 const CXXScopeSpec &SS,
5468 SourceLocation NameLoc,
5469 const LookupResult &Prev) {
5470 // C++03 [namespace.udecl]p8:
5471 // C++0x [namespace.udecl]p10:
5472 // A using-declaration is a declaration and can therefore be used
5473 // repeatedly where (and only where) multiple declarations are
5474 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005475 //
John McCall8a726212010-11-29 18:01:58 +00005476 // That's in non-member contexts.
5477 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005478 return false;
5479
5480 NestedNameSpecifier *Qual
5481 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5482
5483 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5484 NamedDecl *D = *I;
5485
5486 bool DTypename;
5487 NestedNameSpecifier *DQual;
5488 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5489 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00005490 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005491 } else if (UnresolvedUsingValueDecl *UD
5492 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5493 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00005494 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005495 } else if (UnresolvedUsingTypenameDecl *UD
5496 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5497 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00005498 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005499 } else continue;
5500
5501 // using decls differ if one says 'typename' and the other doesn't.
5502 // FIXME: non-dependent using decls?
5503 if (isTypeName != DTypename) continue;
5504
5505 // using decls differ if they name different scopes (but note that
5506 // template instantiation can cause this check to trigger when it
5507 // didn't before instantiation).
5508 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5509 Context.getCanonicalNestedNameSpecifier(DQual))
5510 continue;
5511
5512 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00005513 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00005514 return true;
5515 }
5516
5517 return false;
5518}
5519
John McCall604e7f12009-12-08 07:46:18 +00005520
John McCalled976492009-12-04 22:46:56 +00005521/// Checks that the given nested-name qualifier used in a using decl
5522/// in the current context is appropriately related to the current
5523/// scope. If an error is found, diagnoses it and returns true.
5524bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5525 const CXXScopeSpec &SS,
5526 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00005527 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005528
John McCall604e7f12009-12-08 07:46:18 +00005529 if (!CurContext->isRecord()) {
5530 // C++03 [namespace.udecl]p3:
5531 // C++0x [namespace.udecl]p8:
5532 // A using-declaration for a class member shall be a member-declaration.
5533
5534 // If we weren't able to compute a valid scope, it must be a
5535 // dependent class scope.
5536 if (!NamedContext || NamedContext->isRecord()) {
5537 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5538 << SS.getRange();
5539 return true;
5540 }
5541
5542 // Otherwise, everything is known to be fine.
5543 return false;
5544 }
5545
5546 // The current scope is a record.
5547
5548 // If the named context is dependent, we can't decide much.
5549 if (!NamedContext) {
5550 // FIXME: in C++0x, we can diagnose if we can prove that the
5551 // nested-name-specifier does not refer to a base class, which is
5552 // still possible in some cases.
5553
5554 // Otherwise we have to conservatively report that things might be
5555 // okay.
5556 return false;
5557 }
5558
5559 if (!NamedContext->isRecord()) {
5560 // Ideally this would point at the last name in the specifier,
5561 // but we don't have that level of source info.
5562 Diag(SS.getRange().getBegin(),
5563 diag::err_using_decl_nested_name_specifier_is_not_class)
5564 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5565 return true;
5566 }
5567
Douglas Gregor6fb07292010-12-21 07:41:49 +00005568 if (!NamedContext->isDependentContext() &&
5569 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5570 return true;
5571
John McCall604e7f12009-12-08 07:46:18 +00005572 if (getLangOptions().CPlusPlus0x) {
5573 // C++0x [namespace.udecl]p3:
5574 // In a using-declaration used as a member-declaration, the
5575 // nested-name-specifier shall name a base class of the class
5576 // being defined.
5577
5578 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5579 cast<CXXRecordDecl>(NamedContext))) {
5580 if (CurContext == NamedContext) {
5581 Diag(NameLoc,
5582 diag::err_using_decl_nested_name_specifier_is_current_class)
5583 << SS.getRange();
5584 return true;
5585 }
5586
5587 Diag(SS.getRange().getBegin(),
5588 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5589 << (NestedNameSpecifier*) SS.getScopeRep()
5590 << cast<CXXRecordDecl>(CurContext)
5591 << SS.getRange();
5592 return true;
5593 }
5594
5595 return false;
5596 }
5597
5598 // C++03 [namespace.udecl]p4:
5599 // A using-declaration used as a member-declaration shall refer
5600 // to a member of a base class of the class being defined [etc.].
5601
5602 // Salient point: SS doesn't have to name a base class as long as
5603 // lookup only finds members from base classes. Therefore we can
5604 // diagnose here only if we can prove that that can't happen,
5605 // i.e. if the class hierarchies provably don't intersect.
5606
5607 // TODO: it would be nice if "definitely valid" results were cached
5608 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5609 // need to be repeated.
5610
5611 struct UserData {
5612 llvm::DenseSet<const CXXRecordDecl*> Bases;
5613
5614 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5615 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5616 Data->Bases.insert(Base);
5617 return true;
5618 }
5619
5620 bool hasDependentBases(const CXXRecordDecl *Class) {
5621 return !Class->forallBases(collect, this);
5622 }
5623
5624 /// Returns true if the base is dependent or is one of the
5625 /// accumulated base classes.
5626 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5627 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5628 return !Data->Bases.count(Base);
5629 }
5630
5631 bool mightShareBases(const CXXRecordDecl *Class) {
5632 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5633 }
5634 };
5635
5636 UserData Data;
5637
5638 // Returns false if we find a dependent base.
5639 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5640 return false;
5641
5642 // Returns false if the class has a dependent base or if it or one
5643 // of its bases is present in the base set of the current context.
5644 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5645 return false;
5646
5647 Diag(SS.getRange().getBegin(),
5648 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5649 << (NestedNameSpecifier*) SS.getScopeRep()
5650 << cast<CXXRecordDecl>(CurContext)
5651 << SS.getRange();
5652
5653 return true;
John McCalled976492009-12-04 22:46:56 +00005654}
5655
Richard Smith162e1c12011-04-15 14:24:37 +00005656Decl *Sema::ActOnAliasDeclaration(Scope *S,
5657 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005658 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005659 SourceLocation UsingLoc,
5660 UnqualifiedId &Name,
5661 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005662 // Skip up to the relevant declaration scope.
5663 while (S->getFlags() & Scope::TemplateParamScope)
5664 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005665 assert((S->getFlags() & Scope::DeclScope) &&
5666 "got alias-declaration outside of declaration scope");
5667
5668 if (Type.isInvalid())
5669 return 0;
5670
5671 bool Invalid = false;
5672 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5673 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005674 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005675
5676 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5677 return 0;
5678
5679 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005680 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005681 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005682 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5683 TInfo->getTypeLoc().getBeginLoc());
5684 }
Richard Smith162e1c12011-04-15 14:24:37 +00005685
5686 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5687 LookupName(Previous, S);
5688
5689 // Warn about shadowing the name of a template parameter.
5690 if (Previous.isSingleResult() &&
5691 Previous.getFoundDecl()->isTemplateParameter()) {
5692 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5693 Previous.getFoundDecl()))
5694 Invalid = true;
5695 Previous.clear();
5696 }
5697
5698 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5699 "name in alias declaration must be an identifier");
5700 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5701 Name.StartLocation,
5702 Name.Identifier, TInfo);
5703
5704 NewTD->setAccess(AS);
5705
5706 if (Invalid)
5707 NewTD->setInvalidDecl();
5708
Richard Smith3e4c6c42011-05-05 21:57:07 +00005709 CheckTypedefForVariablyModifiedType(S, NewTD);
5710 Invalid |= NewTD->isInvalidDecl();
5711
Richard Smith162e1c12011-04-15 14:24:37 +00005712 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005713
5714 NamedDecl *NewND;
5715 if (TemplateParamLists.size()) {
5716 TypeAliasTemplateDecl *OldDecl = 0;
5717 TemplateParameterList *OldTemplateParams = 0;
5718
5719 if (TemplateParamLists.size() != 1) {
5720 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5721 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5722 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5723 }
5724 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5725
5726 // Only consider previous declarations in the same scope.
5727 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5728 /*ExplicitInstantiationOrSpecialization*/false);
5729 if (!Previous.empty()) {
5730 Redeclaration = true;
5731
5732 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5733 if (!OldDecl && !Invalid) {
5734 Diag(UsingLoc, diag::err_redefinition_different_kind)
5735 << Name.Identifier;
5736
5737 NamedDecl *OldD = Previous.getRepresentativeDecl();
5738 if (OldD->getLocation().isValid())
5739 Diag(OldD->getLocation(), diag::note_previous_definition);
5740
5741 Invalid = true;
5742 }
5743
5744 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5745 if (TemplateParameterListsAreEqual(TemplateParams,
5746 OldDecl->getTemplateParameters(),
5747 /*Complain=*/true,
5748 TPL_TemplateMatch))
5749 OldTemplateParams = OldDecl->getTemplateParameters();
5750 else
5751 Invalid = true;
5752
5753 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5754 if (!Invalid &&
5755 !Context.hasSameType(OldTD->getUnderlyingType(),
5756 NewTD->getUnderlyingType())) {
5757 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5758 // but we can't reasonably accept it.
5759 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5760 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5761 if (OldTD->getLocation().isValid())
5762 Diag(OldTD->getLocation(), diag::note_previous_definition);
5763 Invalid = true;
5764 }
5765 }
5766 }
5767
5768 // Merge any previous default template arguments into our parameters,
5769 // and check the parameter list.
5770 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5771 TPC_TypeAliasTemplate))
5772 return 0;
5773
5774 TypeAliasTemplateDecl *NewDecl =
5775 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5776 Name.Identifier, TemplateParams,
5777 NewTD);
5778
5779 NewDecl->setAccess(AS);
5780
5781 if (Invalid)
5782 NewDecl->setInvalidDecl();
5783 else if (OldDecl)
5784 NewDecl->setPreviousDeclaration(OldDecl);
5785
5786 NewND = NewDecl;
5787 } else {
5788 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5789 NewND = NewTD;
5790 }
Richard Smith162e1c12011-04-15 14:24:37 +00005791
5792 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005793 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005794
Richard Smith3e4c6c42011-05-05 21:57:07 +00005795 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005796}
5797
John McCalld226f652010-08-21 09:40:31 +00005798Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005799 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005800 SourceLocation AliasLoc,
5801 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005802 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005803 SourceLocation IdentLoc,
5804 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Anders Carlsson81c85c42009-03-28 23:53:49 +00005806 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005807 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5808 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005809
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005810 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005811 NamedDecl *PrevDecl
5812 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5813 ForRedeclaration);
5814 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5815 PrevDecl = 0;
5816
5817 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005818 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005819 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005820 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005821 // FIXME: At some point, we'll want to create the (redundant)
5822 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005823 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005824 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005825 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005826 }
Mike Stump1eb44332009-09-09 15:08:12 +00005827
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005828 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5829 diag::err_redefinition_different_kind;
5830 Diag(AliasLoc, DiagID) << Alias;
5831 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005832 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005833 }
5834
John McCalla24dc2e2009-11-17 02:14:36 +00005835 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005836 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005837
John McCallf36e02d2009-10-09 21:13:30 +00005838 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005839 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005840 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005841 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005842 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005843 }
Mike Stump1eb44332009-09-09 15:08:12 +00005844
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005845 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005846 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005847 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005848 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005849
John McCall3dbd3d52010-02-16 06:53:13 +00005850 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005851 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005852}
5853
Douglas Gregor39957dc2010-05-01 15:04:51 +00005854namespace {
5855 /// \brief Scoped object used to handle the state changes required in Sema
5856 /// to implicitly define the body of a C++ member function;
5857 class ImplicitlyDefinedFunctionScope {
5858 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005859 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005860
5861 public:
5862 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005863 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005864 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005865 S.PushFunctionScope();
5866 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5867 }
5868
5869 ~ImplicitlyDefinedFunctionScope() {
5870 S.PopExpressionEvaluationContext();
5871 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005872 }
5873 };
5874}
5875
Sean Hunt001cad92011-05-10 00:49:42 +00005876Sema::ImplicitExceptionSpecification
5877Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005878 // C++ [except.spec]p14:
5879 // An implicitly declared special member function (Clause 12) shall have an
5880 // exception-specification. [...]
5881 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00005882 if (ClassDecl->isInvalidDecl())
5883 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005884
Sebastian Redl60618fa2011-03-12 11:50:43 +00005885 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005886 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5887 BEnd = ClassDecl->bases_end();
5888 B != BEnd; ++B) {
5889 if (B->isVirtual()) // Handled below.
5890 continue;
5891
Douglas Gregor18274032010-07-03 00:47:00 +00005892 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5893 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005894 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5895 // If this is a deleted function, add it anyway. This might be conformant
5896 // with the standard. This might not. I'm not sure. It might not matter.
5897 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005898 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005899 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005900 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005901
5902 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005903 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5904 BEnd = ClassDecl->vbases_end();
5905 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00005906 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5907 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005908 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5909 // If this is a deleted function, add it anyway. This might be conformant
5910 // with the standard. This might not. I'm not sure. It might not matter.
5911 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005912 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005913 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005914 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005915
5916 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005917 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5918 FEnd = ClassDecl->field_end();
5919 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00005920 if (F->hasInClassInitializer()) {
5921 if (Expr *E = F->getInClassInitializer())
5922 ExceptSpec.CalledExpr(E);
5923 else if (!F->isInvalidDecl())
5924 ExceptSpec.SetDelayed();
5925 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00005926 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00005927 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5928 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5929 // If this is a deleted function, add it anyway. This might be conformant
5930 // with the standard. This might not. I'm not sure. It might not matter.
5931 // In particular, the problem is that this function never gets called. It
5932 // might just be ill-formed because this function attempts to refer to
5933 // a deleted function here.
5934 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005935 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005936 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005937 }
John McCalle23cf432010-12-14 08:05:40 +00005938
Sean Hunt001cad92011-05-10 00:49:42 +00005939 return ExceptSpec;
5940}
5941
5942CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5943 CXXRecordDecl *ClassDecl) {
5944 // C++ [class.ctor]p5:
5945 // A default constructor for a class X is a constructor of class X
5946 // that can be called without an argument. If there is no
5947 // user-declared constructor for class X, a default constructor is
5948 // implicitly declared. An implicitly-declared default constructor
5949 // is an inline public member of its class.
5950 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5951 "Should not build implicit default constructor!");
5952
5953 ImplicitExceptionSpecification Spec =
5954 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5955 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00005956
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005957 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00005958 CanQualType ClassType
5959 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005960 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005961 DeclarationName Name
5962 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005963 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005964 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005965 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00005966 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00005967 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00005968 /*TInfo=*/0,
5969 /*isExplicit=*/false,
5970 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00005971 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00005972 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00005973 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00005974 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00005975 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00005976
5977 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00005978 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5979
Douglas Gregor23c94db2010-07-02 17:43:08 +00005980 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00005981 PushOnScopeChains(DefaultCon, S, false);
5982 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00005983
5984 if (ShouldDeleteDefaultConstructor(DefaultCon))
5985 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00005986
Douglas Gregor32df23e2010-07-01 22:02:46 +00005987 return DefaultCon;
5988}
5989
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005990void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5991 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00005992 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00005993 !Constructor->doesThisDeclarationHaveABody() &&
5994 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005995 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005996
Anders Carlssonf6513ed2010-04-23 16:04:08 +00005997 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00005998 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00005999
Douglas Gregor39957dc2010-05-01 15:04:51 +00006000 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006001 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006002 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006003 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006004 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006005 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006006 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006007 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006008 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006009
6010 SourceLocation Loc = Constructor->getLocation();
6011 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6012
6013 Constructor->setUsed();
6014 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006015
6016 if (ASTMutationListener *L = getASTMutationListener()) {
6017 L->CompletedImplicitDefinition(Constructor);
6018 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006019}
6020
Richard Smith7a614d82011-06-11 17:19:42 +00006021/// Get any existing defaulted default constructor for the given class. Do not
6022/// implicitly define one if it does not exist.
6023static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6024 CXXRecordDecl *D) {
6025 ASTContext &Context = Self.Context;
6026 QualType ClassType = Context.getTypeDeclType(D);
6027 DeclarationName ConstructorName
6028 = Context.DeclarationNames.getCXXConstructorName(
6029 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6030
6031 DeclContext::lookup_const_iterator Con, ConEnd;
6032 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6033 Con != ConEnd; ++Con) {
6034 // A function template cannot be defaulted.
6035 if (isa<FunctionTemplateDecl>(*Con))
6036 continue;
6037
6038 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6039 if (Constructor->isDefaultConstructor())
6040 return Constructor->isDefaulted() ? Constructor : 0;
6041 }
6042 return 0;
6043}
6044
6045void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6046 if (!D) return;
6047 AdjustDeclIfTemplate(D);
6048
6049 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6050 CXXConstructorDecl *CtorDecl
6051 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6052
6053 if (!CtorDecl) return;
6054
6055 // Compute the exception specification for the default constructor.
6056 const FunctionProtoType *CtorTy =
6057 CtorDecl->getType()->castAs<FunctionProtoType>();
6058 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6059 ImplicitExceptionSpecification Spec =
6060 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6061 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6062 assert(EPI.ExceptionSpecType != EST_Delayed);
6063
6064 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6065 }
6066
6067 // If the default constructor is explicitly defaulted, checking the exception
6068 // specification is deferred until now.
6069 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6070 !ClassDecl->isDependentType())
6071 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6072}
6073
Sebastian Redlf677ea32011-02-05 19:23:19 +00006074void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6075 // We start with an initial pass over the base classes to collect those that
6076 // inherit constructors from. If there are none, we can forgo all further
6077 // processing.
6078 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6079 BasesVector BasesToInheritFrom;
6080 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6081 BaseE = ClassDecl->bases_end();
6082 BaseIt != BaseE; ++BaseIt) {
6083 if (BaseIt->getInheritConstructors()) {
6084 QualType Base = BaseIt->getType();
6085 if (Base->isDependentType()) {
6086 // If we inherit constructors from anything that is dependent, just
6087 // abort processing altogether. We'll get another chance for the
6088 // instantiations.
6089 return;
6090 }
6091 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6092 }
6093 }
6094 if (BasesToInheritFrom.empty())
6095 return;
6096
6097 // Now collect the constructors that we already have in the current class.
6098 // Those take precedence over inherited constructors.
6099 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6100 // unless there is a user-declared constructor with the same signature in
6101 // the class where the using-declaration appears.
6102 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6103 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6104 CtorE = ClassDecl->ctor_end();
6105 CtorIt != CtorE; ++CtorIt) {
6106 ExistingConstructors.insert(
6107 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6108 }
6109
6110 Scope *S = getScopeForContext(ClassDecl);
6111 DeclarationName CreatedCtorName =
6112 Context.DeclarationNames.getCXXConstructorName(
6113 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6114
6115 // Now comes the true work.
6116 // First, we keep a map from constructor types to the base that introduced
6117 // them. Needed for finding conflicting constructors. We also keep the
6118 // actually inserted declarations in there, for pretty diagnostics.
6119 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6120 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6121 ConstructorToSourceMap InheritedConstructors;
6122 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6123 BaseE = BasesToInheritFrom.end();
6124 BaseIt != BaseE; ++BaseIt) {
6125 const RecordType *Base = *BaseIt;
6126 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6127 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6128 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6129 CtorE = BaseDecl->ctor_end();
6130 CtorIt != CtorE; ++CtorIt) {
6131 // Find the using declaration for inheriting this base's constructors.
6132 DeclarationName Name =
6133 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6134 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6135 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6136 SourceLocation UsingLoc = UD ? UD->getLocation() :
6137 ClassDecl->getLocation();
6138
6139 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6140 // from the class X named in the using-declaration consists of actual
6141 // constructors and notional constructors that result from the
6142 // transformation of defaulted parameters as follows:
6143 // - all non-template default constructors of X, and
6144 // - for each non-template constructor of X that has at least one
6145 // parameter with a default argument, the set of constructors that
6146 // results from omitting any ellipsis parameter specification and
6147 // successively omitting parameters with a default argument from the
6148 // end of the parameter-type-list.
6149 CXXConstructorDecl *BaseCtor = *CtorIt;
6150 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6151 const FunctionProtoType *BaseCtorType =
6152 BaseCtor->getType()->getAs<FunctionProtoType>();
6153
6154 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6155 maxParams = BaseCtor->getNumParams();
6156 params <= maxParams; ++params) {
6157 // Skip default constructors. They're never inherited.
6158 if (params == 0)
6159 continue;
6160 // Skip copy and move constructors for the same reason.
6161 if (CanBeCopyOrMove && params == 1)
6162 continue;
6163
6164 // Build up a function type for this particular constructor.
6165 // FIXME: The working paper does not consider that the exception spec
6166 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006167 // source. This code doesn't yet, either. When it does, this code will
6168 // need to be delayed until after exception specifications and in-class
6169 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006170 const Type *NewCtorType;
6171 if (params == maxParams)
6172 NewCtorType = BaseCtorType;
6173 else {
6174 llvm::SmallVector<QualType, 16> Args;
6175 for (unsigned i = 0; i < params; ++i) {
6176 Args.push_back(BaseCtorType->getArgType(i));
6177 }
6178 FunctionProtoType::ExtProtoInfo ExtInfo =
6179 BaseCtorType->getExtProtoInfo();
6180 ExtInfo.Variadic = false;
6181 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6182 Args.data(), params, ExtInfo)
6183 .getTypePtr();
6184 }
6185 const Type *CanonicalNewCtorType =
6186 Context.getCanonicalType(NewCtorType);
6187
6188 // Now that we have the type, first check if the class already has a
6189 // constructor with this signature.
6190 if (ExistingConstructors.count(CanonicalNewCtorType))
6191 continue;
6192
6193 // Then we check if we have already declared an inherited constructor
6194 // with this signature.
6195 std::pair<ConstructorToSourceMap::iterator, bool> result =
6196 InheritedConstructors.insert(std::make_pair(
6197 CanonicalNewCtorType,
6198 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6199 if (!result.second) {
6200 // Already in the map. If it came from a different class, that's an
6201 // error. Not if it's from the same.
6202 CanQualType PreviousBase = result.first->second.first;
6203 if (CanonicalBase != PreviousBase) {
6204 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6205 const CXXConstructorDecl *PrevBaseCtor =
6206 PrevCtor->getInheritedConstructor();
6207 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6208
6209 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6210 Diag(BaseCtor->getLocation(),
6211 diag::note_using_decl_constructor_conflict_current_ctor);
6212 Diag(PrevBaseCtor->getLocation(),
6213 diag::note_using_decl_constructor_conflict_previous_ctor);
6214 Diag(PrevCtor->getLocation(),
6215 diag::note_using_decl_constructor_conflict_previous_using);
6216 }
6217 continue;
6218 }
6219
6220 // OK, we're there, now add the constructor.
6221 // C++0x [class.inhctor]p8: [...] that would be performed by a
6222 // user-writtern inline constructor [...]
6223 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6224 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006225 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6226 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006227 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006228 NewCtor->setAccess(BaseCtor->getAccess());
6229
6230 // Build up the parameter decls and add them.
6231 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6232 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006233 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6234 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006235 /*IdentifierInfo=*/0,
6236 BaseCtorType->getArgType(i),
6237 /*TInfo=*/0, SC_None,
6238 SC_None, /*DefaultArg=*/0));
6239 }
6240 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6241 NewCtor->setInheritedConstructor(BaseCtor);
6242
6243 PushOnScopeChains(NewCtor, S, false);
6244 ClassDecl->addDecl(NewCtor);
6245 result.first->second.second = NewCtor;
6246 }
6247 }
6248 }
6249}
6250
Sean Huntcb45a0f2011-05-12 22:46:25 +00006251Sema::ImplicitExceptionSpecification
6252Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006253 // C++ [except.spec]p14:
6254 // An implicitly declared special member function (Clause 12) shall have
6255 // an exception-specification.
6256 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006257 if (ClassDecl->isInvalidDecl())
6258 return ExceptSpec;
6259
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006260 // Direct base-class destructors.
6261 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6262 BEnd = ClassDecl->bases_end();
6263 B != BEnd; ++B) {
6264 if (B->isVirtual()) // Handled below.
6265 continue;
6266
6267 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6268 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006269 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006270 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006271
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006272 // Virtual base-class destructors.
6273 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6274 BEnd = ClassDecl->vbases_end();
6275 B != BEnd; ++B) {
6276 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6277 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006278 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006279 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006280
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006281 // Field destructors.
6282 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6283 FEnd = ClassDecl->field_end();
6284 F != FEnd; ++F) {
6285 if (const RecordType *RecordTy
6286 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6287 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006288 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006289 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006290
Sean Huntcb45a0f2011-05-12 22:46:25 +00006291 return ExceptSpec;
6292}
6293
6294CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6295 // C++ [class.dtor]p2:
6296 // If a class has no user-declared destructor, a destructor is
6297 // declared implicitly. An implicitly-declared destructor is an
6298 // inline public member of its class.
6299
6300 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006301 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006302 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6303
Douglas Gregor4923aa22010-07-02 20:37:36 +00006304 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006305 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006306
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006307 CanQualType ClassType
6308 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006309 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006310 DeclarationName Name
6311 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006312 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006313 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006314 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6315 /*isInline=*/true,
6316 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006317 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006318 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006319 Destructor->setImplicit();
6320 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006321
6322 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006323 ++ASTContext::NumImplicitDestructorsDeclared;
6324
6325 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006326 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006327 PushOnScopeChains(Destructor, S, false);
6328 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006329
6330 // This could be uniqued if it ever proves significant.
6331 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006332
6333 if (ShouldDeleteDestructor(Destructor))
6334 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006335
6336 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006337
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006338 return Destructor;
6339}
6340
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006341void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006342 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006343 assert((Destructor->isDefaulted() &&
6344 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006345 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006346 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006347 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006348
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006349 if (Destructor->isInvalidDecl())
6350 return;
6351
Douglas Gregor39957dc2010-05-01 15:04:51 +00006352 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006353
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006354 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006355 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6356 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006357
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006358 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006359 Diag(CurrentLocation, diag::note_member_synthesized_at)
6360 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6361
6362 Destructor->setInvalidDecl();
6363 return;
6364 }
6365
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006366 SourceLocation Loc = Destructor->getLocation();
6367 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6368
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006369 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006370 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006371
6372 if (ASTMutationListener *L = getASTMutationListener()) {
6373 L->CompletedImplicitDefinition(Destructor);
6374 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006375}
6376
Sebastian Redl0ee33912011-05-19 05:13:44 +00006377void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6378 CXXDestructorDecl *destructor) {
6379 // C++11 [class.dtor]p3:
6380 // A declaration of a destructor that does not have an exception-
6381 // specification is implicitly considered to have the same exception-
6382 // specification as an implicit declaration.
6383 const FunctionProtoType *dtorType = destructor->getType()->
6384 getAs<FunctionProtoType>();
6385 if (dtorType->hasExceptionSpec())
6386 return;
6387
6388 ImplicitExceptionSpecification exceptSpec =
6389 ComputeDefaultedDtorExceptionSpec(classDecl);
6390
6391 // Replace the destructor's type.
6392 FunctionProtoType::ExtProtoInfo epi;
6393 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6394 epi.NumExceptions = exceptSpec.size();
6395 epi.Exceptions = exceptSpec.data();
6396 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6397
6398 destructor->setType(ty);
6399
6400 // FIXME: If the destructor has a body that could throw, and the newly created
6401 // spec doesn't allow exceptions, we should emit a warning, because this
6402 // change in behavior can break conforming C++03 programs at runtime.
6403 // However, we don't have a body yet, so it needs to be done somewhere else.
6404}
6405
Douglas Gregor06a9f362010-05-01 20:49:11 +00006406/// \brief Builds a statement that copies the given entity from \p From to
6407/// \c To.
6408///
6409/// This routine is used to copy the members of a class with an
6410/// implicitly-declared copy assignment operator. When the entities being
6411/// copied are arrays, this routine builds for loops to copy them.
6412///
6413/// \param S The Sema object used for type-checking.
6414///
6415/// \param Loc The location where the implicit copy is being generated.
6416///
6417/// \param T The type of the expressions being copied. Both expressions must
6418/// have this type.
6419///
6420/// \param To The expression we are copying to.
6421///
6422/// \param From The expression we are copying from.
6423///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006424/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6425/// Otherwise, it's a non-static member subobject.
6426///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006427/// \param Depth Internal parameter recording the depth of the recursion.
6428///
6429/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006430static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006431BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006432 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006433 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006434 // C++0x [class.copy]p30:
6435 // Each subobject is assigned in the manner appropriate to its type:
6436 //
6437 // - if the subobject is of class type, the copy assignment operator
6438 // for the class is used (as if by explicit qualification; that is,
6439 // ignoring any possible virtual overriding functions in more derived
6440 // classes);
6441 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6442 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6443
6444 // Look for operator=.
6445 DeclarationName Name
6446 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6447 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6448 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6449
6450 // Filter out any result that isn't a copy-assignment operator.
6451 LookupResult::Filter F = OpLookup.makeFilter();
6452 while (F.hasNext()) {
6453 NamedDecl *D = F.next();
6454 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6455 if (Method->isCopyAssignmentOperator())
6456 continue;
6457
6458 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006459 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006460 F.done();
6461
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006462 // Suppress the protected check (C++ [class.protected]) for each of the
6463 // assignment operators we found. This strange dance is required when
6464 // we're assigning via a base classes's copy-assignment operator. To
6465 // ensure that we're getting the right base class subobject (without
6466 // ambiguities), we need to cast "this" to that subobject type; to
6467 // ensure that we don't go through the virtual call mechanism, we need
6468 // to qualify the operator= name with the base class (see below). However,
6469 // this means that if the base class has a protected copy assignment
6470 // operator, the protected member access check will fail. So, we
6471 // rewrite "protected" access to "public" access in this case, since we
6472 // know by construction that we're calling from a derived class.
6473 if (CopyingBaseSubobject) {
6474 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6475 L != LEnd; ++L) {
6476 if (L.getAccess() == AS_protected)
6477 L.setAccess(AS_public);
6478 }
6479 }
6480
Douglas Gregor06a9f362010-05-01 20:49:11 +00006481 // Create the nested-name-specifier that will be used to qualify the
6482 // reference to operator=; this is required to suppress the virtual
6483 // call mechanism.
6484 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00006485 SS.MakeTrivial(S.Context,
6486 NestedNameSpecifier::Create(S.Context, 0, false,
6487 T.getTypePtr()),
6488 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006489
6490 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00006491 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00006492 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006493 /*FirstQualifierInScope=*/0, OpLookup,
6494 /*TemplateArgs=*/0,
6495 /*SuppressQualifierCheck=*/true);
6496 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006497 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006498
6499 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00006500
John McCall60d7b3a2010-08-24 06:29:42 +00006501 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00006502 OpEqualRef.takeAs<Expr>(),
6503 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006504 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006505 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006506
6507 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006508 }
John McCallb0207482010-03-16 06:11:48 +00006509
Douglas Gregor06a9f362010-05-01 20:49:11 +00006510 // - if the subobject is of scalar type, the built-in assignment
6511 // operator is used.
6512 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6513 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00006514 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006515 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006516 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006517
6518 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006519 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006520
6521 // - if the subobject is an array, each element is assigned, in the
6522 // manner appropriate to the element type;
6523
6524 // Construct a loop over the array bounds, e.g.,
6525 //
6526 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6527 //
6528 // that will copy each of the array elements.
6529 QualType SizeType = S.Context.getSizeType();
6530
6531 // Create the iteration variable.
6532 IdentifierInfo *IterationVarName = 0;
6533 {
6534 llvm::SmallString<8> Str;
6535 llvm::raw_svector_ostream OS(Str);
6536 OS << "__i" << Depth;
6537 IterationVarName = &S.Context.Idents.get(OS.str());
6538 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006539 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006540 IterationVarName, SizeType,
6541 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00006542 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006543
6544 // Initialize the iteration variable to zero.
6545 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006546 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006547
6548 // Create a reference to the iteration variable; we'll use this several
6549 // times throughout.
6550 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00006551 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006552 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6553
6554 // Create the DeclStmt that holds the iteration variable.
6555 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6556
6557 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006558 llvm::APInt Upper
6559 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00006560 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00006561 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00006562 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6563 BO_NE, S.Context.BoolTy,
6564 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006565
6566 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006567 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00006568 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6569 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006570
6571 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006572 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6573 IterationVarRef, Loc));
6574 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6575 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006576
6577 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00006578 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6579 To, From, CopyingBaseSubobject,
6580 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00006581 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006582 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006583
6584 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00006585 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006586 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00006587 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00006588 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006589}
6590
Sean Hunt30de05c2011-05-14 05:23:20 +00006591std::pair<Sema::ImplicitExceptionSpecification, bool>
6592Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6593 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006594 if (ClassDecl->isInvalidDecl())
6595 return std::make_pair(ImplicitExceptionSpecification(Context), false);
6596
Douglas Gregord3c35902010-07-01 16:36:15 +00006597 // C++ [class.copy]p10:
6598 // If the class definition does not explicitly declare a copy
6599 // assignment operator, one is declared implicitly.
6600 // The implicitly-defined copy assignment operator for a class X
6601 // will have the form
6602 //
6603 // X& X::operator=(const X&)
6604 //
6605 // if
6606 bool HasConstCopyAssignment = true;
6607
6608 // -- each direct base class B of X has a copy assignment operator
6609 // whose parameter is of type const B&, const volatile B& or B,
6610 // and
6611 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6612 BaseEnd = ClassDecl->bases_end();
6613 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00006614 // We'll handle this below
6615 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6616 continue;
6617
Douglas Gregord3c35902010-07-01 16:36:15 +00006618 assert(!Base->getType()->isDependentType() &&
6619 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00006620 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6621 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6622 &HasConstCopyAssignment);
6623 }
6624
6625 // In C++0x, the above citation has "or virtual added"
6626 if (LangOpts.CPlusPlus0x) {
6627 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6628 BaseEnd = ClassDecl->vbases_end();
6629 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6630 assert(!Base->getType()->isDependentType() &&
6631 "Cannot generate implicit members for class with dependent bases.");
6632 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6633 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6634 &HasConstCopyAssignment);
6635 }
Douglas Gregord3c35902010-07-01 16:36:15 +00006636 }
6637
6638 // -- for all the nonstatic data members of X that are of a class
6639 // type M (or array thereof), each such class type has a copy
6640 // assignment operator whose parameter is of type const M&,
6641 // const volatile M& or M.
6642 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6643 FieldEnd = ClassDecl->field_end();
6644 HasConstCopyAssignment && Field != FieldEnd;
6645 ++Field) {
6646 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00006647 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6648 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6649 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006650 }
6651 }
6652
6653 // Otherwise, the implicitly declared copy assignment operator will
6654 // have the form
6655 //
6656 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00006657
Douglas Gregorb87786f2010-07-01 17:48:08 +00006658 // C++ [except.spec]p14:
6659 // An implicitly declared special member function (Clause 12) shall have an
6660 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00006661
6662 // It is unspecified whether or not an implicit copy assignment operator
6663 // attempts to deduplicate calls to assignment operators of virtual bases are
6664 // made. As such, this exception specification is effectively unspecified.
6665 // Based on a similar decision made for constness in C++0x, we're erring on
6666 // the side of assuming such calls to be made regardless of whether they
6667 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00006668 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00006669 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00006670 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6671 BaseEnd = ClassDecl->bases_end();
6672 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00006673 if (Base->isVirtual())
6674 continue;
6675
Douglas Gregora376d102010-07-02 21:50:04 +00006676 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00006678 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6679 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00006680 ExceptSpec.CalledDecl(CopyAssign);
6681 }
Sean Hunt661c67a2011-06-21 23:42:56 +00006682
6683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6684 BaseEnd = ClassDecl->vbases_end();
6685 Base != BaseEnd; ++Base) {
6686 CXXRecordDecl *BaseClassDecl
6687 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6688 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6689 ArgQuals, false, 0))
6690 ExceptSpec.CalledDecl(CopyAssign);
6691 }
6692
Douglas Gregorb87786f2010-07-01 17:48:08 +00006693 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6694 FieldEnd = ClassDecl->field_end();
6695 Field != FieldEnd;
6696 ++Field) {
6697 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00006698 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6699 if (CXXMethodDecl *CopyAssign =
6700 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6701 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006702 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00006703 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006704
Sean Hunt30de05c2011-05-14 05:23:20 +00006705 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6706}
6707
6708CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6709 // Note: The following rules are largely analoguous to the copy
6710 // constructor rules. Note that virtual bases are not taken into account
6711 // for determining the argument type of the operator. Note also that
6712 // operators taking an object instead of a reference are allowed.
6713
6714 ImplicitExceptionSpecification Spec(Context);
6715 bool Const;
6716 llvm::tie(Spec, Const) =
6717 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6718
6719 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6720 QualType RetType = Context.getLValueReferenceType(ArgType);
6721 if (Const)
6722 ArgType = ArgType.withConst();
6723 ArgType = Context.getLValueReferenceType(ArgType);
6724
Douglas Gregord3c35902010-07-01 16:36:15 +00006725 // An implicitly-declared copy assignment operator is an inline public
6726 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00006727 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00006728 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006729 SourceLocation ClassLoc = ClassDecl->getLocation();
6730 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006731 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006732 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006733 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006734 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006735 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006736 /*isInline=*/true,
6737 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006738 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00006739 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00006740 CopyAssignment->setImplicit();
6741 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006742
6743 // Add the parameter to the operator.
6744 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006745 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006746 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006747 SC_None,
6748 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006749 CopyAssignment->setParams(&FromParam, 1);
6750
Douglas Gregora376d102010-07-02 21:50:04 +00006751 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006752 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00006753
Douglas Gregor23c94db2010-07-02 17:43:08 +00006754 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006755 PushOnScopeChains(CopyAssignment, S, false);
6756 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006757
Sean Hunt1ccbc542011-06-22 01:05:13 +00006758 // C++0x [class.copy]p18:
6759 // ... If the class definition declares a move constructor or move
6760 // assignment operator, the implicitly declared copy assignment operator is
6761 // defined as deleted; ...
6762 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6763 ClassDecl->hasUserDeclaredMoveAssignment() ||
6764 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00006765 CopyAssignment->setDeletedAsWritten();
6766
Douglas Gregord3c35902010-07-01 16:36:15 +00006767 AddOverriddenMethods(ClassDecl, CopyAssignment);
6768 return CopyAssignment;
6769}
6770
Douglas Gregor06a9f362010-05-01 20:49:11 +00006771void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6772 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00006773 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006774 CopyAssignOperator->isOverloadedOperator() &&
6775 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006776 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006777 "DefineImplicitCopyAssignment called for wrong function");
6778
6779 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6780
6781 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6782 CopyAssignOperator->setInvalidDecl();
6783 return;
6784 }
6785
6786 CopyAssignOperator->setUsed();
6787
6788 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006789 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006790
6791 // C++0x [class.copy]p30:
6792 // The implicitly-defined or explicitly-defaulted copy assignment operator
6793 // for a non-union class X performs memberwise copy assignment of its
6794 // subobjects. The direct base classes of X are assigned first, in the
6795 // order of their declaration in the base-specifier-list, and then the
6796 // immediate non-static data members of X are assigned, in the order in
6797 // which they were declared in the class definition.
6798
6799 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006800 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006801
6802 // The parameter for the "other" object, which we are copying from.
6803 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6804 Qualifiers OtherQuals = Other->getType().getQualifiers();
6805 QualType OtherRefType = Other->getType();
6806 if (const LValueReferenceType *OtherRef
6807 = OtherRefType->getAs<LValueReferenceType>()) {
6808 OtherRefType = OtherRef->getPointeeType();
6809 OtherQuals = OtherRefType.getQualifiers();
6810 }
6811
6812 // Our location for everything implicitly-generated.
6813 SourceLocation Loc = CopyAssignOperator->getLocation();
6814
6815 // Construct a reference to the "other" object. We'll be using this
6816 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006817 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006818 assert(OtherRef && "Reference to parameter cannot fail!");
6819
6820 // Construct the "this" pointer. We'll be using this throughout the generated
6821 // ASTs.
6822 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6823 assert(This && "Reference to this cannot fail!");
6824
6825 // Assign base classes.
6826 bool Invalid = false;
6827 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6828 E = ClassDecl->bases_end(); Base != E; ++Base) {
6829 // Form the assignment:
6830 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6831 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006832 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006833 Invalid = true;
6834 continue;
6835 }
6836
John McCallf871d0c2010-08-07 06:22:56 +00006837 CXXCastPath BasePath;
6838 BasePath.push_back(Base);
6839
Douglas Gregor06a9f362010-05-01 20:49:11 +00006840 // Construct the "from" expression, which is an implicit cast to the
6841 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006842 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006843 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6844 CK_UncheckedDerivedToBase,
6845 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006846
6847 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006848 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006849
6850 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006851 To = ImpCastExprToType(To.take(),
6852 Context.getCVRQualifiedType(BaseType,
6853 CopyAssignOperator->getTypeQualifiers()),
6854 CK_UncheckedDerivedToBase,
6855 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006856
6857 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006858 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006859 To.get(), From,
6860 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006861 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006862 Diag(CurrentLocation, diag::note_member_synthesized_at)
6863 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6864 CopyAssignOperator->setInvalidDecl();
6865 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006866 }
6867
6868 // Success! Record the copy.
6869 Statements.push_back(Copy.takeAs<Expr>());
6870 }
6871
6872 // \brief Reference to the __builtin_memcpy function.
6873 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006874 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006875 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006876
6877 // Assign non-static members.
6878 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6879 FieldEnd = ClassDecl->field_end();
6880 Field != FieldEnd; ++Field) {
6881 // Check for members of reference type; we can't copy those.
6882 if (Field->getType()->isReferenceType()) {
6883 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6884 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6885 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006886 Diag(CurrentLocation, diag::note_member_synthesized_at)
6887 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006888 Invalid = true;
6889 continue;
6890 }
6891
6892 // Check for members of const-qualified, non-class type.
6893 QualType BaseType = Context.getBaseElementType(Field->getType());
6894 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6895 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6896 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6897 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006898 Diag(CurrentLocation, diag::note_member_synthesized_at)
6899 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006900 Invalid = true;
6901 continue;
6902 }
John McCallb77115d2011-06-17 00:18:42 +00006903
6904 // Suppress assigning zero-width bitfields.
6905 if (const Expr *Width = Field->getBitWidth())
6906 if (Width->EvaluateAsInt(Context) == 0)
6907 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006908
6909 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006910 if (FieldType->isIncompleteArrayType()) {
6911 assert(ClassDecl->hasFlexibleArrayMember() &&
6912 "Incomplete array type is not valid");
6913 continue;
6914 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006915
6916 // Build references to the field in the object we're copying from and to.
6917 CXXScopeSpec SS; // Intentionally empty
6918 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6919 LookupMemberName);
6920 MemberLookup.addDecl(*Field);
6921 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00006922 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00006923 Loc, /*IsArrow=*/false,
6924 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006925 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00006926 Loc, /*IsArrow=*/true,
6927 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006928 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6929 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6930
6931 // If the field should be copied with __builtin_memcpy rather than via
6932 // explicit assignments, do so. This optimization only applies for arrays
6933 // of scalars and arrays of class type with trivial copy-assignment
6934 // operators.
John McCallf85e1932011-06-15 23:02:42 +00006935 if (FieldType->isArrayType() &&
6936 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006937 // Compute the size of the memory buffer to be copied.
6938 QualType SizeType = Context.getSizeType();
6939 llvm::APInt Size(Context.getTypeSize(SizeType),
6940 Context.getTypeSizeInChars(BaseType).getQuantity());
6941 for (const ConstantArrayType *Array
6942 = Context.getAsConstantArrayType(FieldType);
6943 Array;
6944 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00006945 llvm::APInt ArraySize
6946 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00006947 Size *= ArraySize;
6948 }
6949
6950 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00006951 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6952 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006953
6954 bool NeedsCollectableMemCpy =
6955 (BaseType->isRecordType() &&
6956 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6957
6958 if (NeedsCollectableMemCpy) {
6959 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006960 // Create a reference to the __builtin_objc_memmove_collectable function.
6961 LookupResult R(*this,
6962 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006963 Loc, LookupOrdinaryName);
6964 LookupName(R, TUScope, true);
6965
6966 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6967 if (!CollectableMemCpy) {
6968 // Something went horribly wrong earlier, and we will have
6969 // complained about it.
6970 Invalid = true;
6971 continue;
6972 }
6973
6974 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6975 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006976 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006977 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6978 }
6979 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006980 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006981 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006982 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6983 LookupOrdinaryName);
6984 LookupName(R, TUScope, true);
6985
6986 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6987 if (!BuiltinMemCpy) {
6988 // Something went horribly wrong earlier, and we will have complained
6989 // about it.
6990 Invalid = true;
6991 continue;
6992 }
6993
6994 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6995 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00006996 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006997 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6998 }
6999
John McCallca0408f2010-08-23 06:44:23 +00007000 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007001 CallArgs.push_back(To.takeAs<Expr>());
7002 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007003 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007004 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007005 if (NeedsCollectableMemCpy)
7006 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007007 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007008 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007009 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007010 else
7011 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007012 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007013 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007014 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007015
Douglas Gregor06a9f362010-05-01 20:49:11 +00007016 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7017 Statements.push_back(Call.takeAs<Expr>());
7018 continue;
7019 }
7020
7021 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007022 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00007023 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007024 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007025 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007026 Diag(CurrentLocation, diag::note_member_synthesized_at)
7027 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7028 CopyAssignOperator->setInvalidDecl();
7029 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007030 }
7031
7032 // Success! Record the copy.
7033 Statements.push_back(Copy.takeAs<Stmt>());
7034 }
7035
7036 if (!Invalid) {
7037 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007038 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007039
John McCall60d7b3a2010-08-24 06:29:42 +00007040 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007041 if (Return.isInvalid())
7042 Invalid = true;
7043 else {
7044 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007045
7046 if (Trap.hasErrorOccurred()) {
7047 Diag(CurrentLocation, diag::note_member_synthesized_at)
7048 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7049 Invalid = true;
7050 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007051 }
7052 }
7053
7054 if (Invalid) {
7055 CopyAssignOperator->setInvalidDecl();
7056 return;
7057 }
7058
John McCall60d7b3a2010-08-24 06:29:42 +00007059 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007060 /*isStmtExpr=*/false);
7061 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7062 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007063
7064 if (ASTMutationListener *L = getASTMutationListener()) {
7065 L->CompletedImplicitDefinition(CopyAssignOperator);
7066 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007067}
7068
Sean Hunt49634cf2011-05-13 06:10:58 +00007069std::pair<Sema::ImplicitExceptionSpecification, bool>
7070Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007071 if (ClassDecl->isInvalidDecl())
7072 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7073
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007074 // C++ [class.copy]p5:
7075 // The implicitly-declared copy constructor for a class X will
7076 // have the form
7077 //
7078 // X::X(const X&)
7079 //
7080 // if
Sean Huntc530d172011-06-10 04:44:37 +00007081 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007082 bool HasConstCopyConstructor = true;
7083
7084 // -- each direct or virtual base class B of X has a copy
7085 // constructor whose first parameter is of type const B& or
7086 // const volatile B&, and
7087 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7088 BaseEnd = ClassDecl->bases_end();
7089 HasConstCopyConstructor && Base != BaseEnd;
7090 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007091 // Virtual bases are handled below.
7092 if (Base->isVirtual())
7093 continue;
7094
Douglas Gregor22584312010-07-02 23:41:54 +00007095 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007096 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007097 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7098 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00007099 }
7100
7101 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7102 BaseEnd = ClassDecl->vbases_end();
7103 HasConstCopyConstructor && Base != BaseEnd;
7104 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007105 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007106 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007107 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7108 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007109 }
7110
7111 // -- for all the nonstatic data members of X that are of a
7112 // class type M (or array thereof), each such class type
7113 // has a copy constructor whose first parameter is of type
7114 // const M& or const volatile M&.
7115 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7116 FieldEnd = ClassDecl->field_end();
7117 HasConstCopyConstructor && Field != FieldEnd;
7118 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007119 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007120 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007121 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7122 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007123 }
7124 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007125 // Otherwise, the implicitly declared copy constructor will have
7126 // the form
7127 //
7128 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00007129
Douglas Gregor0d405db2010-07-01 20:59:04 +00007130 // C++ [except.spec]p14:
7131 // An implicitly declared special member function (Clause 12) shall have an
7132 // exception-specification. [...]
7133 ImplicitExceptionSpecification ExceptSpec(Context);
7134 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7136 BaseEnd = ClassDecl->bases_end();
7137 Base != BaseEnd;
7138 ++Base) {
7139 // Virtual bases are handled below.
7140 if (Base->isVirtual())
7141 continue;
7142
Douglas Gregor22584312010-07-02 23:41:54 +00007143 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007144 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007145 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007146 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007147 ExceptSpec.CalledDecl(CopyConstructor);
7148 }
7149 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7150 BaseEnd = ClassDecl->vbases_end();
7151 Base != BaseEnd;
7152 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007153 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007154 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007155 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007156 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007157 ExceptSpec.CalledDecl(CopyConstructor);
7158 }
7159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7160 FieldEnd = ClassDecl->field_end();
7161 Field != FieldEnd;
7162 ++Field) {
7163 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007164 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7165 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00007166 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00007167 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00007168 }
7169 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007170
Sean Hunt49634cf2011-05-13 06:10:58 +00007171 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7172}
7173
7174CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7175 CXXRecordDecl *ClassDecl) {
7176 // C++ [class.copy]p4:
7177 // If the class definition does not explicitly declare a copy
7178 // constructor, one is declared implicitly.
7179
7180 ImplicitExceptionSpecification Spec(Context);
7181 bool Const;
7182 llvm::tie(Spec, Const) =
7183 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7184
7185 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7186 QualType ArgType = ClassType;
7187 if (Const)
7188 ArgType = ArgType.withConst();
7189 ArgType = Context.getLValueReferenceType(ArgType);
7190
7191 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7192
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007193 DeclarationName Name
7194 = Context.DeclarationNames.getCXXConstructorName(
7195 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007196 SourceLocation ClassLoc = ClassDecl->getLocation();
7197 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00007198
7199 // An implicitly-declared copy constructor is an inline public
7200 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007201 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007202 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007203 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007204 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007205 /*TInfo=*/0,
7206 /*isExplicit=*/false,
7207 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00007208 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007209 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00007210 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007211 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7212
Douglas Gregor22584312010-07-02 23:41:54 +00007213 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00007214 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7215
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007216 // Add the parameter to the constructor.
7217 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007218 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007219 /*IdentifierInfo=*/0,
7220 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007221 SC_None,
7222 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007223 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00007224
Douglas Gregor23c94db2010-07-02 17:43:08 +00007225 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00007226 PushOnScopeChains(CopyConstructor, S, false);
7227 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00007228
Sean Hunt1ccbc542011-06-22 01:05:13 +00007229 // C++0x [class.copy]p7:
7230 // ... If the class definition declares a move constructor or move
7231 // assignment operator, the implicitly declared constructor is defined as
7232 // deleted; ...
7233 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7234 ClassDecl->hasUserDeclaredMoveAssignment() ||
7235 ShouldDeleteCopyConstructor(CopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007236 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007237
7238 return CopyConstructor;
7239}
7240
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007241void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00007242 CXXConstructorDecl *CopyConstructor) {
7243 assert((CopyConstructor->isDefaulted() &&
7244 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007245 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007246 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007247
Anders Carlsson63010a72010-04-23 16:24:12 +00007248 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007249 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007250
Douglas Gregor39957dc2010-05-01 15:04:51 +00007251 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007252 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007253
Sean Huntcbb67482011-01-08 20:30:50 +00007254 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007255 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00007256 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007257 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00007258 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007259 } else {
7260 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7261 CopyConstructor->getLocation(),
7262 MultiStmtArg(*this, 0, 0),
7263 /*isStmtExpr=*/false)
7264 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00007265 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007266
7267 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007268
7269 if (ASTMutationListener *L = getASTMutationListener()) {
7270 L->CompletedImplicitDefinition(CopyConstructor);
7271 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007272}
7273
John McCall60d7b3a2010-08-24 06:29:42 +00007274ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007275Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00007276 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00007277 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007278 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007279 unsigned ConstructKind,
7280 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007281 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007282
Douglas Gregor2f599792010-04-02 18:24:57 +00007283 // C++0x [class.copy]p34:
7284 // When certain criteria are met, an implementation is allowed to
7285 // omit the copy/move construction of a class object, even if the
7286 // copy/move constructor and/or destructor for the object have
7287 // side effects. [...]
7288 // - when a temporary class object that has not been bound to a
7289 // reference (12.2) would be copied/moved to a class object
7290 // with the same cv-unqualified type, the copy/move operation
7291 // can be omitted by constructing the temporary object
7292 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00007293 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00007294 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00007295 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00007296 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007297 }
Mike Stump1eb44332009-09-09 15:08:12 +00007298
7299 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007300 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007301 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007302}
7303
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007304/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7305/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007306ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007307Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7308 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00007309 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007310 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007311 unsigned ConstructKind,
7312 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00007313 unsigned NumExprs = ExprArgs.size();
7314 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00007315
Nick Lewycky909a70d2011-03-25 01:44:32 +00007316 for (specific_attr_iterator<NonNullAttr>
7317 i = Constructor->specific_attr_begin<NonNullAttr>(),
7318 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7319 const NonNullAttr *NonNull = *i;
7320 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7321 }
7322
Douglas Gregor7edfb692009-11-23 12:27:39 +00007323 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00007324 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00007325 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00007326 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007327 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7328 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007329}
7330
Mike Stump1eb44332009-09-09 15:08:12 +00007331bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007332 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00007333 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00007334 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00007335 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00007336 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007337 move(Exprs), false, CXXConstructExpr::CK_Complete,
7338 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00007339 if (TempResult.isInvalid())
7340 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007341
Anders Carlssonda3f4e22009-08-25 05:12:04 +00007342 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00007343 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007344 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00007345 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00007346 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00007347
Anders Carlssonfe2de492009-08-25 05:18:00 +00007348 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00007349}
7350
John McCall68c6c9a2010-02-02 09:10:11 +00007351void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007352 if (VD->isInvalidDecl()) return;
7353
John McCall68c6c9a2010-02-02 09:10:11 +00007354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007355 if (ClassDecl->isInvalidDecl()) return;
7356 if (ClassDecl->hasTrivialDestructor()) return;
7357 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00007358
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007359 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7360 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7361 CheckDestructorAccess(VD->getLocation(), Destructor,
7362 PDiag(diag::err_access_dtor_var)
7363 << VD->getDeclName()
7364 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00007365
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007366 if (!VD->hasGlobalStorage()) return;
7367
7368 // Emit warning for non-trivial dtor in global scope (a real global,
7369 // class-static, function-static).
7370 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7371
7372 // TODO: this should be re-enabled for static locals by !CXAAtExit
7373 if (!VD->isStaticLocal())
7374 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007375}
7376
Mike Stump1eb44332009-09-09 15:08:12 +00007377/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007378/// ActOnDeclarator, when a C++ direct initializer is present.
7379/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00007380void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007381 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007382 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00007383 SourceLocation RParenLoc,
7384 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00007385 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007386
7387 // If there is no declaration, there was an error parsing it. Just ignore
7388 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00007389 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007390 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007391
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007392 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7393 if (!VDecl) {
7394 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7395 RealDecl->setInvalidDecl();
7396 return;
7397 }
7398
Richard Smith34b41d92011-02-20 03:19:35 +00007399 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7400 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00007401 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7402 if (Exprs.size() > 1) {
7403 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7404 diag::err_auto_var_init_multiple_expressions)
7405 << VDecl->getDeclName() << VDecl->getType()
7406 << VDecl->getSourceRange();
7407 RealDecl->setInvalidDecl();
7408 return;
7409 }
7410
7411 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00007412 TypeSourceInfo *DeducedType = 0;
7413 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00007414 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7415 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7416 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00007417 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00007418 RealDecl->setInvalidDecl();
7419 return;
7420 }
Richard Smitha085da82011-03-17 16:11:59 +00007421 VDecl->setTypeSourceInfo(DeducedType);
7422 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00007423
John McCallf85e1932011-06-15 23:02:42 +00007424 // In ARC, infer lifetime.
7425 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7426 VDecl->setInvalidDecl();
7427
Richard Smith34b41d92011-02-20 03:19:35 +00007428 // If this is a redeclaration, check that the type we just deduced matches
7429 // the previously declared type.
7430 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7431 MergeVarDeclTypes(VDecl, Old);
7432 }
7433
Douglas Gregor83ddad32009-08-26 21:14:46 +00007434 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007435 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007436 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7437 //
7438 // Clients that want to distinguish between the two forms, can check for
7439 // direct initializer using VarDecl::hasCXXDirectInitializer().
7440 // A major benefit is that clients that don't particularly care about which
7441 // exactly form was it (like the CodeGen) can handle both cases without
7442 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007443
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007444 // C++ 8.5p11:
7445 // The form of initialization (using parentheses or '=') is generally
7446 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007447 // class type.
7448
Douglas Gregor4dffad62010-02-11 22:55:30 +00007449 if (!VDecl->getType()->isDependentType() &&
7450 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00007451 diag::err_typecheck_decl_incomplete_type)) {
7452 VDecl->setInvalidDecl();
7453 return;
7454 }
7455
Douglas Gregor90f93822009-12-22 22:17:25 +00007456 // The variable can not have an abstract class type.
7457 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7458 diag::err_abstract_type_in_decl,
7459 AbstractVariableType))
7460 VDecl->setInvalidDecl();
7461
Sebastian Redl31310a22010-02-01 20:16:42 +00007462 const VarDecl *Def;
7463 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00007464 Diag(VDecl->getLocation(), diag::err_redefinition)
7465 << VDecl->getDeclName();
7466 Diag(Def->getLocation(), diag::note_previous_definition);
7467 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007468 return;
7469 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00007470
Douglas Gregor3a91abf2010-08-24 05:27:49 +00007471 // C++ [class.static.data]p4
7472 // If a static data member is of const integral or const
7473 // enumeration type, its declaration in the class definition can
7474 // specify a constant-initializer which shall be an integral
7475 // constant expression (5.19). In that case, the member can appear
7476 // in integral constant expressions. The member shall still be
7477 // defined in a namespace scope if it is used in the program and the
7478 // namespace scope definition shall not contain an initializer.
7479 //
7480 // We already performed a redefinition check above, but for static
7481 // data members we also need to check whether there was an in-class
7482 // declaration with an initializer.
7483 const VarDecl* PrevInit = 0;
7484 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7485 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7486 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7487 return;
7488 }
7489
Douglas Gregora31040f2010-12-16 01:31:22 +00007490 bool IsDependent = false;
7491 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7492 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7493 VDecl->setInvalidDecl();
7494 return;
7495 }
7496
7497 if (Exprs.get()[I]->isTypeDependent())
7498 IsDependent = true;
7499 }
7500
Douglas Gregor4dffad62010-02-11 22:55:30 +00007501 // If either the declaration has a dependent type or if any of the
7502 // expressions is type-dependent, we represent the initialization
7503 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00007504 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00007505 // Let clients know that initialization was done with a direct initializer.
7506 VDecl->setCXXDirectInitializer(true);
7507
7508 // Store the initialization expressions as a ParenListExpr.
7509 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00007510 VDecl->setInit(new (Context) ParenListExpr(
7511 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7512 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00007513 return;
7514 }
Douglas Gregor90f93822009-12-22 22:17:25 +00007515
7516 // Capture the variable that is being initialized and the style of
7517 // initialization.
7518 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7519
7520 // FIXME: Poor source location information.
7521 InitializationKind Kind
7522 = InitializationKind::CreateDirect(VDecl->getLocation(),
7523 LParenLoc, RParenLoc);
7524
7525 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00007526 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00007527 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00007528 if (Result.isInvalid()) {
7529 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007530 return;
7531 }
John McCallb4eb64d2010-10-08 02:01:28 +00007532
7533 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00007534
Douglas Gregor53c374f2010-12-07 00:41:46 +00007535 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00007536 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007537 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007538
John McCall2998d6b2011-01-19 11:48:09 +00007539 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007540}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00007541
Douglas Gregor39da0b82009-09-09 23:08:42 +00007542/// \brief Given a constructor and the set of arguments provided for the
7543/// constructor, convert the arguments and add any required default arguments
7544/// to form a proper call to this constructor.
7545///
7546/// \returns true if an error occurred, false otherwise.
7547bool
7548Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7549 MultiExprArg ArgsPtr,
7550 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00007551 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00007552 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7553 unsigned NumArgs = ArgsPtr.size();
7554 Expr **Args = (Expr **)ArgsPtr.get();
7555
7556 const FunctionProtoType *Proto
7557 = Constructor->getType()->getAs<FunctionProtoType>();
7558 assert(Proto && "Constructor without a prototype?");
7559 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00007560
7561 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007562 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00007563 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007564 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00007565 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007566
7567 VariadicCallType CallType =
7568 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7569 llvm::SmallVector<Expr *, 8> AllArgs;
7570 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7571 Proto, 0, Args, NumArgs, AllArgs,
7572 CallType);
7573 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7574 ConvertedArgs.push_back(AllArgs[i]);
7575 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00007576}
7577
Anders Carlsson20d45d22009-12-12 00:32:00 +00007578static inline bool
7579CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7580 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007581 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00007582 if (isa<NamespaceDecl>(DC)) {
7583 return SemaRef.Diag(FnDecl->getLocation(),
7584 diag::err_operator_new_delete_declared_in_namespace)
7585 << FnDecl->getDeclName();
7586 }
7587
7588 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00007589 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007590 return SemaRef.Diag(FnDecl->getLocation(),
7591 diag::err_operator_new_delete_declared_static)
7592 << FnDecl->getDeclName();
7593 }
7594
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00007595 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00007596}
7597
Anders Carlsson156c78e2009-12-13 17:53:43 +00007598static inline bool
7599CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7600 CanQualType ExpectedResultType,
7601 CanQualType ExpectedFirstParamType,
7602 unsigned DependentParamTypeDiag,
7603 unsigned InvalidParamTypeDiag) {
7604 QualType ResultType =
7605 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7606
7607 // Check that the result type is not dependent.
7608 if (ResultType->isDependentType())
7609 return SemaRef.Diag(FnDecl->getLocation(),
7610 diag::err_operator_new_delete_dependent_result_type)
7611 << FnDecl->getDeclName() << ExpectedResultType;
7612
7613 // Check that the result type is what we expect.
7614 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7615 return SemaRef.Diag(FnDecl->getLocation(),
7616 diag::err_operator_new_delete_invalid_result_type)
7617 << FnDecl->getDeclName() << ExpectedResultType;
7618
7619 // A function template must have at least 2 parameters.
7620 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7621 return SemaRef.Diag(FnDecl->getLocation(),
7622 diag::err_operator_new_delete_template_too_few_parameters)
7623 << FnDecl->getDeclName();
7624
7625 // The function decl must have at least 1 parameter.
7626 if (FnDecl->getNumParams() == 0)
7627 return SemaRef.Diag(FnDecl->getLocation(),
7628 diag::err_operator_new_delete_too_few_parameters)
7629 << FnDecl->getDeclName();
7630
7631 // Check the the first parameter type is not dependent.
7632 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7633 if (FirstParamType->isDependentType())
7634 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7635 << FnDecl->getDeclName() << ExpectedFirstParamType;
7636
7637 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00007638 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00007639 ExpectedFirstParamType)
7640 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7641 << FnDecl->getDeclName() << ExpectedFirstParamType;
7642
7643 return false;
7644}
7645
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007646static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00007647CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007648 // C++ [basic.stc.dynamic.allocation]p1:
7649 // A program is ill-formed if an allocation function is declared in a
7650 // namespace scope other than global scope or declared static in global
7651 // scope.
7652 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7653 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007654
7655 CanQualType SizeTy =
7656 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7657
7658 // C++ [basic.stc.dynamic.allocation]p1:
7659 // The return type shall be void*. The first parameter shall have type
7660 // std::size_t.
7661 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7662 SizeTy,
7663 diag::err_operator_new_dependent_param_type,
7664 diag::err_operator_new_param_type))
7665 return true;
7666
7667 // C++ [basic.stc.dynamic.allocation]p1:
7668 // The first parameter shall not have an associated default argument.
7669 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007670 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007671 diag::err_operator_new_default_arg)
7672 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7673
7674 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007675}
7676
7677static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007678CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7679 // C++ [basic.stc.dynamic.deallocation]p1:
7680 // A program is ill-formed if deallocation functions are declared in a
7681 // namespace scope other than global scope or declared static in global
7682 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007683 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7684 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007685
7686 // C++ [basic.stc.dynamic.deallocation]p2:
7687 // Each deallocation function shall return void and its first parameter
7688 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007689 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7690 SemaRef.Context.VoidPtrTy,
7691 diag::err_operator_delete_dependent_param_type,
7692 diag::err_operator_delete_param_type))
7693 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007694
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007695 return false;
7696}
7697
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007698/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7699/// of this overloaded operator is well-formed. If so, returns false;
7700/// otherwise, emits appropriate diagnostics and returns true.
7701bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007702 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007703 "Expected an overloaded operator declaration");
7704
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007705 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7706
Mike Stump1eb44332009-09-09 15:08:12 +00007707 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007708 // The allocation and deallocation functions, operator new,
7709 // operator new[], operator delete and operator delete[], are
7710 // described completely in 3.7.3. The attributes and restrictions
7711 // found in the rest of this subclause do not apply to them unless
7712 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007713 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007714 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007715
Anders Carlssona3ccda52009-12-12 00:26:23 +00007716 if (Op == OO_New || Op == OO_Array_New)
7717 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007718
7719 // C++ [over.oper]p6:
7720 // An operator function shall either be a non-static member
7721 // function or be a non-member function and have at least one
7722 // parameter whose type is a class, a reference to a class, an
7723 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007724 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7725 if (MethodDecl->isStatic())
7726 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007727 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007728 } else {
7729 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007730 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7731 ParamEnd = FnDecl->param_end();
7732 Param != ParamEnd; ++Param) {
7733 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007734 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7735 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007736 ClassOrEnumParam = true;
7737 break;
7738 }
7739 }
7740
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007741 if (!ClassOrEnumParam)
7742 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007743 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007744 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007745 }
7746
7747 // C++ [over.oper]p8:
7748 // An operator function cannot have default arguments (8.3.6),
7749 // except where explicitly stated below.
7750 //
Mike Stump1eb44332009-09-09 15:08:12 +00007751 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007752 // (C++ [over.call]p1).
7753 if (Op != OO_Call) {
7754 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7755 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007756 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007757 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007758 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007759 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007760 }
7761 }
7762
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007763 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7764 { false, false, false }
7765#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7766 , { Unary, Binary, MemberOnly }
7767#include "clang/Basic/OperatorKinds.def"
7768 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007769
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007770 bool CanBeUnaryOperator = OperatorUses[Op][0];
7771 bool CanBeBinaryOperator = OperatorUses[Op][1];
7772 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007773
7774 // C++ [over.oper]p8:
7775 // [...] Operator functions cannot have more or fewer parameters
7776 // than the number required for the corresponding operator, as
7777 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007778 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007779 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007780 if (Op != OO_Call &&
7781 ((NumParams == 1 && !CanBeUnaryOperator) ||
7782 (NumParams == 2 && !CanBeBinaryOperator) ||
7783 (NumParams < 1) || (NumParams > 2))) {
7784 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007785 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007786 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007787 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007788 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007789 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007790 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007791 assert(CanBeBinaryOperator &&
7792 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007793 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007794 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007795
Chris Lattner416e46f2008-11-21 07:57:12 +00007796 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007797 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007798 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007799
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007800 // Overloaded operators other than operator() cannot be variadic.
7801 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007802 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007803 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007804 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007805 }
7806
7807 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007808 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7809 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007810 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007811 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007812 }
7813
7814 // C++ [over.inc]p1:
7815 // The user-defined function called operator++ implements the
7816 // prefix and postfix ++ operator. If this function is a member
7817 // function with no parameters, or a non-member function with one
7818 // parameter of class or enumeration type, it defines the prefix
7819 // increment operator ++ for objects of that type. If the function
7820 // is a member function with one parameter (which shall be of type
7821 // int) or a non-member function with two parameters (the second
7822 // of which shall be of type int), it defines the postfix
7823 // increment operator ++ for objects of that type.
7824 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7825 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7826 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007827 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007828 ParamIsInt = BT->getKind() == BuiltinType::Int;
7829
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007830 if (!ParamIsInt)
7831 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007832 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007833 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007834 }
7835
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007836 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007837}
Chris Lattner5a003a42008-12-17 07:09:26 +00007838
Sean Hunta6c058d2010-01-13 09:01:02 +00007839/// CheckLiteralOperatorDeclaration - Check whether the declaration
7840/// of this literal operator function is well-formed. If so, returns
7841/// false; otherwise, emits appropriate diagnostics and returns true.
7842bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7843 DeclContext *DC = FnDecl->getDeclContext();
7844 Decl::Kind Kind = DC->getDeclKind();
7845 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7846 Kind != Decl::LinkageSpec) {
7847 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7848 << FnDecl->getDeclName();
7849 return true;
7850 }
7851
7852 bool Valid = false;
7853
Sean Hunt216c2782010-04-07 23:11:06 +00007854 // template <char...> type operator "" name() is the only valid template
7855 // signature, and the only valid signature with no parameters.
7856 if (FnDecl->param_size() == 0) {
7857 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7858 // Must have only one template parameter
7859 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7860 if (Params->size() == 1) {
7861 NonTypeTemplateParmDecl *PmDecl =
7862 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007863
Sean Hunt216c2782010-04-07 23:11:06 +00007864 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007865 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7866 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7867 Valid = true;
7868 }
7869 }
7870 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007871 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007872 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7873
Sean Hunta6c058d2010-01-13 09:01:02 +00007874 QualType T = (*Param)->getType();
7875
Sean Hunt30019c02010-04-07 22:57:35 +00007876 // unsigned long long int, long double, and any character type are allowed
7877 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007878 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7879 Context.hasSameType(T, Context.LongDoubleTy) ||
7880 Context.hasSameType(T, Context.CharTy) ||
7881 Context.hasSameType(T, Context.WCharTy) ||
7882 Context.hasSameType(T, Context.Char16Ty) ||
7883 Context.hasSameType(T, Context.Char32Ty)) {
7884 if (++Param == FnDecl->param_end())
7885 Valid = true;
7886 goto FinishedParams;
7887 }
7888
Sean Hunt30019c02010-04-07 22:57:35 +00007889 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007890 const PointerType *PT = T->getAs<PointerType>();
7891 if (!PT)
7892 goto FinishedParams;
7893 T = PT->getPointeeType();
7894 if (!T.isConstQualified())
7895 goto FinishedParams;
7896 T = T.getUnqualifiedType();
7897
7898 // Move on to the second parameter;
7899 ++Param;
7900
7901 // If there is no second parameter, the first must be a const char *
7902 if (Param == FnDecl->param_end()) {
7903 if (Context.hasSameType(T, Context.CharTy))
7904 Valid = true;
7905 goto FinishedParams;
7906 }
7907
7908 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7909 // are allowed as the first parameter to a two-parameter function
7910 if (!(Context.hasSameType(T, Context.CharTy) ||
7911 Context.hasSameType(T, Context.WCharTy) ||
7912 Context.hasSameType(T, Context.Char16Ty) ||
7913 Context.hasSameType(T, Context.Char32Ty)))
7914 goto FinishedParams;
7915
7916 // The second and final parameter must be an std::size_t
7917 T = (*Param)->getType().getUnqualifiedType();
7918 if (Context.hasSameType(T, Context.getSizeType()) &&
7919 ++Param == FnDecl->param_end())
7920 Valid = true;
7921 }
7922
7923 // FIXME: This diagnostic is absolutely terrible.
7924FinishedParams:
7925 if (!Valid) {
7926 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7927 << FnDecl->getDeclName();
7928 return true;
7929 }
7930
7931 return false;
7932}
7933
Douglas Gregor074149e2009-01-05 19:45:36 +00007934/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7935/// linkage specification, including the language and (if present)
7936/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7937/// the location of the language string literal, which is provided
7938/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7939/// the '{' brace. Otherwise, this linkage specification does not
7940/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00007941Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7942 SourceLocation LangLoc,
7943 llvm::StringRef Lang,
7944 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00007945 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007946 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007947 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00007948 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00007949 Language = LinkageSpecDecl::lang_cxx;
7950 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00007951 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00007952 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007953 }
Mike Stump1eb44332009-09-09 15:08:12 +00007954
Chris Lattnercc98eac2008-12-17 07:13:27 +00007955 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00007956
Douglas Gregor074149e2009-01-05 19:45:36 +00007957 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00007958 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007959 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00007960 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00007961 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00007962}
7963
Abramo Bagnara35f9a192010-07-30 16:47:02 +00007964/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00007965/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7966/// valid, it's the position of the closing '}' brace in a linkage
7967/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00007968Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007969 Decl *LinkageSpec,
7970 SourceLocation RBraceLoc) {
7971 if (LinkageSpec) {
7972 if (RBraceLoc.isValid()) {
7973 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7974 LSDecl->setRBraceLoc(RBraceLoc);
7975 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007976 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00007977 }
Douglas Gregor074149e2009-01-05 19:45:36 +00007978 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00007979}
7980
Douglas Gregord308e622009-05-18 20:51:54 +00007981/// \brief Perform semantic analysis for the variable declaration that
7982/// occurs within a C++ catch clause, returning the newly-created
7983/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007984VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00007985 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007986 SourceLocation StartLoc,
7987 SourceLocation Loc,
7988 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00007989 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00007990 QualType ExDeclType = TInfo->getType();
7991
Sebastian Redl4b07b292008-12-22 19:15:10 +00007992 // Arrays and functions decay.
7993 if (ExDeclType->isArrayType())
7994 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7995 else if (ExDeclType->isFunctionType())
7996 ExDeclType = Context.getPointerType(ExDeclType);
7997
7998 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7999 // The exception-declaration shall not denote a pointer or reference to an
8000 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008001 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00008002 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00008003 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008004 Invalid = true;
8005 }
Douglas Gregord308e622009-05-18 20:51:54 +00008006
Douglas Gregora2762912010-03-08 01:47:36 +00008007 // GCC allows catching pointers and references to incomplete types
8008 // as an extension; so do we, but we warn by default.
8009
Sebastian Redl4b07b292008-12-22 19:15:10 +00008010 QualType BaseType = ExDeclType;
8011 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008012 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00008013 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00008014 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008015 BaseType = Ptr->getPointeeType();
8016 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00008017 DK = diag::ext_catch_incomplete_ptr;
8018 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008019 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008020 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008021 BaseType = Ref->getPointeeType();
8022 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00008023 DK = diag::ext_catch_incomplete_ref;
8024 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008025 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008026 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00008027 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8028 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00008029 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008030
Mike Stump1eb44332009-09-09 15:08:12 +00008031 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00008032 RequireNonAbstractType(Loc, ExDeclType,
8033 diag::err_abstract_type_in_decl,
8034 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00008035 Invalid = true;
8036
John McCall5a180392010-07-24 00:37:23 +00008037 // Only the non-fragile NeXT runtime currently supports C++ catches
8038 // of ObjC types, and no runtime supports catching ObjC types by value.
8039 if (!Invalid && getLangOptions().ObjC1) {
8040 QualType T = ExDeclType;
8041 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8042 T = RT->getPointeeType();
8043
8044 if (T->isObjCObjectType()) {
8045 Diag(Loc, diag::err_objc_object_catch);
8046 Invalid = true;
8047 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00008048 if (!getLangOptions().ObjCNonFragileABI)
8049 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00008050 }
8051 }
8052
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008053 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8054 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00008055 ExDecl->setExceptionVariable(true);
8056
Douglas Gregorc41b8782011-07-06 18:14:43 +00008057 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00008058 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00008059 // C++ [except.handle]p16:
8060 // The object declared in an exception-declaration or, if the
8061 // exception-declaration does not specify a name, a temporary (12.2) is
8062 // copy-initialized (8.5) from the exception object. [...]
8063 // The object is destroyed when the handler exits, after the destruction
8064 // of any automatic objects initialized within the handler.
8065 //
8066 // We just pretend to initialize the object with itself, then make sure
8067 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00008068 QualType initType = ExDeclType;
8069
8070 InitializedEntity entity =
8071 InitializedEntity::InitializeVariable(ExDecl);
8072 InitializationKind initKind =
8073 InitializationKind::CreateCopy(Loc, SourceLocation());
8074
8075 Expr *opaqueValue =
8076 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8077 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8078 ExprResult result = sequence.Perform(*this, entity, initKind,
8079 MultiExprArg(&opaqueValue, 1));
8080 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00008081 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00008082 else {
8083 // If the constructor used was non-trivial, set this as the
8084 // "initializer".
8085 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8086 if (!construct->getConstructor()->isTrivial()) {
8087 Expr *init = MaybeCreateExprWithCleanups(construct);
8088 ExDecl->setInit(init);
8089 }
8090
8091 // And make sure it's destructable.
8092 FinalizeVarWithDestructor(ExDecl, recordType);
8093 }
Douglas Gregor6d182892010-03-05 23:38:39 +00008094 }
8095 }
8096
Douglas Gregord308e622009-05-18 20:51:54 +00008097 if (Invalid)
8098 ExDecl->setInvalidDecl();
8099
8100 return ExDecl;
8101}
8102
8103/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8104/// handler.
John McCalld226f652010-08-21 09:40:31 +00008105Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00008106 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00008107 bool Invalid = D.isInvalidType();
8108
8109 // Check for unexpanded parameter packs.
8110 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8111 UPPC_ExceptionType)) {
8112 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8113 D.getIdentifierLoc());
8114 Invalid = true;
8115 }
8116
Sebastian Redl4b07b292008-12-22 19:15:10 +00008117 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00008118 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00008119 LookupOrdinaryName,
8120 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008121 // The scope should be freshly made just for us. There is just no way
8122 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00008123 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00008124 if (PrevDecl->isTemplateParameter()) {
8125 // Maybe we will complain about the shadowed template parameter.
8126 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008127 }
8128 }
8129
Chris Lattnereaaebc72009-04-25 08:06:05 +00008130 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008131 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8132 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00008133 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008134 }
8135
Douglas Gregor83cb9422010-09-09 17:09:21 +00008136 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008137 D.getSourceRange().getBegin(),
8138 D.getIdentifierLoc(),
8139 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00008140 if (Invalid)
8141 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00008142
Sebastian Redl4b07b292008-12-22 19:15:10 +00008143 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008144 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00008145 PushOnScopeChains(ExDecl, S);
8146 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008147 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008148
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008149 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00008150 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008151}
Anders Carlssonfb311762009-03-14 00:25:26 +00008152
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008153Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008154 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008155 Expr *AssertMessageExpr_,
8156 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00008157 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00008158
Anders Carlssonc3082412009-03-14 00:33:21 +00008159 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8160 llvm::APSInt Value(32);
8161 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008162 Diag(StaticAssertLoc,
8163 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00008164 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008165 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00008166 }
Anders Carlssonfb311762009-03-14 00:25:26 +00008167
Anders Carlssonc3082412009-03-14 00:33:21 +00008168 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008169 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00008170 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00008171 }
8172 }
Mike Stump1eb44332009-09-09 15:08:12 +00008173
Douglas Gregor399ad972010-12-15 23:55:21 +00008174 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8175 return 0;
8176
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008177 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8178 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008179
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008180 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00008181 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00008182}
Sebastian Redl50de12f2009-03-24 22:27:57 +00008183
Douglas Gregor1d869352010-04-07 16:53:43 +00008184/// \brief Perform semantic analysis of the given friend type declaration.
8185///
8186/// \returns A friend declaration that.
8187FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8188 TypeSourceInfo *TSInfo) {
8189 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8190
8191 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008192 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00008193
Douglas Gregor06245bf2010-04-07 17:57:12 +00008194 if (!getLangOptions().CPlusPlus0x) {
8195 // C++03 [class.friend]p2:
8196 // An elaborated-type-specifier shall be used in a friend declaration
8197 // for a class.*
8198 //
8199 // * The class-key of the elaborated-type-specifier is required.
8200 if (!ActiveTemplateInstantiations.empty()) {
8201 // Do not complain about the form of friend template types during
8202 // template instantiation; we will already have complained when the
8203 // template was declared.
8204 } else if (!T->isElaboratedTypeSpecifier()) {
8205 // If we evaluated the type to a record type, suggest putting
8206 // a tag in front.
8207 if (const RecordType *RT = T->getAs<RecordType>()) {
8208 RecordDecl *RD = RT->getDecl();
8209
8210 std::string InsertionText = std::string(" ") + RD->getKindName();
8211
8212 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8213 << (unsigned) RD->getTagKind()
8214 << T
8215 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8216 InsertionText);
8217 } else {
8218 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8219 << T
8220 << SourceRange(FriendLoc, TypeRange.getEnd());
8221 }
8222 } else if (T->getAs<EnumType>()) {
8223 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00008224 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00008225 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00008226 }
8227 }
8228
Douglas Gregor06245bf2010-04-07 17:57:12 +00008229 // C++0x [class.friend]p3:
8230 // If the type specifier in a friend declaration designates a (possibly
8231 // cv-qualified) class type, that class is declared as a friend; otherwise,
8232 // the friend declaration is ignored.
8233
8234 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8235 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00008236
8237 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8238}
8239
John McCall9a34edb2010-10-19 01:40:49 +00008240/// Handle a friend tag declaration where the scope specifier was
8241/// templated.
8242Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8243 unsigned TagSpec, SourceLocation TagLoc,
8244 CXXScopeSpec &SS,
8245 IdentifierInfo *Name, SourceLocation NameLoc,
8246 AttributeList *Attr,
8247 MultiTemplateParamsArg TempParamLists) {
8248 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8249
8250 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00008251 bool Invalid = false;
8252
8253 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00008254 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00008255 TempParamLists.get(),
8256 TempParamLists.size(),
8257 /*friend*/ true,
8258 isExplicitSpecialization,
8259 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00008260 if (TemplateParams->size() > 0) {
8261 // This is a declaration of a class template.
8262 if (Invalid)
8263 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008264
John McCall9a34edb2010-10-19 01:40:49 +00008265 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8266 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008267 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008268 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008269 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00008270 } else {
8271 // The "template<>" header is extraneous.
8272 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8273 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8274 isExplicitSpecialization = true;
8275 }
8276 }
8277
8278 if (Invalid) return 0;
8279
8280 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8281
8282 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008283 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00008284 if (TempParamLists.get()[I]->size()) {
8285 isAllExplicitSpecializations = false;
8286 break;
8287 }
8288 }
8289
8290 // FIXME: don't ignore attributes.
8291
8292 // If it's explicit specializations all the way down, just forget
8293 // about the template header and build an appropriate non-templated
8294 // friend. TODO: for source fidelity, remember the headers.
8295 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00008296 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00008297 ElaboratedTypeKeyword Keyword
8298 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008299 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00008300 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008301 if (T.isNull())
8302 return 0;
8303
8304 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8305 if (isa<DependentNameType>(T)) {
8306 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8307 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008308 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008309 TL.setNameLoc(NameLoc);
8310 } else {
8311 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8312 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00008313 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008314 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8315 }
8316
8317 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8318 TSI, FriendLoc);
8319 Friend->setAccess(AS_public);
8320 CurContext->addDecl(Friend);
8321 return Friend;
8322 }
8323
8324 // Handle the case of a templated-scope friend class. e.g.
8325 // template <class T> class A<T>::B;
8326 // FIXME: we don't support these right now.
8327 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8328 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8329 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8330 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8331 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008332 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00008333 TL.setNameLoc(NameLoc);
8334
8335 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8336 TSI, FriendLoc);
8337 Friend->setAccess(AS_public);
8338 Friend->setUnsupportedFriend(true);
8339 CurContext->addDecl(Friend);
8340 return Friend;
8341}
8342
8343
John McCalldd4a3b02009-09-16 22:47:08 +00008344/// Handle a friend type declaration. This works in tandem with
8345/// ActOnTag.
8346///
8347/// Notes on friend class templates:
8348///
8349/// We generally treat friend class declarations as if they were
8350/// declaring a class. So, for example, the elaborated type specifier
8351/// in a friend declaration is required to obey the restrictions of a
8352/// class-head (i.e. no typedefs in the scope chain), template
8353/// parameters are required to match up with simple template-ids, &c.
8354/// However, unlike when declaring a template specialization, it's
8355/// okay to refer to a template specialization without an empty
8356/// template parameter declaration, e.g.
8357/// friend class A<T>::B<unsigned>;
8358/// We permit this as a special case; if there are any template
8359/// parameters present at all, require proper matching, i.e.
8360/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00008361Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00008362 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00008363 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00008364
8365 assert(DS.isFriendSpecified());
8366 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8367
John McCalldd4a3b02009-09-16 22:47:08 +00008368 // Try to convert the decl specifier to a type. This works for
8369 // friend templates because ActOnTag never produces a ClassTemplateDecl
8370 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00008371 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00008372 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8373 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00008374 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00008375 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008376
Douglas Gregor6ccab972010-12-16 01:14:37 +00008377 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8378 return 0;
8379
John McCalldd4a3b02009-09-16 22:47:08 +00008380 // This is definitely an error in C++98. It's probably meant to
8381 // be forbidden in C++0x, too, but the specification is just
8382 // poorly written.
8383 //
8384 // The problem is with declarations like the following:
8385 // template <T> friend A<T>::foo;
8386 // where deciding whether a class C is a friend or not now hinges
8387 // on whether there exists an instantiation of A that causes
8388 // 'foo' to equal C. There are restrictions on class-heads
8389 // (which we declare (by fiat) elaborated friend declarations to
8390 // be) that makes this tractable.
8391 //
8392 // FIXME: handle "template <> friend class A<T>;", which
8393 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00008394 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00008395 Diag(Loc, diag::err_tagless_friend_type_template)
8396 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008397 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00008398 }
Douglas Gregor1d869352010-04-07 16:53:43 +00008399
John McCall02cace72009-08-28 07:59:38 +00008400 // C++98 [class.friend]p1: A friend of a class is a function
8401 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00008402 // This is fixed in DR77, which just barely didn't make the C++03
8403 // deadline. It's also a very silly restriction that seriously
8404 // affects inner classes and which nobody else seems to implement;
8405 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00008406 //
8407 // But note that we could warn about it: it's always useless to
8408 // friend one of your own members (it's not, however, worthless to
8409 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00008410
John McCalldd4a3b02009-09-16 22:47:08 +00008411 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00008412 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00008413 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00008414 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00008415 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00008416 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00008417 DS.getFriendSpecLoc());
8418 else
Douglas Gregor1d869352010-04-07 16:53:43 +00008419 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8420
8421 if (!D)
John McCalld226f652010-08-21 09:40:31 +00008422 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00008423
John McCalldd4a3b02009-09-16 22:47:08 +00008424 D->setAccess(AS_public);
8425 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00008426
John McCalld226f652010-08-21 09:40:31 +00008427 return D;
John McCall02cace72009-08-28 07:59:38 +00008428}
8429
John McCall337ec3d2010-10-12 23:13:28 +00008430Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8431 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00008432 const DeclSpec &DS = D.getDeclSpec();
8433
8434 assert(DS.isFriendSpecified());
8435 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8436
8437 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00008438 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8439 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00008440
8441 // C++ [class.friend]p1
8442 // A friend of a class is a function or class....
8443 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00008444 // It *doesn't* see through dependent types, which is correct
8445 // according to [temp.arg.type]p3:
8446 // If a declaration acquires a function type through a
8447 // type dependent on a template-parameter and this causes
8448 // a declaration that does not use the syntactic form of a
8449 // function declarator to have a function type, the program
8450 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00008451 if (!T->isFunctionType()) {
8452 Diag(Loc, diag::err_unexpected_friend);
8453
8454 // It might be worthwhile to try to recover by creating an
8455 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00008456 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008457 }
8458
8459 // C++ [namespace.memdef]p3
8460 // - If a friend declaration in a non-local class first declares a
8461 // class or function, the friend class or function is a member
8462 // of the innermost enclosing namespace.
8463 // - The name of the friend is not found by simple name lookup
8464 // until a matching declaration is provided in that namespace
8465 // scope (either before or after the class declaration granting
8466 // friendship).
8467 // - If a friend function is called, its name may be found by the
8468 // name lookup that considers functions from namespaces and
8469 // classes associated with the types of the function arguments.
8470 // - When looking for a prior declaration of a class or a function
8471 // declared as a friend, scopes outside the innermost enclosing
8472 // namespace scope are not considered.
8473
John McCall337ec3d2010-10-12 23:13:28 +00008474 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00008475 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8476 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00008477 assert(Name);
8478
Douglas Gregor6ccab972010-12-16 01:14:37 +00008479 // Check for unexpanded parameter packs.
8480 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8481 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8482 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8483 return 0;
8484
John McCall67d1a672009-08-06 02:15:43 +00008485 // The context we found the declaration in, or in which we should
8486 // create the declaration.
8487 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00008488 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00008489 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00008490 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00008491
John McCall337ec3d2010-10-12 23:13:28 +00008492 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00008493
John McCall337ec3d2010-10-12 23:13:28 +00008494 // There are four cases here.
8495 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00008496 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00008497 // there as appropriate.
8498 // Recover from invalid scope qualifiers as if they just weren't there.
8499 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00008500 // C++0x [namespace.memdef]p3:
8501 // If the name in a friend declaration is neither qualified nor
8502 // a template-id and the declaration is a function or an
8503 // elaborated-type-specifier, the lookup to determine whether
8504 // the entity has been previously declared shall not consider
8505 // any scopes outside the innermost enclosing namespace.
8506 // C++0x [class.friend]p11:
8507 // If a friend declaration appears in a local class and the name
8508 // specified is an unqualified name, a prior declaration is
8509 // looked up without considering scopes that are outside the
8510 // innermost enclosing non-class scope. For a friend function
8511 // declaration, if there is no prior declaration, the program is
8512 // ill-formed.
8513 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00008514 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00008515
John McCall29ae6e52010-10-13 05:45:15 +00008516 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00008517 DC = CurContext;
8518 while (true) {
8519 // Skip class contexts. If someone can cite chapter and verse
8520 // for this behavior, that would be nice --- it's what GCC and
8521 // EDG do, and it seems like a reasonable intent, but the spec
8522 // really only says that checks for unqualified existing
8523 // declarations should stop at the nearest enclosing namespace,
8524 // not that they should only consider the nearest enclosing
8525 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00008526 while (DC->isRecord())
8527 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00008528
John McCall68263142009-11-18 22:49:29 +00008529 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00008530
8531 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00008532 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00008533 break;
John McCall29ae6e52010-10-13 05:45:15 +00008534
John McCall8a407372010-10-14 22:22:28 +00008535 if (isTemplateId) {
8536 if (isa<TranslationUnitDecl>(DC)) break;
8537 } else {
8538 if (DC->isFileContext()) break;
8539 }
John McCall67d1a672009-08-06 02:15:43 +00008540 DC = DC->getParent();
8541 }
8542
8543 // C++ [class.friend]p1: A friend of a class is a function or
8544 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00008545 // C++0x changes this for both friend types and functions.
8546 // Most C++ 98 compilers do seem to give an error here, so
8547 // we do, too.
John McCall68263142009-11-18 22:49:29 +00008548 if (!Previous.empty() && DC->Equals(CurContext)
8549 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00008550 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00008551
John McCall380aaa42010-10-13 06:22:15 +00008552 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00008553
John McCall337ec3d2010-10-12 23:13:28 +00008554 // - There's a non-dependent scope specifier, in which case we
8555 // compute it and do a previous lookup there for a function
8556 // or function template.
8557 } else if (!SS.getScopeRep()->isDependent()) {
8558 DC = computeDeclContext(SS);
8559 if (!DC) return 0;
8560
8561 if (RequireCompleteDeclContext(SS, DC)) return 0;
8562
8563 LookupQualifiedName(Previous, DC);
8564
8565 // Ignore things found implicitly in the wrong scope.
8566 // TODO: better diagnostics for this case. Suggesting the right
8567 // qualified scope would be nice...
8568 LookupResult::Filter F = Previous.makeFilter();
8569 while (F.hasNext()) {
8570 NamedDecl *D = F.next();
8571 if (!DC->InEnclosingNamespaceSetOf(
8572 D->getDeclContext()->getRedeclContext()))
8573 F.erase();
8574 }
8575 F.done();
8576
8577 if (Previous.empty()) {
8578 D.setInvalidType();
8579 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8580 return 0;
8581 }
8582
8583 // C++ [class.friend]p1: A friend of a class is a function or
8584 // class that is not a member of the class . . .
8585 if (DC->Equals(CurContext))
8586 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8587
8588 // - There's a scope specifier that does not match any template
8589 // parameter lists, in which case we use some arbitrary context,
8590 // create a method or method template, and wait for instantiation.
8591 // - There's a scope specifier that does match some template
8592 // parameter lists, which we don't handle right now.
8593 } else {
8594 DC = CurContext;
8595 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00008596 }
8597
John McCall29ae6e52010-10-13 05:45:15 +00008598 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00008599 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008600 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8601 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8602 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00008603 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008604 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8605 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00008606 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008607 }
John McCall67d1a672009-08-06 02:15:43 +00008608 }
8609
Douglas Gregor182ddf02009-09-28 00:08:27 +00008610 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00008611 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00008612 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00008613 IsDefinition,
8614 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00008615 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00008616
Douglas Gregor182ddf02009-09-28 00:08:27 +00008617 assert(ND->getDeclContext() == DC);
8618 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00008619
John McCallab88d972009-08-31 22:39:49 +00008620 // Add the function declaration to the appropriate lookup tables,
8621 // adjusting the redeclarations list as necessary. We don't
8622 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00008623 //
John McCallab88d972009-08-31 22:39:49 +00008624 // Also update the scope-based lookup if the target context's
8625 // lookup context is in lexical scope.
8626 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008627 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00008628 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008629 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00008630 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008631 }
John McCall02cace72009-08-28 07:59:38 +00008632
8633 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00008634 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00008635 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00008636 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00008637 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00008638
John McCall337ec3d2010-10-12 23:13:28 +00008639 if (ND->isInvalidDecl())
8640 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00008641 else {
8642 FunctionDecl *FD;
8643 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8644 FD = FTD->getTemplatedDecl();
8645 else
8646 FD = cast<FunctionDecl>(ND);
8647
8648 // Mark templated-scope function declarations as unsupported.
8649 if (FD->getNumTemplateParameterLists())
8650 FrD->setUnsupportedFriend(true);
8651 }
John McCall337ec3d2010-10-12 23:13:28 +00008652
John McCalld226f652010-08-21 09:40:31 +00008653 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008654}
8655
John McCalld226f652010-08-21 09:40:31 +00008656void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8657 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008658
Sebastian Redl50de12f2009-03-24 22:27:57 +00008659 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8660 if (!Fn) {
8661 Diag(DelLoc, diag::err_deleted_non_function);
8662 return;
8663 }
8664 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8665 Diag(DelLoc, diag::err_deleted_decl_not_first);
8666 Diag(Prev->getLocation(), diag::note_previous_declaration);
8667 // If the declaration wasn't the first, we delete the function anyway for
8668 // recovery.
8669 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008670 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008671}
Sebastian Redl13e88542009-04-27 21:33:24 +00008672
Sean Hunte4246a62011-05-12 06:15:49 +00008673void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8674 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8675
8676 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00008677 if (MD->getParent()->isDependentType()) {
8678 MD->setDefaulted();
8679 MD->setExplicitlyDefaulted();
8680 return;
8681 }
8682
Sean Hunte4246a62011-05-12 06:15:49 +00008683 CXXSpecialMember Member = getSpecialMember(MD);
8684 if (Member == CXXInvalid) {
8685 Diag(DefaultLoc, diag::err_default_special_members);
8686 return;
8687 }
8688
8689 MD->setDefaulted();
8690 MD->setExplicitlyDefaulted();
8691
Sean Huntcd10dec2011-05-23 23:14:04 +00008692 // If this definition appears within the record, do the checking when
8693 // the record is complete.
8694 const FunctionDecl *Primary = MD;
8695 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8696 // Find the uninstantiated declaration that actually had the '= default'
8697 // on it.
8698 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8699
8700 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00008701 return;
8702
8703 switch (Member) {
8704 case CXXDefaultConstructor: {
8705 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8706 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008707 if (!CD->isInvalidDecl())
8708 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8709 break;
8710 }
8711
8712 case CXXCopyConstructor: {
8713 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8714 CheckExplicitlyDefaultedCopyConstructor(CD);
8715 if (!CD->isInvalidDecl())
8716 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00008717 break;
8718 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008719
Sean Hunt2b188082011-05-14 05:23:28 +00008720 case CXXCopyAssignment: {
8721 CheckExplicitlyDefaultedCopyAssignment(MD);
8722 if (!MD->isInvalidDecl())
8723 DefineImplicitCopyAssignment(DefaultLoc, MD);
8724 break;
8725 }
8726
Sean Huntcb45a0f2011-05-12 22:46:25 +00008727 case CXXDestructor: {
8728 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8729 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008730 if (!DD->isInvalidDecl())
8731 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008732 break;
8733 }
8734
Sean Hunt82713172011-05-25 23:16:36 +00008735 case CXXMoveConstructor:
8736 case CXXMoveAssignment:
8737 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8738 break;
8739
Sean Hunte4246a62011-05-12 06:15:49 +00008740 default:
Sean Hunt2b188082011-05-14 05:23:28 +00008741 // FIXME: Do the rest once we have move functions
Sean Hunte4246a62011-05-12 06:15:49 +00008742 break;
8743 }
8744 } else {
8745 Diag(DefaultLoc, diag::err_default_special_members);
8746 }
8747}
8748
Sebastian Redl13e88542009-04-27 21:33:24 +00008749static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008750 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008751 Stmt *SubStmt = *CI;
8752 if (!SubStmt)
8753 continue;
8754 if (isa<ReturnStmt>(SubStmt))
8755 Self.Diag(SubStmt->getSourceRange().getBegin(),
8756 diag::err_return_in_constructor_handler);
8757 if (!isa<Expr>(SubStmt))
8758 SearchForReturnInStmt(Self, SubStmt);
8759 }
8760}
8761
8762void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8763 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8764 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8765 SearchForReturnInStmt(*this, Handler);
8766 }
8767}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008768
Mike Stump1eb44332009-09-09 15:08:12 +00008769bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008770 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008771 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8772 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008773
Chandler Carruth73857792010-02-15 11:53:20 +00008774 if (Context.hasSameType(NewTy, OldTy) ||
8775 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008776 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008777
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008778 // Check if the return types are covariant
8779 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008780
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008781 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008782 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8783 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008784 NewClassTy = NewPT->getPointeeType();
8785 OldClassTy = OldPT->getPointeeType();
8786 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008787 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8788 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8789 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8790 NewClassTy = NewRT->getPointeeType();
8791 OldClassTy = OldRT->getPointeeType();
8792 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008793 }
8794 }
Mike Stump1eb44332009-09-09 15:08:12 +00008795
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008796 // The return types aren't either both pointers or references to a class type.
8797 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008798 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008799 diag::err_different_return_type_for_overriding_virtual_function)
8800 << New->getDeclName() << NewTy << OldTy;
8801 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008802
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008803 return true;
8804 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008805
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008806 // C++ [class.virtual]p6:
8807 // If the return type of D::f differs from the return type of B::f, the
8808 // class type in the return type of D::f shall be complete at the point of
8809 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008810 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8811 if (!RT->isBeingDefined() &&
8812 RequireCompleteType(New->getLocation(), NewClassTy,
8813 PDiag(diag::err_covariant_return_incomplete)
8814 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008815 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008816 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008817
Douglas Gregora4923eb2009-11-16 21:35:15 +00008818 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008819 // Check if the new class derives from the old class.
8820 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8821 Diag(New->getLocation(),
8822 diag::err_covariant_return_not_derived)
8823 << New->getDeclName() << NewTy << OldTy;
8824 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8825 return true;
8826 }
Mike Stump1eb44332009-09-09 15:08:12 +00008827
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008828 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008829 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008830 diag::err_covariant_return_inaccessible_base,
8831 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8832 // FIXME: Should this point to the return type?
8833 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008834 // FIXME: this note won't trigger for delayed access control
8835 // diagnostics, and it's impossible to get an undelayed error
8836 // here from access control during the original parse because
8837 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008838 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8839 return true;
8840 }
8841 }
Mike Stump1eb44332009-09-09 15:08:12 +00008842
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008843 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008844 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008845 Diag(New->getLocation(),
8846 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008847 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008848 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8849 return true;
8850 };
Mike Stump1eb44332009-09-09 15:08:12 +00008851
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008852
8853 // The new class type must have the same or less qualifiers as the old type.
8854 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8855 Diag(New->getLocation(),
8856 diag::err_covariant_return_type_class_type_more_qualified)
8857 << New->getDeclName() << NewTy << OldTy;
8858 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8859 return true;
8860 };
Mike Stump1eb44332009-09-09 15:08:12 +00008861
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008862 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008863}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008864
Douglas Gregor4ba31362009-12-01 17:24:26 +00008865/// \brief Mark the given method pure.
8866///
8867/// \param Method the method to be marked pure.
8868///
8869/// \param InitRange the source range that covers the "0" initializer.
8870bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008871 SourceLocation EndLoc = InitRange.getEnd();
8872 if (EndLoc.isValid())
8873 Method->setRangeEnd(EndLoc);
8874
Douglas Gregor4ba31362009-12-01 17:24:26 +00008875 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8876 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008877 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008878 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008879
8880 if (!Method->isInvalidDecl())
8881 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8882 << Method->getDeclName() << InitRange;
8883 return true;
8884}
8885
John McCall731ad842009-12-19 09:28:58 +00008886/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8887/// an initializer for the out-of-line declaration 'Dcl'. The scope
8888/// is a fresh scope pushed for just this purpose.
8889///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008890/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8891/// static data member of class X, names should be looked up in the scope of
8892/// class X.
John McCalld226f652010-08-21 09:40:31 +00008893void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008894 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008895 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008896
John McCall731ad842009-12-19 09:28:58 +00008897 // We should only get called for declarations with scope specifiers, like:
8898 // int foo::bar;
8899 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008900 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008901}
8902
8903/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00008904/// initializer for the out-of-line declaration 'D'.
8905void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008906 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008907 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008908
John McCall731ad842009-12-19 09:28:58 +00008909 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008910 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008911}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008912
8913/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8914/// C++ if/switch/while/for statement.
8915/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00008916DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008917 // C++ 6.4p2:
8918 // The declarator shall not specify a function or an array.
8919 // The type-specifier-seq shall not contain typedef and shall not declare a
8920 // new class or enumeration.
8921 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8922 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00008923
8924 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +00008925 if (!Dcl)
8926 return true;
8927
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00008928 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
8929 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008930 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +00008931 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008932 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008933
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00008934 return Dcl;
8935}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00008936
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008937void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8938 bool DefinitionRequired) {
8939 // Ignore any vtable uses in unevaluated operands or for classes that do
8940 // not have a vtable.
8941 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8942 CurContext->isDependentContext() ||
8943 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00008944 return;
8945
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008946 // Try to insert this class into the map.
8947 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8948 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8949 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8950 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00008951 // If we already had an entry, check to see if we are promoting this vtable
8952 // to required a definition. If so, we need to reappend to the VTableUses
8953 // list, since we may have already processed the first entry.
8954 if (DefinitionRequired && !Pos.first->second) {
8955 Pos.first->second = true;
8956 } else {
8957 // Otherwise, we can early exit.
8958 return;
8959 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008960 }
8961
8962 // Local classes need to have their virtual members marked
8963 // immediately. For all other classes, we mark their virtual members
8964 // at the end of the translation unit.
8965 if (Class->isLocalClass())
8966 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00008967 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008968 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00008969}
8970
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008971bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008972 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00008973 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00008974
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008975 // Note: The VTableUses vector could grow as a result of marking
8976 // the members of a class as "used", so we check the size each
8977 // time through the loop and prefer indices (with are stable) to
8978 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00008979 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008980 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00008981 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008982 if (!Class)
8983 continue;
8984
8985 SourceLocation Loc = VTableUses[I].second;
8986
8987 // If this class has a key function, but that key function is
8988 // defined in another translation unit, we don't need to emit the
8989 // vtable even though we're using it.
8990 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00008991 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008992 switch (KeyFunction->getTemplateSpecializationKind()) {
8993 case TSK_Undeclared:
8994 case TSK_ExplicitSpecialization:
8995 case TSK_ExplicitInstantiationDeclaration:
8996 // The key function is in another translation unit.
8997 continue;
8998
8999 case TSK_ExplicitInstantiationDefinition:
9000 case TSK_ImplicitInstantiation:
9001 // We will be instantiating the key function.
9002 break;
9003 }
9004 } else if (!KeyFunction) {
9005 // If we have a class with no key function that is the subject
9006 // of an explicit instantiation declaration, suppress the
9007 // vtable; it will live with the explicit instantiation
9008 // definition.
9009 bool IsExplicitInstantiationDeclaration
9010 = Class->getTemplateSpecializationKind()
9011 == TSK_ExplicitInstantiationDeclaration;
9012 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9013 REnd = Class->redecls_end();
9014 R != REnd; ++R) {
9015 TemplateSpecializationKind TSK
9016 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9017 if (TSK == TSK_ExplicitInstantiationDeclaration)
9018 IsExplicitInstantiationDeclaration = true;
9019 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9020 IsExplicitInstantiationDeclaration = false;
9021 break;
9022 }
9023 }
9024
9025 if (IsExplicitInstantiationDeclaration)
9026 continue;
9027 }
9028
9029 // Mark all of the virtual members of this class as referenced, so
9030 // that we can build a vtable. Then, tell the AST consumer that a
9031 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00009032 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009033 MarkVirtualMembersReferenced(Loc, Class);
9034 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9035 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9036
9037 // Optionally warn if we're emitting a weak vtable.
9038 if (Class->getLinkage() == ExternalLinkage &&
9039 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009040 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009041 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9042 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009043 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009044 VTableUses.clear();
9045
Douglas Gregor78844032011-04-22 22:25:37 +00009046 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009047}
Anders Carlssond6a637f2009-12-07 08:24:59 +00009048
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009049void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9050 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00009051 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9052 e = RD->method_end(); i != e; ++i) {
9053 CXXMethodDecl *MD = *i;
9054
9055 // C++ [basic.def.odr]p2:
9056 // [...] A virtual member function is used if it is not pure. [...]
9057 if (MD->isVirtual() && !MD->isPure())
9058 MarkDeclarationReferenced(Loc, MD);
9059 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009060
9061 // Only classes that have virtual bases need a VTT.
9062 if (RD->getNumVBases() == 0)
9063 return;
9064
9065 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9066 e = RD->bases_end(); i != e; ++i) {
9067 const CXXRecordDecl *Base =
9068 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009069 if (Base->getNumVBases() == 0)
9070 continue;
9071 MarkVirtualMembersReferenced(Loc, Base);
9072 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00009073}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009074
9075/// SetIvarInitializers - This routine builds initialization ASTs for the
9076/// Objective-C implementation whose ivars need be initialized.
9077void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9078 if (!getLangOptions().CPlusPlus)
9079 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00009080 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009081 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9082 CollectIvarsToConstructOrDestruct(OID, ivars);
9083 if (ivars.empty())
9084 return;
Sean Huntcbb67482011-01-08 20:30:50 +00009085 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009086 for (unsigned i = 0; i < ivars.size(); i++) {
9087 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009088 if (Field->isInvalidDecl())
9089 continue;
9090
Sean Huntcbb67482011-01-08 20:30:50 +00009091 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009092 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9093 InitializationKind InitKind =
9094 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9095
9096 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009097 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00009098 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00009099 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009100 // Note, MemberInit could actually come back empty if no initialization
9101 // is required (e.g., because it would call a trivial default constructor)
9102 if (!MemberInit.get() || MemberInit.isInvalid())
9103 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00009104
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009105 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00009106 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9107 SourceLocation(),
9108 MemberInit.takeAs<Expr>(),
9109 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009110 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009111
9112 // Be sure that the destructor is accessible and is marked as referenced.
9113 if (const RecordType *RecordTy
9114 = Context.getBaseElementType(Field->getType())
9115 ->getAs<RecordType>()) {
9116 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00009117 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009118 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9119 CheckDestructorAccess(Field->getLocation(), Destructor,
9120 PDiag(diag::err_access_dtor_ivar)
9121 << Context.getBaseElementType(Field->getType()));
9122 }
9123 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009124 }
9125 ObjCImplementation->setIvarInitializers(Context,
9126 AllToInit.data(), AllToInit.size());
9127 }
9128}
Sean Huntfe57eef2011-05-04 05:57:24 +00009129
Sean Huntebcbe1d2011-05-04 23:29:54 +00009130static
9131void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9132 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9133 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9134 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9135 Sema &S) {
9136 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9137 CE = Current.end();
9138 if (Ctor->isInvalidDecl())
9139 return;
9140
9141 const FunctionDecl *FNTarget = 0;
9142 CXXConstructorDecl *Target;
9143
9144 // We ignore the result here since if we don't have a body, Target will be
9145 // null below.
9146 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9147 Target
9148= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9149
9150 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9151 // Avoid dereferencing a null pointer here.
9152 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9153
9154 if (!Current.insert(Canonical))
9155 return;
9156
9157 // We know that beyond here, we aren't chaining into a cycle.
9158 if (!Target || !Target->isDelegatingConstructor() ||
9159 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9160 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9161 Valid.insert(*CI);
9162 Current.clear();
9163 // We've hit a cycle.
9164 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9165 Current.count(TCanonical)) {
9166 // If we haven't diagnosed this cycle yet, do so now.
9167 if (!Invalid.count(TCanonical)) {
9168 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00009169 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00009170 << Ctor;
9171
9172 // Don't add a note for a function delegating directo to itself.
9173 if (TCanonical != Canonical)
9174 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9175
9176 CXXConstructorDecl *C = Target;
9177 while (C->getCanonicalDecl() != Canonical) {
9178 (void)C->getTargetConstructor()->hasBody(FNTarget);
9179 assert(FNTarget && "Ctor cycle through bodiless function");
9180
9181 C
9182 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9183 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9184 }
9185 }
9186
9187 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9188 Invalid.insert(*CI);
9189 Current.clear();
9190 } else {
9191 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9192 }
9193}
9194
9195
Sean Huntfe57eef2011-05-04 05:57:24 +00009196void Sema::CheckDelegatingCtorCycles() {
9197 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9198
Sean Huntebcbe1d2011-05-04 23:29:54 +00009199 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9200 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00009201
9202 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00009203 I = DelegatingCtorDecls.begin(),
9204 E = DelegatingCtorDecls.end();
9205 I != E; ++I) {
9206 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00009207 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00009208
9209 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9210 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00009211}