blob: 09597d2ef1fb54432ef7730cf08cf1926a0a4e1b [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:
188 // [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
191 // 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
John McCall4bde1e12010-06-04 08:34:12 +00001082 bool isFunc = false;
1083 if (D.isFunctionDeclarator())
1084 isFunc = true;
1085 else if (D.getNumTypeObjects() == 0 &&
1086 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +00001087 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +00001088 isFunc = TDType->isFunctionType();
1089 }
1090
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001091 // C++ 9.2p6: A member shall not be declared to have automatic storage
1092 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001093 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1094 // data members and cannot be applied to names declared const or static,
1095 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001096 switch (DS.getStorageClassSpec()) {
1097 case DeclSpec::SCS_unspecified:
1098 case DeclSpec::SCS_typedef:
1099 case DeclSpec::SCS_static:
1100 // FALL THROUGH.
1101 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001102 case DeclSpec::SCS_mutable:
1103 if (isFunc) {
1104 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001105 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001106 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001107 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Sebastian Redla11f42f2008-11-17 23:24:37 +00001109 // FIXME: It would be nicer if the keyword was ignored only for this
1110 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001111 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001112 }
1113 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001114 default:
1115 if (DS.getStorageClassSpecLoc().isValid())
1116 Diag(DS.getStorageClassSpecLoc(),
1117 diag::err_storageclass_invalid_for_member);
1118 else
1119 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1120 D.getMutableDeclSpec().ClearStorageClassSpecs();
1121 }
1122
Sebastian Redl669d5d72008-11-14 23:42:31 +00001123 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1124 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001125 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001126
1127 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001128 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001129 CXXScopeSpec &SS = D.getCXXScopeSpec();
1130
Douglas Gregor922fff22010-10-13 22:19:53 +00001131 if (SS.isSet() && !SS.isInvalid()) {
1132 // The user provided a superfluous scope specifier inside a class
1133 // definition:
1134 //
1135 // class X {
1136 // int X::member;
1137 // };
1138 DeclContext *DC = 0;
1139 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1140 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1141 << Name << FixItHint::CreateRemoval(SS.getRange());
1142 else
1143 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1144 << Name << SS.getRange();
1145
1146 SS.clear();
1147 }
1148
Douglas Gregor37b372b2009-08-20 22:52:58 +00001149 // FIXME: Check for template parameters!
Douglas Gregor56c04582010-12-16 00:46:58 +00001150 // FIXME: Check that the name is an identifier!
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001151 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001152 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001153 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001154 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001155 assert(!HasDeferredInit);
1156
Sean Hunte4246a62011-05-12 06:15:49 +00001157 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001158 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001159 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001160 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001161
1162 // Non-instance-fields can't have a bitfield.
1163 if (BitWidth) {
1164 if (Member->isInvalidDecl()) {
1165 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001166 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001167 // C++ 9.6p3: A bit-field shall not be a static member.
1168 // "static member 'A' cannot be a bit-field"
1169 Diag(Loc, diag::err_static_not_bitfield)
1170 << Name << BitWidth->getSourceRange();
1171 } else if (isa<TypedefDecl>(Member)) {
1172 // "typedef member 'x' cannot be a bit-field"
1173 Diag(Loc, diag::err_typedef_not_bitfield)
1174 << Name << BitWidth->getSourceRange();
1175 } else {
1176 // A function typedef ("typedef int f(); f a;").
1177 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1178 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001179 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001180 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001181 }
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattner8b963ef2009-03-05 23:01:03 +00001183 BitWidth = 0;
1184 Member->setInvalidDecl();
1185 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001186
1187 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Douglas Gregor37b372b2009-08-20 22:52:58 +00001189 // If we have declared a member function template, set the access of the
1190 // templated declaration as well.
1191 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1192 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001193 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001194
Anders Carlssonaae5af22011-01-20 04:34:22 +00001195 if (VS.isOverrideSpecified()) {
1196 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1197 if (!MD || !MD->isVirtual()) {
1198 Diag(Member->getLocStart(),
1199 diag::override_keyword_only_allowed_on_virtual_member_functions)
1200 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001201 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001202 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001203 }
1204 if (VS.isFinalSpecified()) {
1205 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1206 if (!MD || !MD->isVirtual()) {
1207 Diag(Member->getLocStart(),
1208 diag::override_keyword_only_allowed_on_virtual_member_functions)
1209 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001210 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001211 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001212 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001213
Douglas Gregorf5251602011-03-08 17:10:18 +00001214 if (VS.getLastLocation().isValid()) {
1215 // Update the end location of a method that has a virt-specifiers.
1216 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1217 MD->setRangeEnd(VS.getLastLocation());
1218 }
1219
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001220 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001221
Douglas Gregor10bd3682008-11-17 22:58:34 +00001222 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001223
Douglas Gregor021c3b32009-03-11 23:00:04 +00001224 if (Init)
Richard Smith34b41d92011-02-20 03:19:35 +00001225 AddInitializerToDecl(Member, Init, false,
1226 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith7a614d82011-06-11 17:19:42 +00001227 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1228 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1229 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1230 // data member if a brace-or-equal-initializer is provided.
1231 Diag(Loc, diag::err_auto_var_requires_init)
1232 << Name << cast<ValueDecl>(Member)->getType();
1233 Member->setInvalidDecl();
1234 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001235
Richard Smith483b9f32011-02-21 20:05:19 +00001236 FinalizeDeclaration(Member);
1237
John McCallb25b2952011-02-15 07:12:36 +00001238 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001239 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001240 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001241}
1242
Richard Smith7a614d82011-06-11 17:19:42 +00001243/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1244/// in-class initializer for a non-static C++ class member. Such parsing
1245/// is deferred until the class is complete.
1246void
1247Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1248 Expr *InitExpr) {
1249 FieldDecl *FD = cast<FieldDecl>(D);
1250
1251 if (!InitExpr) {
1252 FD->setInvalidDecl();
1253 FD->removeInClassInitializer();
1254 return;
1255 }
1256
1257 ExprResult Init = InitExpr;
1258 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1259 // FIXME: if there is no EqualLoc, this is list-initialization.
1260 Init = PerformCopyInitialization(
1261 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1262 if (Init.isInvalid()) {
1263 FD->setInvalidDecl();
1264 return;
1265 }
1266
1267 CheckImplicitConversions(Init.get(), EqualLoc);
1268 }
1269
1270 // C++0x [class.base.init]p7:
1271 // The initialization of each base and member constitutes a
1272 // full-expression.
1273 Init = MaybeCreateExprWithCleanups(Init);
1274 if (Init.isInvalid()) {
1275 FD->setInvalidDecl();
1276 return;
1277 }
1278
1279 InitExpr = Init.release();
1280
1281 FD->setInClassInitializer(InitExpr);
1282}
1283
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001284/// \brief Find the direct and/or virtual base specifiers that
1285/// correspond to the given base type, for use in base initialization
1286/// within a constructor.
1287static bool FindBaseInitializer(Sema &SemaRef,
1288 CXXRecordDecl *ClassDecl,
1289 QualType BaseType,
1290 const CXXBaseSpecifier *&DirectBaseSpec,
1291 const CXXBaseSpecifier *&VirtualBaseSpec) {
1292 // First, check for a direct base class.
1293 DirectBaseSpec = 0;
1294 for (CXXRecordDecl::base_class_const_iterator Base
1295 = ClassDecl->bases_begin();
1296 Base != ClassDecl->bases_end(); ++Base) {
1297 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1298 // We found a direct base of this type. That's what we're
1299 // initializing.
1300 DirectBaseSpec = &*Base;
1301 break;
1302 }
1303 }
1304
1305 // Check for a virtual base class.
1306 // FIXME: We might be able to short-circuit this if we know in advance that
1307 // there are no virtual bases.
1308 VirtualBaseSpec = 0;
1309 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1310 // We haven't found a base yet; search the class hierarchy for a
1311 // virtual base class.
1312 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1313 /*DetectVirtual=*/false);
1314 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1315 BaseType, Paths)) {
1316 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1317 Path != Paths.end(); ++Path) {
1318 if (Path->back().Base->isVirtual()) {
1319 VirtualBaseSpec = Path->back().Base;
1320 break;
1321 }
1322 }
1323 }
1324 }
1325
1326 return DirectBaseSpec || VirtualBaseSpec;
1327}
1328
Douglas Gregor7ad83902008-11-05 04:29:56 +00001329/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001330MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001331Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001332 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001333 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001334 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001335 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001336 SourceLocation IdLoc,
1337 SourceLocation LParenLoc,
1338 ExprTy **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001339 SourceLocation RParenLoc,
1340 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001341 if (!ConstructorD)
1342 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001344 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001345
1346 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001347 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001348 if (!Constructor) {
1349 // The user wrote a constructor initializer on a function that is
1350 // not a C++ constructor. Ignore the error for now, because we may
1351 // have more member initializers coming; we'll diagnose it just
1352 // once in ActOnMemInitializers.
1353 return true;
1354 }
1355
1356 CXXRecordDecl *ClassDecl = Constructor->getParent();
1357
1358 // C++ [class.base.init]p2:
1359 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001360 // constructor's class and, if not found in that scope, are looked
1361 // up in the scope containing the constructor's definition.
1362 // [Note: if the constructor's class contains a member with the
1363 // same name as a direct or virtual base class of the class, a
1364 // mem-initializer-id naming the member or base class and composed
1365 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001366 // mem-initializer-id for the hidden base class may be specified
1367 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001368 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001369 // Look for a member, first.
1370 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001371 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001372 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001373 if (Result.first != Result.second) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001374 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet87c2e122010-11-21 06:08:52 +00001375
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001376 if (Member) {
1377 if (EllipsisLoc.isValid())
1378 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1379 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1380
Francois Pichet00eb3f92010-12-04 09:14:42 +00001381 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001382 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001383 }
1384
Francois Pichet00eb3f92010-12-04 09:14:42 +00001385 // Handle anonymous union case.
1386 if (IndirectFieldDecl* IndirectField
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001387 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1388 if (EllipsisLoc.isValid())
1389 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1390 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1391
Francois Pichet00eb3f92010-12-04 09:14:42 +00001392 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1393 NumArgs, IdLoc,
1394 LParenLoc, RParenLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001395 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001396 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001397 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001398 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001399 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001400 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001401
1402 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001403 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001404 } else {
1405 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1406 LookupParsedName(R, S, &SS);
1407
1408 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1409 if (!TyD) {
1410 if (R.isAmbiguous()) return true;
1411
John McCallfd225442010-04-09 19:01:14 +00001412 // We don't want access-control diagnostics here.
1413 R.suppressDiagnostics();
1414
Douglas Gregor7a886e12010-01-19 06:46:48 +00001415 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1416 bool NotUnknownSpecialization = false;
1417 DeclContext *DC = computeDeclContext(SS, false);
1418 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1419 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1420
1421 if (!NotUnknownSpecialization) {
1422 // When the scope specifier can refer to a member of an unknown
1423 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001424 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1425 SS.getWithLocInContext(Context),
1426 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001427 if (BaseType.isNull())
1428 return true;
1429
Douglas Gregor7a886e12010-01-19 06:46:48 +00001430 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001431 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001432 }
1433 }
1434
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001435 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001436 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001437 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1438 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001439 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001440 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001441 // We have found a non-static data member with a similar
1442 // name to what was typed; complain and initialize that
1443 // member.
1444 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1445 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001446 << FixItHint::CreateReplacement(R.getNameLoc(),
1447 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001448 Diag(Member->getLocation(), diag::note_previous_decl)
1449 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001450
1451 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1452 LParenLoc, RParenLoc);
1453 }
1454 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1455 const CXXBaseSpecifier *DirectBaseSpec;
1456 const CXXBaseSpecifier *VirtualBaseSpec;
1457 if (FindBaseInitializer(*this, ClassDecl,
1458 Context.getTypeDeclType(Type),
1459 DirectBaseSpec, VirtualBaseSpec)) {
1460 // We have found a direct or virtual base class with a
1461 // similar name to what was typed; complain and initialize
1462 // that base class.
1463 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1464 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001465 << FixItHint::CreateReplacement(R.getNameLoc(),
1466 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001467
1468 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1469 : VirtualBaseSpec;
1470 Diag(BaseSpec->getSourceRange().getBegin(),
1471 diag::note_base_class_specified_here)
1472 << BaseSpec->getType()
1473 << BaseSpec->getSourceRange();
1474
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001475 TyD = Type;
1476 }
1477 }
1478 }
1479
Douglas Gregor7a886e12010-01-19 06:46:48 +00001480 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001481 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1482 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1483 return true;
1484 }
John McCall2b194412009-12-21 10:41:20 +00001485 }
1486
Douglas Gregor7a886e12010-01-19 06:46:48 +00001487 if (BaseType.isNull()) {
1488 BaseType = Context.getTypeDeclType(TyD);
1489 if (SS.isSet()) {
1490 NestedNameSpecifier *Qualifier =
1491 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001492
Douglas Gregor7a886e12010-01-19 06:46:48 +00001493 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001494 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001495 }
John McCall2b194412009-12-21 10:41:20 +00001496 }
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
John McCalla93c9342009-12-07 02:54:59 +00001499 if (!TInfo)
1500 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001501
John McCalla93c9342009-12-07 02:54:59 +00001502 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001503 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001504}
1505
John McCallb4190042009-11-04 23:02:40 +00001506/// Checks an initializer expression for use of uninitialized fields, such as
1507/// containing the field that is being initialized. Returns true if there is an
1508/// uninitialized field was used an updates the SourceLocation parameter; false
1509/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001510static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00001511 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00001512 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001513 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1514
Nick Lewycky43ad1822010-06-15 07:32:55 +00001515 if (isa<CallExpr>(S)) {
1516 // Do not descend into function calls or constructors, as the use
1517 // of an uninitialized field may be valid. One would have to inspect
1518 // the contents of the function/ctor to determine if it is safe or not.
1519 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1520 // may be safe, depending on what the function/ctor does.
1521 return false;
1522 }
1523 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1524 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001525
1526 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1527 // The member expression points to a static data member.
1528 assert(VD->isStaticDataMember() &&
1529 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00001530 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00001531 return false;
1532 }
1533
1534 if (isa<EnumConstantDecl>(RhsField)) {
1535 // The member expression points to an enum.
1536 return false;
1537 }
1538
John McCallb4190042009-11-04 23:02:40 +00001539 if (RhsField == LhsField) {
1540 // Initializing a field with itself. Throw a warning.
1541 // But wait; there are exceptions!
1542 // Exception #1: The field may not belong to this record.
1543 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001544 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001545 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1546 // Even though the field matches, it does not belong to this record.
1547 return false;
1548 }
1549 // None of the exceptions triggered; return true to indicate an
1550 // uninitialized field was used.
1551 *L = ME->getMemberLoc();
1552 return true;
1553 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001554 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00001555 // sizeof/alignof doesn't reference contents, do not warn.
1556 return false;
1557 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1558 // address-of doesn't reference contents (the pointer may be dereferenced
1559 // in the same expression but it would be rare; and weird).
1560 if (UOE->getOpcode() == UO_AddrOf)
1561 return false;
John McCallb4190042009-11-04 23:02:40 +00001562 }
John McCall7502c1d2011-02-13 04:07:26 +00001563 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00001564 if (!*it) {
1565 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001566 continue;
1567 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001568 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1569 return true;
John McCallb4190042009-11-04 23:02:40 +00001570 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001571 return false;
John McCallb4190042009-11-04 23:02:40 +00001572}
1573
John McCallf312b1e2010-08-26 23:41:50 +00001574MemInitResult
Chandler Carruth894aed92010-12-06 09:23:57 +00001575Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman59c04372009-07-29 19:44:27 +00001576 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001577 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001578 SourceLocation RParenLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00001579 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1580 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1581 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00001582 "Member must be a FieldDecl or IndirectFieldDecl");
1583
Douglas Gregor464b2f02010-11-05 22:21:31 +00001584 if (Member->isInvalidDecl())
1585 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00001586
John McCallb4190042009-11-04 23:02:40 +00001587 // Diagnose value-uses of fields to initialize themselves, e.g.
1588 // foo(foo)
1589 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001590 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001591 for (unsigned i = 0; i < NumArgs; ++i) {
1592 SourceLocation L;
1593 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1594 // FIXME: Return true in the case when other fields are used before being
1595 // uninitialized. For example, let this field be the i'th field. When
1596 // initializing the i'th field, throw a warning if any of the >= i'th
1597 // fields are used, as they are not yet initialized.
1598 // Right now we are only handling the case where the i'th field uses
1599 // itself in its initializer.
1600 Diag(L, diag::warn_field_is_uninit);
1601 }
1602 }
1603
Eli Friedman59c04372009-07-29 19:44:27 +00001604 bool HasDependentArg = false;
1605 for (unsigned i = 0; i < NumArgs; i++)
1606 HasDependentArg |= Args[i]->isTypeDependent();
1607
Chandler Carruth894aed92010-12-06 09:23:57 +00001608 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001609 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610 // Can't check initialization for a member of dependent type or when
1611 // any of the arguments are type-dependent expressions.
Chandler Carruth894aed92010-12-06 09:23:57 +00001612 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1613 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001614
John McCallf85e1932011-06-15 23:02:42 +00001615 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00001616 } else {
1617 // Initialize the member.
1618 InitializedEntity MemberEntity =
1619 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1620 : InitializedEntity::InitializeMember(IndirectMember, 0);
1621 InitializationKind Kind =
1622 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallb4eb64d2010-10-08 02:01:28 +00001623
Chandler Carruth894aed92010-12-06 09:23:57 +00001624 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1625
1626 ExprResult MemberInit =
1627 InitSeq.Perform(*this, MemberEntity, Kind,
1628 MultiExprArg(*this, Args, NumArgs), 0);
1629 if (MemberInit.isInvalid())
1630 return true;
1631
1632 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1633
1634 // C++0x [class.base.init]p7:
1635 // The initialization of each base and member constitutes a
1636 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001637 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00001638 if (MemberInit.isInvalid())
1639 return true;
1640
1641 // If we are in a dependent context, template instantiation will
1642 // perform this type-checking again. Just save the arguments that we
1643 // received in a ParenListExpr.
1644 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1645 // of the information that we have about the member
1646 // initializer. However, deconstructing the ASTs is a dicey process,
1647 // and this approach is far more likely to get the corner cases right.
1648 if (CurContext->isDependentContext())
1649 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1650 RParenLoc);
1651 else
1652 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001653 }
1654
Chandler Carruth894aed92010-12-06 09:23:57 +00001655 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00001656 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001657 IdLoc, LParenLoc, Init,
1658 RParenLoc);
1659 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00001660 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruth894aed92010-12-06 09:23:57 +00001661 IdLoc, LParenLoc, Init,
1662 RParenLoc);
1663 }
Eli Friedman59c04372009-07-29 19:44:27 +00001664}
1665
John McCallf312b1e2010-08-26 23:41:50 +00001666MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00001667Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1668 Expr **Args, unsigned NumArgs,
Sean Hunt41717662011-02-26 19:13:13 +00001669 SourceLocation NameLoc,
Sean Hunt97fcc492011-01-08 19:20:43 +00001670 SourceLocation LParenLoc,
1671 SourceLocation RParenLoc,
Sean Hunt41717662011-02-26 19:13:13 +00001672 CXXRecordDecl *ClassDecl) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001673 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1674 if (!LangOpts.CPlusPlus0x)
1675 return Diag(Loc, diag::err_delegation_0x_only)
1676 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00001677
Sean Hunt41717662011-02-26 19:13:13 +00001678 // Initialize the object.
1679 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1680 QualType(ClassDecl->getTypeForDecl(), 0));
1681 InitializationKind Kind =
1682 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1683
1684 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1685
1686 ExprResult DelegationInit =
1687 InitSeq.Perform(*this, DelegationEntity, Kind,
1688 MultiExprArg(*this, Args, NumArgs), 0);
1689 if (DelegationInit.isInvalid())
1690 return true;
1691
1692 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Sean Huntfe57eef2011-05-04 05:57:24 +00001693 CXXConstructorDecl *Constructor
1694 = ConExpr->getConstructor();
Sean Hunt41717662011-02-26 19:13:13 +00001695 assert(Constructor && "Delegating constructor with no target?");
1696
1697 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1698
1699 // C++0x [class.base.init]p7:
1700 // The initialization of each base and member constitutes a
1701 // full-expression.
1702 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1703 if (DelegationInit.isInvalid())
1704 return true;
1705
1706 // If we are in a dependent context, template instantiation will
1707 // perform this type-checking again. Just save the arguments that we
1708 // received in a ParenListExpr.
1709 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1710 // of the information that we have about the base
1711 // initializer. However, deconstructing the ASTs is a dicey process,
1712 // and this approach is far more likely to get the corner cases right.
1713 if (CurContext->isDependentContext()) {
1714 ExprResult Init
1715 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1716 NumArgs, RParenLoc));
1717 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1718 Constructor, Init.takeAs<Expr>(),
1719 RParenLoc);
1720 }
1721
1722 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1723 DelegationInit.takeAs<Expr>(),
1724 RParenLoc);
Sean Hunt97fcc492011-01-08 19:20:43 +00001725}
1726
1727MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001728Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001729 Expr **Args, unsigned NumArgs,
1730 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001731 CXXRecordDecl *ClassDecl,
1732 SourceLocation EllipsisLoc) {
Eli Friedman59c04372009-07-29 19:44:27 +00001733 bool HasDependentArg = false;
1734 for (unsigned i = 0; i < NumArgs; i++)
1735 HasDependentArg |= Args[i]->isTypeDependent();
1736
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001737 SourceLocation BaseLoc
1738 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1739
1740 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1741 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1742 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1743
1744 // C++ [class.base.init]p2:
1745 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00001746 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001747 // of that class, the mem-initializer is ill-formed. A
1748 // mem-initializer-list can initialize a base class using any
1749 // name that denotes that base class type.
1750 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1751
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001752 if (EllipsisLoc.isValid()) {
1753 // This is a pack expansion.
1754 if (!BaseType->containsUnexpandedParameterPack()) {
1755 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1756 << SourceRange(BaseLoc, RParenLoc);
1757
1758 EllipsisLoc = SourceLocation();
1759 }
1760 } else {
1761 // Check for any unexpanded parameter packs.
1762 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1763 return true;
1764
1765 for (unsigned I = 0; I != NumArgs; ++I)
1766 if (DiagnoseUnexpandedParameterPack(Args[I]))
1767 return true;
1768 }
1769
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001770 // Check for direct and virtual base classes.
1771 const CXXBaseSpecifier *DirectBaseSpec = 0;
1772 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1773 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00001774 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1775 BaseType))
Sean Hunt41717662011-02-26 19:13:13 +00001776 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1777 LParenLoc, RParenLoc, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00001778
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001779 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1780 VirtualBaseSpec);
1781
1782 // C++ [base.class.init]p2:
1783 // Unless the mem-initializer-id names a nonstatic data member of the
1784 // constructor's class or a direct or virtual base of that class, the
1785 // mem-initializer is ill-formed.
1786 if (!DirectBaseSpec && !VirtualBaseSpec) {
1787 // If the class has any dependent bases, then it's possible that
1788 // one of those types will resolve to the same type as
1789 // BaseType. Therefore, just treat this as a dependent base
1790 // class initialization. FIXME: Should we try to check the
1791 // initialization anyway? It seems odd.
1792 if (ClassDecl->hasAnyDependentBases())
1793 Dependent = true;
1794 else
1795 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1796 << BaseType << Context.getTypeDeclType(ClassDecl)
1797 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1798 }
1799 }
1800
1801 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001802 // Can't check initialization for a base of dependent type or when
1803 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001804 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001805 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1806 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001807
John McCallf85e1932011-06-15 23:02:42 +00001808 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Sean Huntcbb67482011-01-08 20:30:50 +00001810 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001811 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001812 LParenLoc,
1813 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001814 RParenLoc,
1815 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001816 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001817
1818 // C++ [base.class.init]p2:
1819 // If a mem-initializer-id is ambiguous because it designates both
1820 // a direct non-virtual base class and an inherited virtual base
1821 // class, the mem-initializer is ill-formed.
1822 if (DirectBaseSpec && VirtualBaseSpec)
1823 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001824 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001825
1826 CXXBaseSpecifier *BaseSpec
1827 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1828 if (!BaseSpec)
1829 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1830
1831 // Initialize the base.
1832 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001833 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001834 InitializationKind Kind =
1835 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1836
1837 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1838
John McCall60d7b3a2010-08-24 06:29:42 +00001839 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001840 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001841 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001842 if (BaseInit.isInvalid())
1843 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00001844
1845 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001846
1847 // C++0x [class.base.init]p7:
1848 // The initialization of each base and member constitutes a
1849 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00001850 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001851 if (BaseInit.isInvalid())
1852 return true;
1853
1854 // If we are in a dependent context, template instantiation will
1855 // perform this type-checking again. Just save the arguments that we
1856 // received in a ParenListExpr.
1857 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1858 // of the information that we have about the base
1859 // initializer. However, deconstructing the ASTs is a dicey process,
1860 // and this approach is far more likely to get the corner cases right.
1861 if (CurContext->isDependentContext()) {
John McCall60d7b3a2010-08-24 06:29:42 +00001862 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001863 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1864 RParenLoc));
Sean Huntcbb67482011-01-08 20:30:50 +00001865 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001866 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001867 LParenLoc,
1868 Init.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001869 RParenLoc,
1870 EllipsisLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001871 }
1872
Sean Huntcbb67482011-01-08 20:30:50 +00001873 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001874 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001875 LParenLoc,
1876 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001877 RParenLoc,
1878 EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001879}
1880
Anders Carlssone5ef7402010-04-23 03:10:23 +00001881/// ImplicitInitializerKind - How an implicit base or member initializer should
1882/// initialize its base or member.
1883enum ImplicitInitializerKind {
1884 IIK_Default,
1885 IIK_Copy,
1886 IIK_Move
1887};
1888
Anders Carlssondefefd22010-04-23 02:00:02 +00001889static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001890BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001891 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001892 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001893 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00001894 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001895 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001896 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1897 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001898
John McCall60d7b3a2010-08-24 06:29:42 +00001899 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001900
1901 switch (ImplicitInitKind) {
1902 case IIK_Default: {
1903 InitializationKind InitKind
1904 = InitializationKind::CreateDefault(Constructor->getLocation());
1905 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1906 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001907 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001908 break;
1909 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001910
Anders Carlssone5ef7402010-04-23 03:10:23 +00001911 case IIK_Copy: {
1912 ParmVarDecl *Param = Constructor->getParamDecl(0);
1913 QualType ParamType = Param->getType().getNonReferenceType();
1914
1915 Expr *CopyCtorArg =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001916 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001917 Constructor->getLocation(), ParamType,
1918 VK_LValue, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001919
Anders Carlssonc7957502010-04-24 22:02:54 +00001920 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001921 QualType ArgTy =
1922 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1923 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001924
1925 CXXCastPath BasePath;
1926 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00001927 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1928 CK_UncheckedDerivedToBase,
1929 VK_LValue, &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00001930
Anders Carlssone5ef7402010-04-23 03:10:23 +00001931 InitializationKind InitKind
1932 = InitializationKind::CreateDirect(Constructor->getLocation(),
1933 SourceLocation(), SourceLocation());
1934 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1935 &CopyCtorArg, 1);
1936 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001937 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001938 break;
1939 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001940
Anders Carlssone5ef7402010-04-23 03:10:23 +00001941 case IIK_Move:
1942 assert(false && "Unhandled initializer kind!");
1943 }
John McCall9ae2f072010-08-23 23:25:46 +00001944
Douglas Gregor53c374f2010-12-07 00:41:46 +00001945 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00001946 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001947 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001948
Anders Carlssondefefd22010-04-23 02:00:02 +00001949 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00001950 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00001951 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1952 SourceLocation()),
1953 BaseSpec->isVirtual(),
1954 SourceLocation(),
1955 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001956 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00001957 SourceLocation());
1958
Anders Carlssondefefd22010-04-23 02:00:02 +00001959 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001960}
1961
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001962static bool
1963BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001964 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001965 FieldDecl *Field,
Sean Huntcbb67482011-01-08 20:30:50 +00001966 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001967 if (Field->isInvalidDecl())
1968 return true;
1969
Chandler Carruthf186b542010-06-29 23:50:44 +00001970 SourceLocation Loc = Constructor->getLocation();
1971
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001972 if (ImplicitInitKind == IIK_Copy) {
1973 ParmVarDecl *Param = Constructor->getParamDecl(0);
1974 QualType ParamType = Param->getType().getNonReferenceType();
1975
1976 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001977 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001978 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001979
1980 // Build a reference to this field within the parameter.
1981 CXXScopeSpec SS;
1982 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1983 Sema::LookupMemberName);
1984 MemberLookup.addDecl(Field, AS_public);
1985 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001986 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001987 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001988 ParamType, Loc,
1989 /*IsArrow=*/false,
1990 SS,
1991 /*FirstQualifierInScope=*/0,
1992 MemberLookup,
1993 /*TemplateArgs=*/0);
1994 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001995 return true;
1996
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001997 // When the field we are copying is an array, create index variables for
1998 // each dimension of the array. We use these index variables to subscript
1999 // the source array, and other clients (e.g., CodeGen) will perform the
2000 // necessary iteration with these index variables.
2001 llvm::SmallVector<VarDecl *, 4> IndexVariables;
2002 QualType BaseType = Field->getType();
2003 QualType SizeType = SemaRef.Context.getSizeType();
2004 while (const ConstantArrayType *Array
2005 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2006 // Create the iteration variable for this array index.
2007 IdentifierInfo *IterationVarName = 0;
2008 {
2009 llvm::SmallString<8> Str;
2010 llvm::raw_svector_ostream OS(Str);
2011 OS << "__i" << IndexVariables.size();
2012 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2013 }
2014 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002015 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002016 IterationVarName, SizeType,
2017 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002018 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002019 IndexVariables.push_back(IterationVar);
2020
2021 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002022 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002023 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002024 assert(!IterationVarRef.isInvalid() &&
2025 "Reference to invented variable cannot fail!");
2026
2027 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002028 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002029 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002030 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002031 Loc);
2032 if (CopyCtorArg.isInvalid())
2033 return true;
2034
2035 BaseType = Array->getElementType();
2036 }
2037
2038 // Construct the entity that we will be initializing. For an array, this
2039 // will be first element in the array, which may require several levels
2040 // of array-subscript entities.
2041 llvm::SmallVector<InitializedEntity, 4> Entities;
2042 Entities.reserve(1 + IndexVariables.size());
2043 Entities.push_back(InitializedEntity::InitializeMember(Field));
2044 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2045 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2046 0,
2047 Entities.back()));
2048
2049 // Direct-initialize to use the copy constructor.
2050 InitializationKind InitKind =
2051 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2052
2053 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2054 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2055 &CopyCtorArgE, 1);
2056
John McCall60d7b3a2010-08-24 06:29:42 +00002057 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002058 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002059 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002060 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002061 if (MemberInit.isInvalid())
2062 return true;
2063
2064 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00002065 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002066 MemberInit.takeAs<Expr>(), Loc,
2067 IndexVariables.data(),
2068 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002069 return false;
2070 }
2071
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002072 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2073
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002074 QualType FieldBaseElementType =
2075 SemaRef.Context.getBaseElementType(Field->getType());
2076
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002077 if (FieldBaseElementType->isRecordType()) {
2078 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002079 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002080 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002081
2082 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002083 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002084 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002085
Douglas Gregor53c374f2010-12-07 00:41:46 +00002086 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002087 if (MemberInit.isInvalid())
2088 return true;
2089
2090 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002091 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00002092 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002093 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00002094 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002095 return false;
2096 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002097
Sean Hunt1f2f3842011-05-17 00:19:05 +00002098 if (!Field->getParent()->isUnion()) {
2099 if (FieldBaseElementType->isReferenceType()) {
2100 SemaRef.Diag(Constructor->getLocation(),
2101 diag::err_uninitialized_member_in_ctor)
2102 << (int)Constructor->isImplicit()
2103 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2104 << 0 << Field->getDeclName();
2105 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2106 return true;
2107 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002108
Sean Hunt1f2f3842011-05-17 00:19:05 +00002109 if (FieldBaseElementType.isConstQualified()) {
2110 SemaRef.Diag(Constructor->getLocation(),
2111 diag::err_uninitialized_member_in_ctor)
2112 << (int)Constructor->isImplicit()
2113 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2114 << 1 << Field->getDeclName();
2115 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2116 return true;
2117 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002118 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002119
John McCallf85e1932011-06-15 23:02:42 +00002120 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2121 FieldBaseElementType->isObjCRetainableType() &&
2122 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2123 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2124 // Instant objects:
2125 // Default-initialize Objective-C pointers to NULL.
2126 CXXMemberInit
2127 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2128 Loc, Loc,
2129 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2130 Loc);
2131 return false;
2132 }
2133
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002134 // Nothing to initialize.
2135 CXXMemberInit = 0;
2136 return false;
2137}
John McCallf1860e52010-05-20 23:23:51 +00002138
2139namespace {
2140struct BaseAndFieldInfo {
2141 Sema &S;
2142 CXXConstructorDecl *Ctor;
2143 bool AnyErrorsInInits;
2144 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002145 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2146 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002147
2148 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2149 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2150 // FIXME: Handle implicit move constructors.
2151 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2152 IIK = IIK_Copy;
2153 else
2154 IIK = IIK_Default;
2155 }
2156};
2157}
2158
Richard Smith7a614d82011-06-11 17:19:42 +00002159static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallf1860e52010-05-20 23:23:51 +00002160 FieldDecl *Top, FieldDecl *Field) {
2161
Chandler Carruthe861c602010-06-30 02:59:29 +00002162 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002163 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002164 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002165 return false;
2166 }
2167
Richard Smith7a614d82011-06-11 17:19:42 +00002168 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2169 // has a brace-or-equal-initializer, the entity is initialized as specified
2170 // in [dcl.init].
2171 if (Field->hasInClassInitializer()) {
2172 Info.AllToInit.push_back(
2173 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2174 SourceLocation(),
2175 SourceLocation(), 0,
2176 SourceLocation()));
2177 return false;
2178 }
2179
John McCallf1860e52010-05-20 23:23:51 +00002180 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2181 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2182 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002183 CXXRecordDecl *FieldClassDecl
2184 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002185
2186 // Even though union members never have non-trivial default
2187 // constructions in C++03, we still build member initializers for aggregate
2188 // record types which can be union members, and C++0x allows non-trivial
2189 // default constructors for union members, so we ensure that only one
2190 // member is initialized for these.
2191 if (FieldClassDecl->isUnion()) {
2192 // First check for an explicit initializer for one field.
2193 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2194 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002195 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002196 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002197
2198 // Once we've initialized a field of an anonymous union, the union
2199 // field in the class is also initialized, so exit immediately.
2200 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002201 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith7a614d82011-06-11 17:19:42 +00002202 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002203 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002204 }
2205 }
2206
2207 // Fallthrough and construct a default initializer for the union as
2208 // a whole, which can call its default constructor if such a thing exists
2209 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2210 // behavior going forward with C++0x, when anonymous unions there are
2211 // finalized, we should revisit this.
2212 } else {
2213 // For structs, we simply descend through to initialize all members where
2214 // necessary.
2215 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2216 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith7a614d82011-06-11 17:19:42 +00002217 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruthe861c602010-06-30 02:59:29 +00002218 return true;
2219 }
2220 }
John McCallf1860e52010-05-20 23:23:51 +00002221 }
2222
2223 // Don't try to build an implicit initializer if there were semantic
2224 // errors in any of the initializers (and therefore we might be
2225 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002226 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002227 return false;
2228
Sean Huntcbb67482011-01-08 20:30:50 +00002229 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002230 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2231 return true;
John McCallf1860e52010-05-20 23:23:51 +00002232
Francois Pichet00eb3f92010-12-04 09:14:42 +00002233 if (Init)
2234 Info.AllToInit.push_back(Init);
2235
John McCallf1860e52010-05-20 23:23:51 +00002236 return false;
2237}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002238
2239bool
2240Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2241 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002242 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002243 Constructor->setNumCtorInitializers(1);
2244 CXXCtorInitializer **initializer =
2245 new (Context) CXXCtorInitializer*[1];
2246 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2247 Constructor->setCtorInitializers(initializer);
2248
Sean Huntb76af9c2011-05-03 23:05:34 +00002249 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2250 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2251 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2252 }
2253
Sean Huntc1598702011-05-05 00:05:47 +00002254 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002255
Sean Hunt059ce0d2011-05-01 07:04:31 +00002256 return false;
2257}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002258
Eli Friedman80c30da2009-11-09 19:20:36 +00002259bool
Sean Huntcbb67482011-01-08 20:30:50 +00002260Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2261 CXXCtorInitializer **Initializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002262 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002263 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002264 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002265 // Just store the initializers as written, they will be checked during
2266 // instantiation.
2267 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002268 Constructor->setNumCtorInitializers(NumInitializers);
2269 CXXCtorInitializer **baseOrMemberInitializers =
2270 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002271 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002272 NumInitializers * sizeof(CXXCtorInitializer*));
2273 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002274 }
2275
2276 return false;
2277 }
2278
John McCallf1860e52010-05-20 23:23:51 +00002279 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002280
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002281 // We need to build the initializer AST according to order of construction
2282 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002283 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002284 if (!ClassDecl)
2285 return true;
2286
Eli Friedman80c30da2009-11-09 19:20:36 +00002287 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002289 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002290 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002291
2292 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002293 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002294 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002295 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002296 }
2297
Anders Carlsson711f34a2010-04-21 19:52:01 +00002298 // Keep track of the direct virtual bases.
2299 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2300 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2301 E = ClassDecl->bases_end(); I != E; ++I) {
2302 if (I->isVirtual())
2303 DirectVBases.insert(I);
2304 }
2305
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002306 // Push virtual bases before others.
2307 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2308 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2309
Sean Huntcbb67482011-01-08 20:30:50 +00002310 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002311 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2312 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002313 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002314 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002315 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002316 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002317 VBase, IsInheritedVirtualBase,
2318 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002319 HadError = true;
2320 continue;
2321 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002322
John McCallf1860e52010-05-20 23:23:51 +00002323 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002324 }
2325 }
Mike Stump1eb44332009-09-09 15:08:12 +00002326
John McCallf1860e52010-05-20 23:23:51 +00002327 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002328 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2329 E = ClassDecl->bases_end(); Base != E; ++Base) {
2330 // Virtuals are in the virtual base list and already constructed.
2331 if (Base->isVirtual())
2332 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Sean Huntcbb67482011-01-08 20:30:50 +00002334 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002335 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2336 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002337 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002338 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002339 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002340 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002341 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002342 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002343 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002344 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002345
John McCallf1860e52010-05-20 23:23:51 +00002346 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002347 }
2348 }
Mike Stump1eb44332009-09-09 15:08:12 +00002349
John McCallf1860e52010-05-20 23:23:51 +00002350 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002351 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002352 E = ClassDecl->field_end(); Field != E; ++Field) {
2353 if ((*Field)->getType()->isIncompleteArrayType()) {
2354 assert(ClassDecl->hasFlexibleArrayMember() &&
2355 "Incomplete array type is not valid");
2356 continue;
2357 }
Richard Smith7a614d82011-06-11 17:19:42 +00002358 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002359 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
John McCallf1860e52010-05-20 23:23:51 +00002362 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002363 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002364 Constructor->setNumCtorInitializers(NumInitializers);
2365 CXXCtorInitializer **baseOrMemberInitializers =
2366 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002367 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002368 NumInitializers * sizeof(CXXCtorInitializer*));
2369 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002370
John McCallef027fe2010-03-16 21:39:52 +00002371 // Constructors implicitly reference the base and member
2372 // destructors.
2373 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2374 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002375 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002376
2377 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002378}
2379
Eli Friedman6347f422009-07-21 19:28:10 +00002380static void *GetKeyForTopLevelField(FieldDecl *Field) {
2381 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002382 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002383 if (RT->getDecl()->isAnonymousStructOrUnion())
2384 return static_cast<void *>(RT->getDecl());
2385 }
2386 return static_cast<void *>(Field);
2387}
2388
Anders Carlssonea356fb2010-04-02 05:42:15 +00002389static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002390 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002391}
2392
Anders Carlssonea356fb2010-04-02 05:42:15 +00002393static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002394 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002395 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002396 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002397
Eli Friedman6347f422009-07-21 19:28:10 +00002398 // For fields injected into the class via declaration of an anonymous union,
2399 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002400 FieldDecl *Field = Member->getAnyMember();
2401
John McCall3c3ccdb2010-04-10 09:28:51 +00002402 // If the field is a member of an anonymous struct or union, our key
2403 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002404 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002405 if (RD->isAnonymousStructOrUnion()) {
2406 while (true) {
2407 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2408 if (Parent->isAnonymousStructOrUnion())
2409 RD = Parent;
2410 else
2411 break;
2412 }
2413
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002414 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002415 }
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002417 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002418}
2419
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002420static void
2421DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002422 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002423 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002424 unsigned NumInits) {
2425 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002428 // Don't check initializers order unless the warning is enabled at the
2429 // location of at least one initializer.
2430 bool ShouldCheckOrder = false;
2431 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002432 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002433 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2434 Init->getSourceLocation())
2435 != Diagnostic::Ignored) {
2436 ShouldCheckOrder = true;
2437 break;
2438 }
2439 }
2440 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002441 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002442
John McCalld6ca8da2010-04-10 07:37:23 +00002443 // Build the list of bases and members in the order that they'll
2444 // actually be initialized. The explicit initializers should be in
2445 // this same order but may be missing things.
2446 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Anders Carlsson071d6102010-04-02 03:38:04 +00002448 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2449
John McCalld6ca8da2010-04-10 07:37:23 +00002450 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002451 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002452 ClassDecl->vbases_begin(),
2453 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002454 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002455
John McCalld6ca8da2010-04-10 07:37:23 +00002456 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002457 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002458 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002459 if (Base->isVirtual())
2460 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002461 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002462 }
Mike Stump1eb44332009-09-09 15:08:12 +00002463
John McCalld6ca8da2010-04-10 07:37:23 +00002464 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002465 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2466 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002467 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002468
John McCalld6ca8da2010-04-10 07:37:23 +00002469 unsigned NumIdealInits = IdealInitKeys.size();
2470 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002471
Sean Huntcbb67482011-01-08 20:30:50 +00002472 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002473 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002474 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002475 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002476
2477 // Scan forward to try to find this initializer in the idealized
2478 // initializers list.
2479 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2480 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002481 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002482
2483 // If we didn't find this initializer, it must be because we
2484 // scanned past it on a previous iteration. That can only
2485 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002486 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002487 Sema::SemaDiagnosticBuilder D =
2488 SemaRef.Diag(PrevInit->getSourceLocation(),
2489 diag::warn_initializer_out_of_order);
2490
Francois Pichet00eb3f92010-12-04 09:14:42 +00002491 if (PrevInit->isAnyMemberInitializer())
2492 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002493 else
2494 D << 1 << PrevInit->getBaseClassInfo()->getType();
2495
Francois Pichet00eb3f92010-12-04 09:14:42 +00002496 if (Init->isAnyMemberInitializer())
2497 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002498 else
2499 D << 1 << Init->getBaseClassInfo()->getType();
2500
2501 // Move back to the initializer's location in the ideal list.
2502 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2503 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002504 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002505
2506 assert(IdealIndex != NumIdealInits &&
2507 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002508 }
John McCalld6ca8da2010-04-10 07:37:23 +00002509
2510 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002511 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002512}
2513
John McCall3c3ccdb2010-04-10 09:28:51 +00002514namespace {
2515bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002516 CXXCtorInitializer *Init,
2517 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002518 if (!PrevInit) {
2519 PrevInit = Init;
2520 return false;
2521 }
2522
2523 if (FieldDecl *Field = Init->getMember())
2524 S.Diag(Init->getSourceLocation(),
2525 diag::err_multiple_mem_initialization)
2526 << Field->getDeclName()
2527 << Init->getSourceRange();
2528 else {
John McCallf4c73712011-01-19 06:33:43 +00002529 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002530 assert(BaseClass && "neither field nor base");
2531 S.Diag(Init->getSourceLocation(),
2532 diag::err_multiple_base_initialization)
2533 << QualType(BaseClass, 0)
2534 << Init->getSourceRange();
2535 }
2536 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2537 << 0 << PrevInit->getSourceRange();
2538
2539 return true;
2540}
2541
Sean Huntcbb67482011-01-08 20:30:50 +00002542typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002543typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2544
2545bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002546 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002547 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002548 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002549 RecordDecl *Parent = Field->getParent();
2550 if (!Parent->isAnonymousStructOrUnion())
2551 return false;
2552
2553 NamedDecl *Child = Field;
2554 do {
2555 if (Parent->isUnion()) {
2556 UnionEntry &En = Unions[Parent];
2557 if (En.first && En.first != Child) {
2558 S.Diag(Init->getSourceLocation(),
2559 diag::err_multiple_mem_union_initialization)
2560 << Field->getDeclName()
2561 << Init->getSourceRange();
2562 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2563 << 0 << En.second->getSourceRange();
2564 return true;
2565 } else if (!En.first) {
2566 En.first = Child;
2567 En.second = Init;
2568 }
2569 }
2570
2571 Child = Parent;
2572 Parent = cast<RecordDecl>(Parent->getDeclContext());
2573 } while (Parent->isAnonymousStructOrUnion());
2574
2575 return false;
2576}
2577}
2578
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002579/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002580void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002581 SourceLocation ColonLoc,
2582 MemInitTy **meminits, unsigned NumMemInits,
2583 bool AnyErrors) {
2584 if (!ConstructorDecl)
2585 return;
2586
2587 AdjustDeclIfTemplate(ConstructorDecl);
2588
2589 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002590 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002591
2592 if (!Constructor) {
2593 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2594 return;
2595 }
2596
Sean Huntcbb67482011-01-08 20:30:50 +00002597 CXXCtorInitializer **MemInits =
2598 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002599
2600 // Mapping for the duplicate initializers check.
2601 // For member initializers, this is keyed with a FieldDecl*.
2602 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002603 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002604
2605 // Mapping for the inconsistent anonymous-union initializers check.
2606 RedundantUnionMap MemberUnions;
2607
Anders Carlssonea356fb2010-04-02 05:42:15 +00002608 bool HadError = false;
2609 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002610 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002611
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002612 // Set the source order index.
2613 Init->setSourceOrder(i);
2614
Francois Pichet00eb3f92010-12-04 09:14:42 +00002615 if (Init->isAnyMemberInitializer()) {
2616 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002617 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2618 CheckRedundantUnionInit(*this, Init, MemberUnions))
2619 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002620 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002621 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2622 if (CheckRedundantInit(*this, Init, Members[Key]))
2623 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002624 } else {
2625 assert(Init->isDelegatingInitializer());
2626 // This must be the only initializer
2627 if (i != 0 || NumMemInits > 1) {
2628 Diag(MemInits[0]->getSourceLocation(),
2629 diag::err_delegating_initializer_alone)
2630 << MemInits[0]->getSourceRange();
2631 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002632 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002633 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002634 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002635 // Return immediately as the initializer is set.
2636 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002637 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002638 }
2639
Anders Carlssonea356fb2010-04-02 05:42:15 +00002640 if (HadError)
2641 return;
2642
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002643 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002644
Sean Huntcbb67482011-01-08 20:30:50 +00002645 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002646}
2647
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002648void
John McCallef027fe2010-03-16 21:39:52 +00002649Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2650 CXXRecordDecl *ClassDecl) {
2651 // Ignore dependent contexts.
2652 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002653 return;
John McCall58e6f342010-03-16 05:22:47 +00002654
2655 // FIXME: all the access-control diagnostics are positioned on the
2656 // field/base declaration. That's probably good; that said, the
2657 // user might reasonably want to know why the destructor is being
2658 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002659
Anders Carlsson9f853df2009-11-17 04:44:12 +00002660 // Non-static data members.
2661 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2662 E = ClassDecl->field_end(); I != E; ++I) {
2663 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002664 if (Field->isInvalidDecl())
2665 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002666 QualType FieldType = Context.getBaseElementType(Field->getType());
2667
2668 const RecordType* RT = FieldType->getAs<RecordType>();
2669 if (!RT)
2670 continue;
2671
2672 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002673 if (FieldClassDecl->isInvalidDecl())
2674 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002675 if (FieldClassDecl->hasTrivialDestructor())
2676 continue;
2677
Douglas Gregordb89f282010-07-01 22:47:18 +00002678 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002679 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002680 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002681 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002682 << Field->getDeclName()
2683 << FieldType);
2684
John McCallef027fe2010-03-16 21:39:52 +00002685 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002686 }
2687
John McCall58e6f342010-03-16 05:22:47 +00002688 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2689
Anders Carlsson9f853df2009-11-17 04:44:12 +00002690 // Bases.
2691 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2692 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002693 // Bases are always records in a well-formed non-dependent class.
2694 const RecordType *RT = Base->getType()->getAs<RecordType>();
2695
2696 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002697 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002698 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002699
John McCall58e6f342010-03-16 05:22:47 +00002700 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002701 // If our base class is invalid, we probably can't get its dtor anyway.
2702 if (BaseClassDecl->isInvalidDecl())
2703 continue;
2704 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002705 if (BaseClassDecl->hasTrivialDestructor())
2706 continue;
John McCall58e6f342010-03-16 05:22:47 +00002707
Douglas Gregordb89f282010-07-01 22:47:18 +00002708 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002709 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002710
2711 // FIXME: caret should be on the start of the class name
2712 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002713 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002714 << Base->getType()
2715 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002716
John McCallef027fe2010-03-16 21:39:52 +00002717 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002718 }
2719
2720 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002721 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2722 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002723
2724 // Bases are always records in a well-formed non-dependent class.
2725 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2726
2727 // Ignore direct virtual bases.
2728 if (DirectVirtualBases.count(RT))
2729 continue;
2730
John McCall58e6f342010-03-16 05:22:47 +00002731 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002732 // If our base class is invalid, we probably can't get its dtor anyway.
2733 if (BaseClassDecl->isInvalidDecl())
2734 continue;
2735 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002736 if (BaseClassDecl->hasTrivialDestructor())
2737 continue;
John McCall58e6f342010-03-16 05:22:47 +00002738
Douglas Gregordb89f282010-07-01 22:47:18 +00002739 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002740 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002741 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002742 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002743 << VBase->getType());
2744
John McCallef027fe2010-03-16 21:39:52 +00002745 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002746 }
2747}
2748
John McCalld226f652010-08-21 09:40:31 +00002749void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002750 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002751 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Mike Stump1eb44332009-09-09 15:08:12 +00002753 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002754 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002755 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002756}
2757
Mike Stump1eb44332009-09-09 15:08:12 +00002758bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002759 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002760 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002761 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002762 else
John McCall94c3b562010-08-18 09:41:07 +00002763 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002764}
2765
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002766bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002767 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002768 if (!getLangOptions().CPlusPlus)
2769 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Anders Carlsson11f21a02009-03-23 19:10:31 +00002771 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002772 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Ted Kremenek6217b802009-07-29 21:53:49 +00002774 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002775 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002776 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002777 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002779 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002780 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002781 }
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Ted Kremenek6217b802009-07-29 21:53:49 +00002783 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002784 if (!RT)
2785 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002786
John McCall86ff3082010-02-04 22:26:26 +00002787 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002788
John McCall94c3b562010-08-18 09:41:07 +00002789 // We can't answer whether something is abstract until it has a
2790 // definition. If it's currently being defined, we'll walk back
2791 // over all the declarations when we have a full definition.
2792 const CXXRecordDecl *Def = RD->getDefinition();
2793 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002794 return false;
2795
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002796 if (!RD->isAbstract())
2797 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002799 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002800 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002801
John McCall94c3b562010-08-18 09:41:07 +00002802 return true;
2803}
2804
2805void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2806 // Check if we've already emitted the list of pure virtual functions
2807 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002808 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002809 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002811 CXXFinalOverriderMap FinalOverriders;
2812 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002813
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002814 // Keep a set of seen pure methods so we won't diagnose the same method
2815 // more than once.
2816 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2817
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002818 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2819 MEnd = FinalOverriders.end();
2820 M != MEnd;
2821 ++M) {
2822 for (OverridingMethods::iterator SO = M->second.begin(),
2823 SOEnd = M->second.end();
2824 SO != SOEnd; ++SO) {
2825 // C++ [class.abstract]p4:
2826 // A class is abstract if it contains or inherits at least one
2827 // pure virtual function for which the final overrider is pure
2828 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002829
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002830 //
2831 if (SO->second.size() != 1)
2832 continue;
2833
2834 if (!SO->second.front().Method->isPure())
2835 continue;
2836
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002837 if (!SeenPureMethods.insert(SO->second.front().Method))
2838 continue;
2839
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002840 Diag(SO->second.front().Method->getLocation(),
2841 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002842 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002843 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002844 }
2845
2846 if (!PureVirtualClassDiagSet)
2847 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2848 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002849}
2850
Anders Carlsson8211eff2009-03-24 01:19:16 +00002851namespace {
John McCall94c3b562010-08-18 09:41:07 +00002852struct AbstractUsageInfo {
2853 Sema &S;
2854 CXXRecordDecl *Record;
2855 CanQualType AbstractType;
2856 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002857
John McCall94c3b562010-08-18 09:41:07 +00002858 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2859 : S(S), Record(Record),
2860 AbstractType(S.Context.getCanonicalType(
2861 S.Context.getTypeDeclType(Record))),
2862 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002863
John McCall94c3b562010-08-18 09:41:07 +00002864 void DiagnoseAbstractType() {
2865 if (Invalid) return;
2866 S.DiagnoseAbstractType(Record);
2867 Invalid = true;
2868 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002869
John McCall94c3b562010-08-18 09:41:07 +00002870 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2871};
2872
2873struct CheckAbstractUsage {
2874 AbstractUsageInfo &Info;
2875 const NamedDecl *Ctx;
2876
2877 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2878 : Info(Info), Ctx(Ctx) {}
2879
2880 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2881 switch (TL.getTypeLocClass()) {
2882#define ABSTRACT_TYPELOC(CLASS, PARENT)
2883#define TYPELOC(CLASS, PARENT) \
2884 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2885#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002886 }
John McCall94c3b562010-08-18 09:41:07 +00002887 }
Mike Stump1eb44332009-09-09 15:08:12 +00002888
John McCall94c3b562010-08-18 09:41:07 +00002889 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2890 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2891 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002892 if (!TL.getArg(I))
2893 continue;
2894
John McCall94c3b562010-08-18 09:41:07 +00002895 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2896 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002897 }
John McCall94c3b562010-08-18 09:41:07 +00002898 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002899
John McCall94c3b562010-08-18 09:41:07 +00002900 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2901 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2902 }
Mike Stump1eb44332009-09-09 15:08:12 +00002903
John McCall94c3b562010-08-18 09:41:07 +00002904 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2905 // Visit the type parameters from a permissive context.
2906 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2907 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2908 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2909 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2910 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2911 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002912 }
John McCall94c3b562010-08-18 09:41:07 +00002913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCall94c3b562010-08-18 09:41:07 +00002915 // Visit pointee types from a permissive context.
2916#define CheckPolymorphic(Type) \
2917 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2918 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2919 }
2920 CheckPolymorphic(PointerTypeLoc)
2921 CheckPolymorphic(ReferenceTypeLoc)
2922 CheckPolymorphic(MemberPointerTypeLoc)
2923 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002924
John McCall94c3b562010-08-18 09:41:07 +00002925 /// Handle all the types we haven't given a more specific
2926 /// implementation for above.
2927 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2928 // Every other kind of type that we haven't called out already
2929 // that has an inner type is either (1) sugar or (2) contains that
2930 // inner type in some way as a subobject.
2931 if (TypeLoc Next = TL.getNextTypeLoc())
2932 return Visit(Next, Sel);
2933
2934 // If there's no inner type and we're in a permissive context,
2935 // don't diagnose.
2936 if (Sel == Sema::AbstractNone) return;
2937
2938 // Check whether the type matches the abstract type.
2939 QualType T = TL.getType();
2940 if (T->isArrayType()) {
2941 Sel = Sema::AbstractArrayType;
2942 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002943 }
John McCall94c3b562010-08-18 09:41:07 +00002944 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2945 if (CT != Info.AbstractType) return;
2946
2947 // It matched; do some magic.
2948 if (Sel == Sema::AbstractArrayType) {
2949 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2950 << T << TL.getSourceRange();
2951 } else {
2952 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2953 << Sel << T << TL.getSourceRange();
2954 }
2955 Info.DiagnoseAbstractType();
2956 }
2957};
2958
2959void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2960 Sema::AbstractDiagSelID Sel) {
2961 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2962}
2963
2964}
2965
2966/// Check for invalid uses of an abstract type in a method declaration.
2967static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2968 CXXMethodDecl *MD) {
2969 // No need to do the check on definitions, which require that
2970 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002971 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002972 return;
2973
2974 // For safety's sake, just ignore it if we don't have type source
2975 // information. This should never happen for non-implicit methods,
2976 // but...
2977 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2978 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2979}
2980
2981/// Check for invalid uses of an abstract type within a class definition.
2982static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2983 CXXRecordDecl *RD) {
2984 for (CXXRecordDecl::decl_iterator
2985 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2986 Decl *D = *I;
2987 if (D->isImplicit()) continue;
2988
2989 // Methods and method templates.
2990 if (isa<CXXMethodDecl>(D)) {
2991 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2992 } else if (isa<FunctionTemplateDecl>(D)) {
2993 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2994 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2995
2996 // Fields and static variables.
2997 } else if (isa<FieldDecl>(D)) {
2998 FieldDecl *FD = cast<FieldDecl>(D);
2999 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3000 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3001 } else if (isa<VarDecl>(D)) {
3002 VarDecl *VD = cast<VarDecl>(D);
3003 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3004 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3005
3006 // Nested classes and class templates.
3007 } else if (isa<CXXRecordDecl>(D)) {
3008 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3009 } else if (isa<ClassTemplateDecl>(D)) {
3010 CheckAbstractClassUsage(Info,
3011 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3012 }
3013 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003014}
3015
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003016/// \brief Perform semantic checks on a class definition that has been
3017/// completing, introducing implicitly-declared members, checking for
3018/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003019void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003020 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003021 return;
3022
John McCall94c3b562010-08-18 09:41:07 +00003023 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3024 AbstractUsageInfo Info(*this, Record);
3025 CheckAbstractClassUsage(Info, Record);
3026 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003027
3028 // If this is not an aggregate type and has no user-declared constructor,
3029 // complain about any non-static data members of reference or const scalar
3030 // type, since they will never get initializers.
3031 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3032 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3033 bool Complained = false;
3034 for (RecordDecl::field_iterator F = Record->field_begin(),
3035 FEnd = Record->field_end();
3036 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003037 if (F->hasInClassInitializer())
3038 continue;
3039
Douglas Gregor325e5932010-04-15 00:00:53 +00003040 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003041 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003042 if (!Complained) {
3043 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3044 << Record->getTagKind() << Record;
3045 Complained = true;
3046 }
3047
3048 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3049 << F->getType()->isReferenceType()
3050 << F->getDeclName();
3051 }
3052 }
3053 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003054
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003055 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003056 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003057
3058 if (Record->getIdentifier()) {
3059 // C++ [class.mem]p13:
3060 // If T is the name of a class, then each of the following shall have a
3061 // name different from T:
3062 // - every member of every anonymous union that is a member of class T.
3063 //
3064 // C++ [class.mem]p14:
3065 // In addition, if class T has a user-declared constructor (12.1), every
3066 // non-static data member of class T shall have a name different from T.
3067 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003068 R.first != R.second; ++R.first) {
3069 NamedDecl *D = *R.first;
3070 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3071 isa<IndirectFieldDecl>(D)) {
3072 Diag(D->getLocation(), diag::err_member_name_of_class)
3073 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003074 break;
3075 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003076 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003077 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003078
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003079 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003080 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003081 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003082 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003083 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3084 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3085 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003086
3087 // See if a method overloads virtual methods in a base
3088 /// class without overriding any.
3089 if (!Record->isDependentType()) {
3090 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3091 MEnd = Record->method_end();
3092 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003093 if (!(*M)->isStatic())
3094 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003095 }
3096 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003097
3098 // Declare inherited constructors. We do this eagerly here because:
3099 // - The standard requires an eager diagnostic for conflicting inherited
3100 // constructors from different classes.
3101 // - The lazy declaration of the other implicit constructors is so as to not
3102 // waste space and performance on classes that are not meant to be
3103 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3104 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003105 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003106
Sean Hunteb88ae52011-05-23 21:07:59 +00003107 if (!Record->isDependentType())
3108 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003109}
3110
3111void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003112 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3113 ME = Record->method_end();
3114 MI != ME; ++MI) {
3115 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3116 switch (getSpecialMember(*MI)) {
3117 case CXXDefaultConstructor:
3118 CheckExplicitlyDefaultedDefaultConstructor(
3119 cast<CXXConstructorDecl>(*MI));
3120 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003121
Sean Huntcb45a0f2011-05-12 22:46:25 +00003122 case CXXDestructor:
3123 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3124 break;
3125
3126 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003127 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3128 break;
3129
Sean Huntcb45a0f2011-05-12 22:46:25 +00003130 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003131 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003132 break;
3133
Sean Hunt82713172011-05-25 23:16:36 +00003134 case CXXMoveConstructor:
3135 case CXXMoveAssignment:
3136 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3137 break;
3138
Sean Huntcb45a0f2011-05-12 22:46:25 +00003139 default:
Sean Hunt2b188082011-05-14 05:23:28 +00003140 // FIXME: Do moves once they exist
Sean Huntcb45a0f2011-05-12 22:46:25 +00003141 llvm_unreachable("non-special member explicitly defaulted!");
3142 }
Sean Hunt001cad92011-05-10 00:49:42 +00003143 }
3144 }
3145
Sean Hunt001cad92011-05-10 00:49:42 +00003146}
3147
3148void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3149 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3150
3151 // Whether this was the first-declared instance of the constructor.
3152 // This affects whether we implicitly add an exception spec (and, eventually,
3153 // constexpr). It is also ill-formed to explicitly default a constructor such
3154 // that it would be deleted. (C++0x [decl.fct.def.default])
3155 bool First = CD == CD->getCanonicalDecl();
3156
Sean Hunt49634cf2011-05-13 06:10:58 +00003157 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003158 if (CD->getNumParams() != 0) {
3159 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3160 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003161 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003162 }
3163
3164 ImplicitExceptionSpecification Spec
3165 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3166 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003167 if (EPI.ExceptionSpecType == EST_Delayed) {
3168 // Exception specification depends on some deferred part of the class. We'll
3169 // try again when the class's definition has been fully processed.
3170 return;
3171 }
Sean Hunt001cad92011-05-10 00:49:42 +00003172 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3173 *ExceptionType = Context.getFunctionType(
3174 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3175
3176 if (CtorType->hasExceptionSpec()) {
3177 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003178 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003179 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003180 PDiag(),
3181 ExceptionType, SourceLocation(),
3182 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003183 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003184 }
3185 } else if (First) {
3186 // We set the declaration to have the computed exception spec here.
3187 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003188 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003189 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3190 }
Sean Huntca46d132011-05-12 03:51:48 +00003191
Sean Hunt49634cf2011-05-13 06:10:58 +00003192 if (HadError) {
3193 CD->setInvalidDecl();
3194 return;
3195 }
3196
Sean Huntca46d132011-05-12 03:51:48 +00003197 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003198 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003199 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003200 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003201 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003202 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003203 CD->setInvalidDecl();
3204 }
3205 }
3206}
3207
3208void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3209 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3210
3211 // Whether this was the first-declared instance of the constructor.
3212 bool First = CD == CD->getCanonicalDecl();
3213
3214 bool HadError = false;
3215 if (CD->getNumParams() != 1) {
3216 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3217 << CD->getSourceRange();
3218 HadError = true;
3219 }
3220
3221 ImplicitExceptionSpecification Spec(Context);
3222 bool Const;
3223 llvm::tie(Spec, Const) =
3224 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3225
3226 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3227 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3228 *ExceptionType = Context.getFunctionType(
3229 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3230
3231 // Check for parameter type matching.
3232 // This is a copy ctor so we know it's a cv-qualified reference to T.
3233 QualType ArgType = CtorType->getArgType(0);
3234 if (ArgType->getPointeeType().isVolatileQualified()) {
3235 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3236 HadError = true;
3237 }
3238 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3239 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3240 HadError = true;
3241 }
3242
3243 if (CtorType->hasExceptionSpec()) {
3244 if (CheckEquivalentExceptionSpec(
3245 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003246 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003247 PDiag(),
3248 ExceptionType, SourceLocation(),
3249 CtorType, CD->getLocation())) {
3250 HadError = true;
3251 }
3252 } else if (First) {
3253 // We set the declaration to have the computed exception spec here.
3254 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003255 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003256 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3257 }
3258
3259 if (HadError) {
3260 CD->setInvalidDecl();
3261 return;
3262 }
3263
3264 if (ShouldDeleteCopyConstructor(CD)) {
3265 if (First) {
3266 CD->setDeletedAsWritten();
3267 } else {
3268 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003269 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003270 CD->setInvalidDecl();
3271 }
Sean Huntca46d132011-05-12 03:51:48 +00003272 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003273}
Sean Hunt001cad92011-05-10 00:49:42 +00003274
Sean Hunt2b188082011-05-14 05:23:28 +00003275void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3276 assert(MD->isExplicitlyDefaulted());
3277
3278 // Whether this was the first-declared instance of the operator
3279 bool First = MD == MD->getCanonicalDecl();
3280
3281 bool HadError = false;
3282 if (MD->getNumParams() != 1) {
3283 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3284 << MD->getSourceRange();
3285 HadError = true;
3286 }
3287
3288 QualType ReturnType =
3289 MD->getType()->getAs<FunctionType>()->getResultType();
3290 if (!ReturnType->isLValueReferenceType() ||
3291 !Context.hasSameType(
3292 Context.getCanonicalType(ReturnType->getPointeeType()),
3293 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3294 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3295 HadError = true;
3296 }
3297
3298 ImplicitExceptionSpecification Spec(Context);
3299 bool Const;
3300 llvm::tie(Spec, Const) =
3301 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3302
3303 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3304 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3305 *ExceptionType = Context.getFunctionType(
3306 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3307
Sean Hunt2b188082011-05-14 05:23:28 +00003308 QualType ArgType = OperType->getArgType(0);
Sean Huntbe631222011-05-17 20:44:43 +00003309 if (!ArgType->isReferenceType()) {
3310 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003311 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003312 } else {
3313 if (ArgType->getPointeeType().isVolatileQualified()) {
3314 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3315 HadError = true;
3316 }
3317 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3318 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3319 HadError = true;
3320 }
Sean Hunt2b188082011-05-14 05:23:28 +00003321 }
Sean Huntbe631222011-05-17 20:44:43 +00003322
Sean Hunt2b188082011-05-14 05:23:28 +00003323 if (OperType->getTypeQuals()) {
3324 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3325 HadError = true;
3326 }
3327
3328 if (OperType->hasExceptionSpec()) {
3329 if (CheckEquivalentExceptionSpec(
3330 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003331 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003332 PDiag(),
3333 ExceptionType, SourceLocation(),
3334 OperType, MD->getLocation())) {
3335 HadError = true;
3336 }
3337 } else if (First) {
3338 // We set the declaration to have the computed exception spec here.
3339 // We duplicate the one parameter type.
3340 EPI.RefQualifier = OperType->getRefQualifier();
3341 EPI.ExtInfo = OperType->getExtInfo();
3342 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3343 }
3344
3345 if (HadError) {
3346 MD->setInvalidDecl();
3347 return;
3348 }
3349
3350 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3351 if (First) {
3352 MD->setDeletedAsWritten();
3353 } else {
3354 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003355 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003356 MD->setInvalidDecl();
3357 }
3358 }
3359}
3360
Sean Huntcb45a0f2011-05-12 22:46:25 +00003361void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3362 assert(DD->isExplicitlyDefaulted());
3363
3364 // Whether this was the first-declared instance of the destructor.
3365 bool First = DD == DD->getCanonicalDecl();
3366
3367 ImplicitExceptionSpecification Spec
3368 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3369 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3370 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3371 *ExceptionType = Context.getFunctionType(
3372 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3373
3374 if (DtorType->hasExceptionSpec()) {
3375 if (CheckEquivalentExceptionSpec(
3376 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003377 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003378 PDiag(),
3379 ExceptionType, SourceLocation(),
3380 DtorType, DD->getLocation())) {
3381 DD->setInvalidDecl();
3382 return;
3383 }
3384 } else if (First) {
3385 // We set the declaration to have the computed exception spec here.
3386 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003387 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003388 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3389 }
3390
3391 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003392 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003393 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003394 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003395 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003396 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003397 DD->setInvalidDecl();
3398 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003399 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003400}
3401
Sean Huntcdee3fe2011-05-11 22:34:38 +00003402bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3403 CXXRecordDecl *RD = CD->getParent();
3404 assert(!RD->isDependentType() && "do deletion after instantiation");
3405 if (!LangOpts.CPlusPlus0x)
3406 return false;
3407
Sean Hunt71a682f2011-05-18 03:41:58 +00003408 SourceLocation Loc = CD->getLocation();
3409
Sean Huntcdee3fe2011-05-11 22:34:38 +00003410 // Do access control from the constructor
3411 ContextRAII CtorContext(*this, CD);
3412
3413 bool Union = RD->isUnion();
3414 bool AllConst = true;
3415
Sean Huntcdee3fe2011-05-11 22:34:38 +00003416 // We do this because we should never actually use an anonymous
3417 // union's constructor.
3418 if (Union && RD->isAnonymousStructOrUnion())
3419 return false;
3420
3421 // FIXME: We should put some diagnostic logic right into this function.
3422
3423 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003424 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003425
3426 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3427 BE = RD->bases_end();
3428 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003429 // We'll handle this one later
3430 if (BI->isVirtual())
3431 continue;
3432
Sean Huntcdee3fe2011-05-11 22:34:38 +00003433 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3434 assert(BaseDecl && "base isn't a CXXRecordDecl");
3435
3436 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003437 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003438 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3439 if (BaseDtor->isDeleted())
3440 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003441 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003442 AR_accessible)
3443 return true;
3444
Sean Huntcdee3fe2011-05-11 22:34:38 +00003445 // -- any [direct base class either] has no default constructor or
3446 // overload resolution as applied to [its] default constructor
3447 // results in an ambiguity or in a function that is deleted or
3448 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003449 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3450 if (!BaseDefault || BaseDefault->isDeleted())
3451 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003452
Sean Huntb320e0c2011-06-10 03:50:41 +00003453 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3454 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003455 return true;
3456 }
3457
3458 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3459 BE = RD->vbases_end();
3460 BI != BE; ++BI) {
3461 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3462 assert(BaseDecl && "base isn't a CXXRecordDecl");
3463
3464 // -- any [virtual base class] has a type with a destructor that is
3465 // delete or inaccessible from the defaulted default constructor
3466 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3467 if (BaseDtor->isDeleted())
3468 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003469 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003470 AR_accessible)
3471 return true;
3472
3473 // -- any [virtual base class either] has no default constructor or
3474 // overload resolution as applied to [its] default constructor
3475 // results in an ambiguity or in a function that is deleted or
3476 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003477 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3478 if (!BaseDefault || BaseDefault->isDeleted())
3479 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003480
Sean Huntb320e0c2011-06-10 03:50:41 +00003481 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3482 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003483 return true;
3484 }
3485
3486 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3487 FE = RD->field_end();
3488 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003489 if (FI->isInvalidDecl())
3490 continue;
3491
Sean Huntcdee3fe2011-05-11 22:34:38 +00003492 QualType FieldType = Context.getBaseElementType(FI->getType());
3493 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003494
Sean Huntcdee3fe2011-05-11 22:34:38 +00003495 // -- any non-static data member with no brace-or-equal-initializer is of
3496 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003497 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003498 return true;
3499
3500 // -- X is a union and all its variant members are of const-qualified type
3501 // (or array thereof)
3502 if (Union && !FieldType.isConstQualified())
3503 AllConst = false;
3504
3505 if (FieldRecord) {
3506 // -- X is a union-like class that has a variant member with a non-trivial
3507 // default constructor
3508 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3509 return true;
3510
3511 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3512 if (FieldDtor->isDeleted())
3513 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003514 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003515 AR_accessible)
3516 return true;
3517
3518 // -- any non-variant non-static data member of const-qualified type (or
3519 // array thereof) with no brace-or-equal-initializer does not have a
3520 // user-provided default constructor
3521 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003522 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003523 !FieldRecord->hasUserProvidedDefaultConstructor())
3524 return true;
3525
3526 if (!Union && FieldRecord->isUnion() &&
3527 FieldRecord->isAnonymousStructOrUnion()) {
3528 // We're okay to reuse AllConst here since we only care about the
3529 // value otherwise if we're in a union.
3530 AllConst = true;
3531
3532 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3533 UE = FieldRecord->field_end();
3534 UI != UE; ++UI) {
3535 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3536 CXXRecordDecl *UnionFieldRecord =
3537 UnionFieldType->getAsCXXRecordDecl();
3538
3539 if (!UnionFieldType.isConstQualified())
3540 AllConst = false;
3541
3542 if (UnionFieldRecord &&
3543 !UnionFieldRecord->hasTrivialDefaultConstructor())
3544 return true;
3545 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003546
Sean Huntcdee3fe2011-05-11 22:34:38 +00003547 if (AllConst)
3548 return true;
3549
3550 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003551 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003552 continue;
3553 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003554
Richard Smith7a614d82011-06-11 17:19:42 +00003555 // -- any non-static data member with no brace-or-equal-initializer has
3556 // class type M (or array thereof) and either M has no default
3557 // constructor or overload resolution as applied to M's default
3558 // constructor results in an ambiguity or in a function that is deleted
3559 // or inaccessible from the defaulted default constructor.
3560 if (!FI->hasInClassInitializer()) {
3561 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3562 if (!FieldDefault || FieldDefault->isDeleted())
3563 return true;
3564 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3565 PDiag()) != AR_accessible)
3566 return true;
3567 }
3568 } else if (!Union && FieldType.isConstQualified() &&
3569 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003570 // -- any non-variant non-static data member of const-qualified type (or
3571 // array thereof) with no brace-or-equal-initializer does not have a
3572 // user-provided default constructor
3573 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003574 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003575 }
3576
3577 if (Union && AllConst)
3578 return true;
3579
3580 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003581}
3582
Sean Hunt49634cf2011-05-13 06:10:58 +00003583bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003584 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003585 assert(!RD->isDependentType() && "do deletion after instantiation");
3586 if (!LangOpts.CPlusPlus0x)
3587 return false;
3588
Sean Hunt71a682f2011-05-18 03:41:58 +00003589 SourceLocation Loc = CD->getLocation();
3590
Sean Hunt49634cf2011-05-13 06:10:58 +00003591 // Do access control from the constructor
3592 ContextRAII CtorContext(*this, CD);
3593
Sean Huntc530d172011-06-10 04:44:37 +00003594 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003595
Sean Hunt2b188082011-05-14 05:23:28 +00003596 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3597 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003598 unsigned ArgQuals =
3599 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3600 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003601
3602 // We do this because we should never actually use an anonymous
3603 // union's constructor.
3604 if (Union && RD->isAnonymousStructOrUnion())
3605 return false;
3606
3607 // FIXME: We should put some diagnostic logic right into this function.
3608
3609 // C++0x [class.copy]/11
3610 // A defaulted [copy] constructor for class X is defined as delete if X has:
3611
3612 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3613 BE = RD->bases_end();
3614 BI != BE; ++BI) {
3615 // We'll handle this one later
3616 if (BI->isVirtual())
3617 continue;
3618
3619 QualType BaseType = BI->getType();
3620 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3621 assert(BaseDecl && "base isn't a CXXRecordDecl");
3622
3623 // -- any [direct base class] of a type with a destructor that is deleted or
3624 // inaccessible from the defaulted constructor
3625 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3626 if (BaseDtor->isDeleted())
3627 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003628 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003629 AR_accessible)
3630 return true;
3631
3632 // -- a [direct base class] B that cannot be [copied] because overload
3633 // resolution, as applied to B's [copy] constructor, results in an
3634 // ambiguity or a function that is deleted or inaccessible from the
3635 // defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003636 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003637 if (!BaseCtor || BaseCtor->isDeleted())
3638 return true;
3639 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3640 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003641 return true;
3642 }
3643
3644 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3645 BE = RD->vbases_end();
3646 BI != BE; ++BI) {
3647 QualType BaseType = BI->getType();
3648 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3649 assert(BaseDecl && "base isn't a CXXRecordDecl");
3650
Sean Huntb320e0c2011-06-10 03:50:41 +00003651 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003652 // inaccessible from the defaulted constructor
3653 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3654 if (BaseDtor->isDeleted())
3655 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003656 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003657 AR_accessible)
3658 return true;
3659
3660 // -- a [virtual base class] B that cannot be [copied] because overload
3661 // resolution, as applied to B's [copy] constructor, results in an
3662 // ambiguity or a function that is deleted or inaccessible from the
3663 // defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003664 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003665 if (!BaseCtor || BaseCtor->isDeleted())
3666 return true;
3667 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3668 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003669 return true;
3670 }
3671
3672 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3673 FE = RD->field_end();
3674 FI != FE; ++FI) {
3675 QualType FieldType = Context.getBaseElementType(FI->getType());
3676
3677 // -- for a copy constructor, a non-static data member of rvalue reference
3678 // type
3679 if (FieldType->isRValueReferenceType())
3680 return true;
3681
3682 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3683
3684 if (FieldRecord) {
3685 // This is an anonymous union
3686 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3687 // Anonymous unions inside unions do not variant members create
3688 if (!Union) {
3689 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3690 UE = FieldRecord->field_end();
3691 UI != UE; ++UI) {
3692 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3693 CXXRecordDecl *UnionFieldRecord =
3694 UnionFieldType->getAsCXXRecordDecl();
3695
3696 // -- a variant member with a non-trivial [copy] constructor and X
3697 // is a union-like class
3698 if (UnionFieldRecord &&
3699 !UnionFieldRecord->hasTrivialCopyConstructor())
3700 return true;
3701 }
3702 }
3703
3704 // Don't try to initalize an anonymous union
3705 continue;
3706 } else {
3707 // -- a variant member with a non-trivial [copy] constructor and X is a
3708 // union-like class
3709 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3710 return true;
3711
3712 // -- any [non-static data member] of a type with a destructor that is
3713 // deleted or inaccessible from the defaulted constructor
3714 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3715 if (FieldDtor->isDeleted())
3716 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003717 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003718 AR_accessible)
3719 return true;
3720 }
Sean Huntc530d172011-06-10 04:44:37 +00003721
3722 // -- a [non-static data member of class type (or array thereof)] B that
3723 // cannot be [copied] because overload resolution, as applied to B's
3724 // [copy] constructor, results in an ambiguity or a function that is
3725 // deleted or inaccessible from the defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003726 CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3727 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003728 if (!FieldCtor || FieldCtor->isDeleted())
3729 return true;
3730 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3731 PDiag()) != AR_accessible)
3732 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00003733 }
Sean Hunt49634cf2011-05-13 06:10:58 +00003734 }
3735
3736 return false;
3737}
3738
Sean Hunt7f410192011-05-14 05:23:24 +00003739bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3740 CXXRecordDecl *RD = MD->getParent();
3741 assert(!RD->isDependentType() && "do deletion after instantiation");
3742 if (!LangOpts.CPlusPlus0x)
3743 return false;
3744
Sean Hunt71a682f2011-05-18 03:41:58 +00003745 SourceLocation Loc = MD->getLocation();
3746
Sean Hunt7f410192011-05-14 05:23:24 +00003747 // Do access control from the constructor
3748 ContextRAII MethodContext(*this, MD);
3749
3750 bool Union = RD->isUnion();
3751
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003752 bool ConstArg =
3753 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Sean Hunt7f410192011-05-14 05:23:24 +00003754
3755 // We do this because we should never actually use an anonymous
3756 // union's constructor.
3757 if (Union && RD->isAnonymousStructOrUnion())
3758 return false;
3759
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003760 DeclarationName OperatorName =
3761 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3762 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3763 R.suppressDiagnostics();
3764
Sean Hunt7f410192011-05-14 05:23:24 +00003765 // FIXME: We should put some diagnostic logic right into this function.
3766
3767 // C++0x [class.copy]/11
3768 // A defaulted [copy] assignment operator for class X is defined as deleted
3769 // if X has:
3770
3771 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3772 BE = RD->bases_end();
3773 BI != BE; ++BI) {
3774 // We'll handle this one later
3775 if (BI->isVirtual())
3776 continue;
3777
3778 QualType BaseType = BI->getType();
3779 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3780 assert(BaseDecl && "base isn't a CXXRecordDecl");
3781
3782 // -- a [direct base class] B that cannot be [copied] because overload
3783 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003784 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00003785 // assignment operator
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003786
3787 LookupQualifiedName(R, BaseDecl, false);
3788
3789 // Filter out any result that isn't a copy-assignment operator.
3790 LookupResult::Filter F = R.makeFilter();
3791 while (F.hasNext()) {
3792 NamedDecl *D = F.next();
3793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3794 if (Method->isCopyAssignmentOperator())
3795 continue;
3796
3797 F.erase();
3798 }
3799 F.done();
3800
3801 // Build a fake argument expression
3802 QualType ArgType = BaseType;
3803 QualType ThisType = BaseType;
3804 if (ConstArg)
3805 ArgType.addConst();
3806 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3807 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3808 };
3809
3810 OverloadCandidateSet OCS((Loc));
3811 OverloadCandidateSet::iterator Best;
3812
3813 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3814
3815 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3816 OR_Success)
Sean Hunt7f410192011-05-14 05:23:24 +00003817 return true;
3818 }
3819
3820 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3821 BE = RD->vbases_end();
3822 BI != BE; ++BI) {
3823 QualType BaseType = BI->getType();
3824 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3825 assert(BaseDecl && "base isn't a CXXRecordDecl");
3826
Sean Hunt7f410192011-05-14 05:23:24 +00003827 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00003828 // resolution, as applied to B's [copy] assignment operator, results in
3829 // an ambiguity or a function that is deleted or inaccessible from the
3830 // assignment operator
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003831
3832 LookupQualifiedName(R, BaseDecl, false);
3833
3834 // Filter out any result that isn't a copy-assignment operator.
3835 LookupResult::Filter F = R.makeFilter();
3836 while (F.hasNext()) {
3837 NamedDecl *D = F.next();
3838 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3839 if (Method->isCopyAssignmentOperator())
3840 continue;
3841
3842 F.erase();
3843 }
3844 F.done();
3845
3846 // Build a fake argument expression
3847 QualType ArgType = BaseType;
3848 QualType ThisType = BaseType;
3849 if (ConstArg)
3850 ArgType.addConst();
3851 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3852 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3853 };
3854
3855 OverloadCandidateSet OCS((Loc));
3856 OverloadCandidateSet::iterator Best;
3857
3858 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3859
3860 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3861 OR_Success)
Sean Hunt7f410192011-05-14 05:23:24 +00003862 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00003863 }
3864
3865 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3866 FE = RD->field_end();
3867 FI != FE; ++FI) {
3868 QualType FieldType = Context.getBaseElementType(FI->getType());
3869
3870 // -- a non-static data member of reference type
3871 if (FieldType->isReferenceType())
3872 return true;
3873
3874 // -- a non-static data member of const non-class type (or array thereof)
3875 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3876 return true;
3877
3878 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3879
3880 if (FieldRecord) {
3881 // This is an anonymous union
3882 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3883 // Anonymous unions inside unions do not variant members create
3884 if (!Union) {
3885 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3886 UE = FieldRecord->field_end();
3887 UI != UE; ++UI) {
3888 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3889 CXXRecordDecl *UnionFieldRecord =
3890 UnionFieldType->getAsCXXRecordDecl();
3891
3892 // -- a variant member with a non-trivial [copy] assignment operator
3893 // and X is a union-like class
3894 if (UnionFieldRecord &&
3895 !UnionFieldRecord->hasTrivialCopyAssignment())
3896 return true;
3897 }
3898 }
3899
3900 // Don't try to initalize an anonymous union
3901 continue;
3902 // -- a variant member with a non-trivial [copy] assignment operator
3903 // and X is a union-like class
3904 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3905 return true;
3906 }
Sean Hunt7f410192011-05-14 05:23:24 +00003907
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003908 LookupQualifiedName(R, FieldRecord, false);
3909
3910 // Filter out any result that isn't a copy-assignment operator.
3911 LookupResult::Filter F = R.makeFilter();
3912 while (F.hasNext()) {
3913 NamedDecl *D = F.next();
3914 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3915 if (Method->isCopyAssignmentOperator())
3916 continue;
3917
3918 F.erase();
3919 }
3920 F.done();
3921
3922 // Build a fake argument expression
3923 QualType ArgType = FieldType;
3924 QualType ThisType = FieldType;
3925 if (ConstArg)
3926 ArgType.addConst();
3927 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3928 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3929 };
3930
3931 OverloadCandidateSet OCS((Loc));
3932 OverloadCandidateSet::iterator Best;
3933
3934 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3935
3936 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3937 OR_Success)
3938 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00003939 }
Sean Hunt7f410192011-05-14 05:23:24 +00003940 }
3941
3942 return false;
3943}
3944
Sean Huntcb45a0f2011-05-12 22:46:25 +00003945bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3946 CXXRecordDecl *RD = DD->getParent();
3947 assert(!RD->isDependentType() && "do deletion after instantiation");
3948 if (!LangOpts.CPlusPlus0x)
3949 return false;
3950
Sean Hunt71a682f2011-05-18 03:41:58 +00003951 SourceLocation Loc = DD->getLocation();
3952
Sean Huntcb45a0f2011-05-12 22:46:25 +00003953 // Do access control from the destructor
3954 ContextRAII CtorContext(*this, DD);
3955
3956 bool Union = RD->isUnion();
3957
Sean Hunt49634cf2011-05-13 06:10:58 +00003958 // We do this because we should never actually use an anonymous
3959 // union's destructor.
3960 if (Union && RD->isAnonymousStructOrUnion())
3961 return false;
3962
Sean Huntcb45a0f2011-05-12 22:46:25 +00003963 // C++0x [class.dtor]p5
3964 // A defaulted destructor for a class X is defined as deleted if:
3965 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3966 BE = RD->bases_end();
3967 BI != BE; ++BI) {
3968 // We'll handle this one later
3969 if (BI->isVirtual())
3970 continue;
3971
3972 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3973 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3974 assert(BaseDtor && "base has no destructor");
3975
3976 // -- any direct or virtual base class has a deleted destructor or
3977 // a destructor that is inaccessible from the defaulted destructor
3978 if (BaseDtor->isDeleted())
3979 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003980 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003981 AR_accessible)
3982 return true;
3983 }
3984
3985 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3986 BE = RD->vbases_end();
3987 BI != BE; ++BI) {
3988 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3989 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3990 assert(BaseDtor && "base has no destructor");
3991
3992 // -- any direct or virtual base class has a deleted destructor or
3993 // a destructor that is inaccessible from the defaulted destructor
3994 if (BaseDtor->isDeleted())
3995 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003996 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003997 AR_accessible)
3998 return true;
3999 }
4000
4001 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4002 FE = RD->field_end();
4003 FI != FE; ++FI) {
4004 QualType FieldType = Context.getBaseElementType(FI->getType());
4005 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4006 if (FieldRecord) {
4007 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4008 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4009 UE = FieldRecord->field_end();
4010 UI != UE; ++UI) {
4011 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4012 CXXRecordDecl *UnionFieldRecord =
4013 UnionFieldType->getAsCXXRecordDecl();
4014
4015 // -- X is a union-like class that has a variant member with a non-
4016 // trivial destructor.
4017 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4018 return true;
4019 }
4020 // Technically we are supposed to do this next check unconditionally.
4021 // But that makes absolutely no sense.
4022 } else {
4023 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4024
4025 // -- any of the non-static data members has class type M (or array
4026 // thereof) and M has a deleted destructor or a destructor that is
4027 // inaccessible from the defaulted destructor
4028 if (FieldDtor->isDeleted())
4029 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004030 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004031 AR_accessible)
4032 return true;
4033
4034 // -- X is a union-like class that has a variant member with a non-
4035 // trivial destructor.
4036 if (Union && !FieldDtor->isTrivial())
4037 return true;
4038 }
4039 }
4040 }
4041
4042 if (DD->isVirtual()) {
4043 FunctionDecl *OperatorDelete = 0;
4044 DeclarationName Name =
4045 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004046 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004047 false))
4048 return true;
4049 }
4050
4051
4052 return false;
4053}
4054
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004055/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004056namespace {
4057 struct FindHiddenVirtualMethodData {
4058 Sema *S;
4059 CXXMethodDecl *Method;
4060 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4061 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4062 };
4063}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004064
4065/// \brief Member lookup function that determines whether a given C++
4066/// method overloads virtual methods in a base class without overriding any,
4067/// to be used with CXXRecordDecl::lookupInBases().
4068static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4069 CXXBasePath &Path,
4070 void *UserData) {
4071 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4072
4073 FindHiddenVirtualMethodData &Data
4074 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4075
4076 DeclarationName Name = Data.Method->getDeclName();
4077 assert(Name.getNameKind() == DeclarationName::Identifier);
4078
4079 bool foundSameNameMethod = false;
4080 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4081 for (Path.Decls = BaseRecord->lookup(Name);
4082 Path.Decls.first != Path.Decls.second;
4083 ++Path.Decls.first) {
4084 NamedDecl *D = *Path.Decls.first;
4085 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004086 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004087 foundSameNameMethod = true;
4088 // Interested only in hidden virtual methods.
4089 if (!MD->isVirtual())
4090 continue;
4091 // If the method we are checking overrides a method from its base
4092 // don't warn about the other overloaded methods.
4093 if (!Data.S->IsOverload(Data.Method, MD, false))
4094 return true;
4095 // Collect the overload only if its hidden.
4096 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4097 overloadedMethods.push_back(MD);
4098 }
4099 }
4100
4101 if (foundSameNameMethod)
4102 Data.OverloadedMethods.append(overloadedMethods.begin(),
4103 overloadedMethods.end());
4104 return foundSameNameMethod;
4105}
4106
4107/// \brief See if a method overloads virtual methods in a base class without
4108/// overriding any.
4109void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4110 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4111 MD->getLocation()) == Diagnostic::Ignored)
4112 return;
4113 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4114 return;
4115
4116 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4117 /*bool RecordPaths=*/false,
4118 /*bool DetectVirtual=*/false);
4119 FindHiddenVirtualMethodData Data;
4120 Data.Method = MD;
4121 Data.S = this;
4122
4123 // Keep the base methods that were overriden or introduced in the subclass
4124 // by 'using' in a set. A base method not in this set is hidden.
4125 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4126 res.first != res.second; ++res.first) {
4127 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4128 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4129 E = MD->end_overridden_methods();
4130 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004131 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004132 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4133 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004134 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004135 }
4136
4137 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4138 !Data.OverloadedMethods.empty()) {
4139 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4140 << MD << (Data.OverloadedMethods.size() > 1);
4141
4142 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4143 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4144 Diag(overloadedMD->getLocation(),
4145 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4146 }
4147 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004148}
4149
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004150void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004151 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004152 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004153 SourceLocation RBrac,
4154 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004155 if (!TagDecl)
4156 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Douglas Gregor42af25f2009-05-11 19:58:34 +00004158 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004159
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004160 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004161 // strict aliasing violation!
4162 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004163 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004164
Douglas Gregor23c94db2010-07-02 17:43:08 +00004165 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004166 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004167}
4168
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004169/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4170/// special functions, such as the default constructor, copy
4171/// constructor, or destructor, to the given C++ class (C++
4172/// [special]p1). This routine can only be executed just before the
4173/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004174void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004175 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004176 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004177
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004178 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004179 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004180
Douglas Gregora376d102010-07-02 21:50:04 +00004181 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4182 ++ASTContext::NumImplicitCopyAssignmentOperators;
4183
4184 // If we have a dynamic class, then the copy assignment operator may be
4185 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4186 // it shows up in the right place in the vtable and that we diagnose
4187 // problems with the implicit exception specification.
4188 if (ClassDecl->isDynamicClass())
4189 DeclareImplicitCopyAssignment(ClassDecl);
4190 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004191
Douglas Gregor4923aa22010-07-02 20:37:36 +00004192 if (!ClassDecl->hasUserDeclaredDestructor()) {
4193 ++ASTContext::NumImplicitDestructors;
4194
4195 // If we have a dynamic class, then the destructor may be virtual, so we
4196 // have to declare the destructor immediately. This ensures that, e.g., it
4197 // shows up in the right place in the vtable and that we diagnose problems
4198 // with the implicit exception specification.
4199 if (ClassDecl->isDynamicClass())
4200 DeclareImplicitDestructor(ClassDecl);
4201 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004202}
4203
Francois Pichet8387e2a2011-04-22 22:18:13 +00004204void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4205 if (!D)
4206 return;
4207
4208 int NumParamList = D->getNumTemplateParameterLists();
4209 for (int i = 0; i < NumParamList; i++) {
4210 TemplateParameterList* Params = D->getTemplateParameterList(i);
4211 for (TemplateParameterList::iterator Param = Params->begin(),
4212 ParamEnd = Params->end();
4213 Param != ParamEnd; ++Param) {
4214 NamedDecl *Named = cast<NamedDecl>(*Param);
4215 if (Named->getDeclName()) {
4216 S->AddDecl(Named);
4217 IdResolver.AddDecl(Named);
4218 }
4219 }
4220 }
4221}
4222
John McCalld226f652010-08-21 09:40:31 +00004223void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004224 if (!D)
4225 return;
4226
4227 TemplateParameterList *Params = 0;
4228 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4229 Params = Template->getTemplateParameters();
4230 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4231 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4232 Params = PartialSpec->getTemplateParameters();
4233 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004234 return;
4235
Douglas Gregor6569d682009-05-27 23:11:45 +00004236 for (TemplateParameterList::iterator Param = Params->begin(),
4237 ParamEnd = Params->end();
4238 Param != ParamEnd; ++Param) {
4239 NamedDecl *Named = cast<NamedDecl>(*Param);
4240 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004241 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004242 IdResolver.AddDecl(Named);
4243 }
4244 }
4245}
4246
John McCalld226f652010-08-21 09:40:31 +00004247void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004248 if (!RecordD) return;
4249 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004250 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004251 PushDeclContext(S, Record);
4252}
4253
John McCalld226f652010-08-21 09:40:31 +00004254void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004255 if (!RecordD) return;
4256 PopDeclContext();
4257}
4258
Douglas Gregor72b505b2008-12-16 21:30:33 +00004259/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4260/// parsing a top-level (non-nested) C++ class, and we are now
4261/// parsing those parts of the given Method declaration that could
4262/// not be parsed earlier (C++ [class.mem]p2), such as default
4263/// arguments. This action should enter the scope of the given
4264/// Method declaration as if we had just parsed the qualified method
4265/// name. However, it should not bring the parameters into scope;
4266/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004267void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004268}
4269
4270/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4271/// C++ method declaration. We're (re-)introducing the given
4272/// function parameter into scope for use in parsing later parts of
4273/// the method declaration. For example, we could see an
4274/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004275void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004276 if (!ParamD)
4277 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004278
John McCalld226f652010-08-21 09:40:31 +00004279 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004280
4281 // If this parameter has an unparsed default argument, clear it out
4282 // to make way for the parsed default argument.
4283 if (Param->hasUnparsedDefaultArg())
4284 Param->setDefaultArg(0);
4285
John McCalld226f652010-08-21 09:40:31 +00004286 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004287 if (Param->getDeclName())
4288 IdResolver.AddDecl(Param);
4289}
4290
4291/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4292/// processing the delayed method declaration for Method. The method
4293/// declaration is now considered finished. There may be a separate
4294/// ActOnStartOfFunctionDef action later (not necessarily
4295/// immediately!) for this method, if it was also defined inside the
4296/// class body.
John McCalld226f652010-08-21 09:40:31 +00004297void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004298 if (!MethodD)
4299 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004301 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004302
John McCalld226f652010-08-21 09:40:31 +00004303 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004304
4305 // Now that we have our default arguments, check the constructor
4306 // again. It could produce additional diagnostics or affect whether
4307 // the class has implicitly-declared destructors, among other
4308 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004309 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4310 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004311
4312 // Check the default arguments, which we may have added.
4313 if (!Method->isInvalidDecl())
4314 CheckCXXDefaultArguments(Method);
4315}
4316
Douglas Gregor42a552f2008-11-05 20:51:48 +00004317/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004318/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004319/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004320/// emit diagnostics and set the invalid bit to true. In any case, the type
4321/// will be updated to reflect a well-formed type for the constructor and
4322/// returned.
4323QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004324 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004325 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004326
4327 // C++ [class.ctor]p3:
4328 // A constructor shall not be virtual (10.3) or static (9.4). A
4329 // constructor can be invoked for a const, volatile or const
4330 // volatile object. A constructor shall not be declared const,
4331 // volatile, or const volatile (9.3.2).
4332 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004333 if (!D.isInvalidType())
4334 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4335 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4336 << SourceRange(D.getIdentifierLoc());
4337 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004338 }
John McCalld931b082010-08-26 03:08:43 +00004339 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004340 if (!D.isInvalidType())
4341 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4342 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4343 << SourceRange(D.getIdentifierLoc());
4344 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004345 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004346 }
Mike Stump1eb44332009-09-09 15:08:12 +00004347
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004348 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004349 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004350 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004351 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4352 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004353 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004354 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4355 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004356 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004357 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4358 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004359 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004360 }
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Douglas Gregorc938c162011-01-26 05:01:58 +00004362 // C++0x [class.ctor]p4:
4363 // A constructor shall not be declared with a ref-qualifier.
4364 if (FTI.hasRefQualifier()) {
4365 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4366 << FTI.RefQualifierIsLValueRef
4367 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4368 D.setInvalidType();
4369 }
4370
Douglas Gregor42a552f2008-11-05 20:51:48 +00004371 // Rebuild the function type "R" without any type qualifiers (in
4372 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004373 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004374 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004375 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4376 return R;
4377
4378 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4379 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004380 EPI.RefQualifier = RQ_None;
4381
Chris Lattner65401802009-04-25 08:28:21 +00004382 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004383 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004384}
4385
Douglas Gregor72b505b2008-12-16 21:30:33 +00004386/// CheckConstructor - Checks a fully-formed constructor for
4387/// well-formedness, issuing any diagnostics required. Returns true if
4388/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004389void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004390 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004391 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4392 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004393 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004394
4395 // C++ [class.copy]p3:
4396 // A declaration of a constructor for a class X is ill-formed if
4397 // its first parameter is of type (optionally cv-qualified) X and
4398 // either there are no other parameters or else all other
4399 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004400 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004401 ((Constructor->getNumParams() == 1) ||
4402 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004403 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4404 Constructor->getTemplateSpecializationKind()
4405 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004406 QualType ParamType = Constructor->getParamDecl(0)->getType();
4407 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4408 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004409 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004410 const char *ConstRef
4411 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4412 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004413 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004414 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004415
4416 // FIXME: Rather that making the constructor invalid, we should endeavor
4417 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004418 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004419 }
4420 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004421}
4422
John McCall15442822010-08-04 01:04:25 +00004423/// CheckDestructor - Checks a fully-formed destructor definition for
4424/// well-formedness, issuing any diagnostics required. Returns true
4425/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004426bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004427 CXXRecordDecl *RD = Destructor->getParent();
4428
4429 if (Destructor->isVirtual()) {
4430 SourceLocation Loc;
4431
4432 if (!Destructor->isImplicit())
4433 Loc = Destructor->getLocation();
4434 else
4435 Loc = RD->getLocation();
4436
4437 // If we have a virtual destructor, look up the deallocation function
4438 FunctionDecl *OperatorDelete = 0;
4439 DeclarationName Name =
4440 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004441 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004442 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004443
4444 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004445
4446 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004447 }
Anders Carlsson37909802009-11-30 21:24:50 +00004448
4449 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004450}
4451
Mike Stump1eb44332009-09-09 15:08:12 +00004452static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004453FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4454 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4455 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004456 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004457}
4458
Douglas Gregor42a552f2008-11-05 20:51:48 +00004459/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4460/// the well-formednes of the destructor declarator @p D with type @p
4461/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004462/// emit diagnostics and set the declarator to invalid. Even if this happens,
4463/// will be updated to reflect a well-formed type for the destructor and
4464/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004465QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004466 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004467 // C++ [class.dtor]p1:
4468 // [...] A typedef-name that names a class is a class-name
4469 // (7.1.3); however, a typedef-name that names a class shall not
4470 // be used as the identifier in the declarator for a destructor
4471 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004472 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004473 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004474 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004475 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004476 else if (const TemplateSpecializationType *TST =
4477 DeclaratorType->getAs<TemplateSpecializationType>())
4478 if (TST->isTypeAlias())
4479 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4480 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004481
4482 // C++ [class.dtor]p2:
4483 // A destructor is used to destroy objects of its class type. A
4484 // destructor takes no parameters, and no return type can be
4485 // specified for it (not even void). The address of a destructor
4486 // shall not be taken. A destructor shall not be static. A
4487 // destructor can be invoked for a const, volatile or const
4488 // volatile object. A destructor shall not be declared const,
4489 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004490 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004491 if (!D.isInvalidType())
4492 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4493 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004494 << SourceRange(D.getIdentifierLoc())
4495 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4496
John McCalld931b082010-08-26 03:08:43 +00004497 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004498 }
Chris Lattner65401802009-04-25 08:28:21 +00004499 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004500 // Destructors don't have return types, but the parser will
4501 // happily parse something like:
4502 //
4503 // class X {
4504 // float ~X();
4505 // };
4506 //
4507 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004508 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4509 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4510 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004511 }
Mike Stump1eb44332009-09-09 15:08:12 +00004512
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004513 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004514 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004515 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004516 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4517 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004518 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004519 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4520 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004521 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004522 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4523 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004524 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004525 }
4526
Douglas Gregorc938c162011-01-26 05:01:58 +00004527 // C++0x [class.dtor]p2:
4528 // A destructor shall not be declared with a ref-qualifier.
4529 if (FTI.hasRefQualifier()) {
4530 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4531 << FTI.RefQualifierIsLValueRef
4532 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4533 D.setInvalidType();
4534 }
4535
Douglas Gregor42a552f2008-11-05 20:51:48 +00004536 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004537 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004538 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4539
4540 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004541 FTI.freeArgs();
4542 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004543 }
4544
Mike Stump1eb44332009-09-09 15:08:12 +00004545 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004546 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004547 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004548 D.setInvalidType();
4549 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004550
4551 // Rebuild the function type "R" without any type qualifiers or
4552 // parameters (in case any of the errors above fired) and with
4553 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004554 // types.
John McCalle23cf432010-12-14 08:05:40 +00004555 if (!D.isInvalidType())
4556 return R;
4557
Douglas Gregord92ec472010-07-01 05:10:53 +00004558 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004559 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4560 EPI.Variadic = false;
4561 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004562 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004563 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004564}
4565
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004566/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4567/// well-formednes of the conversion function declarator @p D with
4568/// type @p R. If there are any errors in the declarator, this routine
4569/// will emit diagnostics and return true. Otherwise, it will return
4570/// false. Either way, the type @p R will be updated to reflect a
4571/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004572void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004573 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004574 // C++ [class.conv.fct]p1:
4575 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004576 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004577 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004578 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004579 if (!D.isInvalidType())
4580 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4581 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4582 << SourceRange(D.getIdentifierLoc());
4583 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004584 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004585 }
John McCalla3f81372010-04-13 00:04:31 +00004586
4587 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4588
Chris Lattner6e475012009-04-25 08:35:12 +00004589 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004590 // Conversion functions don't have return types, but the parser will
4591 // happily parse something like:
4592 //
4593 // class X {
4594 // float operator bool();
4595 // };
4596 //
4597 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004598 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4599 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4600 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004601 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004602 }
4603
John McCalla3f81372010-04-13 00:04:31 +00004604 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4605
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004606 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004607 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004608 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4609
4610 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004611 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004612 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004613 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004614 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004615 D.setInvalidType();
4616 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004617
John McCalla3f81372010-04-13 00:04:31 +00004618 // Diagnose "&operator bool()" and other such nonsense. This
4619 // is actually a gcc extension which we don't support.
4620 if (Proto->getResultType() != ConvType) {
4621 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4622 << Proto->getResultType();
4623 D.setInvalidType();
4624 ConvType = Proto->getResultType();
4625 }
4626
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004627 // C++ [class.conv.fct]p4:
4628 // The conversion-type-id shall not represent a function type nor
4629 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004630 if (ConvType->isArrayType()) {
4631 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4632 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004633 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004634 } else if (ConvType->isFunctionType()) {
4635 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4636 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004637 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004638 }
4639
4640 // Rebuild the function type "R" without any parameters (in case any
4641 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00004642 // return type.
John McCalle23cf432010-12-14 08:05:40 +00004643 if (D.isInvalidType())
4644 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004645
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004646 // C++0x explicit conversion operators.
4647 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00004648 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004649 diag::warn_explicit_conversion_functions)
4650 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004651}
4652
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004653/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4654/// the declaration of the given C++ conversion function. This routine
4655/// is responsible for recording the conversion function in the C++
4656/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00004657Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004658 assert(Conversion && "Expected to receive a conversion function declaration");
4659
Douglas Gregor9d350972008-12-12 08:25:50 +00004660 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004661
4662 // Make sure we aren't redeclaring the conversion function.
4663 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004664
4665 // C++ [class.conv.fct]p1:
4666 // [...] A conversion function is never used to convert a
4667 // (possibly cv-qualified) object to the (possibly cv-qualified)
4668 // same object type (or a reference to it), to a (possibly
4669 // cv-qualified) base class of that type (or a reference to it),
4670 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004671 // FIXME: Suppress this warning if the conversion function ends up being a
4672 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004673 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004674 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004675 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004676 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004677 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4678 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004679 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004680 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004681 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4682 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004683 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004684 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004685 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004686 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004687 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004688 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004689 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004690 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004691 }
4692
Douglas Gregore80622f2010-09-29 04:25:11 +00004693 if (FunctionTemplateDecl *ConversionTemplate
4694 = Conversion->getDescribedFunctionTemplate())
4695 return ConversionTemplate;
4696
John McCalld226f652010-08-21 09:40:31 +00004697 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004698}
4699
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004700//===----------------------------------------------------------------------===//
4701// Namespace Handling
4702//===----------------------------------------------------------------------===//
4703
John McCallea318642010-08-26 09:15:37 +00004704
4705
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004706/// ActOnStartNamespaceDef - This is called at the start of a namespace
4707/// definition.
John McCalld226f652010-08-21 09:40:31 +00004708Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004709 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004710 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004711 SourceLocation IdentLoc,
4712 IdentifierInfo *II,
4713 SourceLocation LBrace,
4714 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004715 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4716 // For anonymous namespace, take the location of the left brace.
4717 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004718 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004719 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004720 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004721
4722 Scope *DeclRegionScope = NamespcScope->getParent();
4723
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004724 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4725
John McCall90f14502010-12-10 02:59:44 +00004726 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4727 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004728
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004729 if (II) {
4730 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004731 // The identifier in an original-namespace-definition shall not
4732 // have been previously defined in the declarative region in
4733 // which the original-namespace-definition appears. The
4734 // identifier in an original-namespace-definition is the name of
4735 // the namespace. Subsequently in that declarative region, it is
4736 // treated as an original-namespace-name.
4737 //
4738 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004739 // look through using directives, just look for any ordinary names.
4740
4741 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4742 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4743 Decl::IDNS_Namespace;
4744 NamedDecl *PrevDecl = 0;
4745 for (DeclContext::lookup_result R
4746 = CurContext->getRedeclContext()->lookup(II);
4747 R.first != R.second; ++R.first) {
4748 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4749 PrevDecl = *R.first;
4750 break;
4751 }
4752 }
4753
Douglas Gregor44b43212008-12-11 16:49:14 +00004754 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4755 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004756 if (Namespc->isInline() != OrigNS->isInline()) {
4757 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004758 if (OrigNS->isInline()) {
4759 // The user probably just forgot the 'inline', so suggest that it
4760 // be added back.
4761 Diag(Namespc->getLocation(),
4762 diag::warn_inline_namespace_reopened_noninline)
4763 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4764 } else {
4765 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4766 << Namespc->isInline();
4767 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004768 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004769
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004770 // Recover by ignoring the new namespace's inline status.
4771 Namespc->setInline(OrigNS->isInline());
4772 }
4773
Douglas Gregor44b43212008-12-11 16:49:14 +00004774 // Attach this namespace decl to the chain of extended namespace
4775 // definitions.
4776 OrigNS->setNextNamespace(Namespc);
4777 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004778
Mike Stump1eb44332009-09-09 15:08:12 +00004779 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004780 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004781 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004782 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004783 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004784 } else if (PrevDecl) {
4785 // This is an invalid name redefinition.
4786 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4787 << Namespc->getDeclName();
4788 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4789 Namespc->setInvalidDecl();
4790 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004791 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004792 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004793 // This is the first "real" definition of the namespace "std", so update
4794 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004795 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004796 // We had already defined a dummy namespace "std". Link this new
4797 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004798 StdNS->setNextNamespace(Namespc);
4799 StdNS->setLocation(IdentLoc);
4800 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004801 }
4802
4803 // Make our StdNamespace cache point at the first real definition of the
4804 // "std" namespace.
4805 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00004806 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004807
4808 PushOnScopeChains(Namespc, DeclRegionScope);
4809 } else {
John McCall9aeed322009-10-01 00:25:31 +00004810 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004811 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004812
4813 // Link the anonymous namespace into its parent.
4814 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004815 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004816 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4817 PrevDecl = TU->getAnonymousNamespace();
4818 TU->setAnonymousNamespace(Namespc);
4819 } else {
4820 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4821 PrevDecl = ND->getAnonymousNamespace();
4822 ND->setAnonymousNamespace(Namespc);
4823 }
4824
4825 // Link the anonymous namespace with its previous declaration.
4826 if (PrevDecl) {
4827 assert(PrevDecl->isAnonymousNamespace());
4828 assert(!PrevDecl->getNextNamespace());
4829 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4830 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004831
4832 if (Namespc->isInline() != PrevDecl->isInline()) {
4833 // inline-ness must match
4834 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4835 << Namespc->isInline();
4836 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4837 Namespc->setInvalidDecl();
4838 // Recover by ignoring the new namespace's inline status.
4839 Namespc->setInline(PrevDecl->isInline());
4840 }
John McCall5fdd7642009-12-16 02:06:49 +00004841 }
John McCall9aeed322009-10-01 00:25:31 +00004842
Douglas Gregora4181472010-03-24 00:46:35 +00004843 CurContext->addDecl(Namespc);
4844
John McCall9aeed322009-10-01 00:25:31 +00004845 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4846 // behaves as if it were replaced by
4847 // namespace unique { /* empty body */ }
4848 // using namespace unique;
4849 // namespace unique { namespace-body }
4850 // where all occurrences of 'unique' in a translation unit are
4851 // replaced by the same identifier and this identifier differs
4852 // from all other identifiers in the entire program.
4853
4854 // We just create the namespace with an empty name and then add an
4855 // implicit using declaration, just like the standard suggests.
4856 //
4857 // CodeGen enforces the "universally unique" aspect by giving all
4858 // declarations semantically contained within an anonymous
4859 // namespace internal linkage.
4860
John McCall5fdd7642009-12-16 02:06:49 +00004861 if (!PrevDecl) {
4862 UsingDirectiveDecl* UD
4863 = UsingDirectiveDecl::Create(Context, CurContext,
4864 /* 'using' */ LBrace,
4865 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004866 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004867 /* identifier */ SourceLocation(),
4868 Namespc,
4869 /* Ancestor */ CurContext);
4870 UD->setImplicit();
4871 CurContext->addDecl(UD);
4872 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004873 }
4874
4875 // Although we could have an invalid decl (i.e. the namespace name is a
4876 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004877 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4878 // for the namespace has the declarations that showed up in that particular
4879 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004880 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004881 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004882}
4883
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004884/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4885/// is a namespace alias, returns the namespace it points to.
4886static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4887 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4888 return AD->getNamespace();
4889 return dyn_cast_or_null<NamespaceDecl>(D);
4890}
4891
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004892/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4893/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004894void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004895 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4896 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004897 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004898 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004899 if (Namespc->hasAttr<VisibilityAttr>())
4900 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004901}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004902
John McCall384aff82010-08-25 07:42:41 +00004903CXXRecordDecl *Sema::getStdBadAlloc() const {
4904 return cast_or_null<CXXRecordDecl>(
4905 StdBadAlloc.get(Context.getExternalSource()));
4906}
4907
4908NamespaceDecl *Sema::getStdNamespace() const {
4909 return cast_or_null<NamespaceDecl>(
4910 StdNamespace.get(Context.getExternalSource()));
4911}
4912
Douglas Gregor66992202010-06-29 17:53:46 +00004913/// \brief Retrieve the special "std" namespace, which may require us to
4914/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004915NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004916 if (!StdNamespace) {
4917 // The "std" namespace has not yet been defined, so build one implicitly.
4918 StdNamespace = NamespaceDecl::Create(Context,
4919 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004920 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004921 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004922 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004923 }
4924
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004925 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004926}
4927
Douglas Gregor9172aa62011-03-26 22:25:30 +00004928/// \brief Determine whether a using statement is in a context where it will be
4929/// apply in all contexts.
4930static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4931 switch (CurContext->getDeclKind()) {
4932 case Decl::TranslationUnit:
4933 return true;
4934 case Decl::LinkageSpec:
4935 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4936 default:
4937 return false;
4938 }
4939}
4940
John McCalld226f652010-08-21 09:40:31 +00004941Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004942 SourceLocation UsingLoc,
4943 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004944 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004945 SourceLocation IdentLoc,
4946 IdentifierInfo *NamespcName,
4947 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004948 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4949 assert(NamespcName && "Invalid NamespcName.");
4950 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004951
4952 // This can only happen along a recovery path.
4953 while (S->getFlags() & Scope::TemplateParamScope)
4954 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004955 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004956
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004957 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004958 NestedNameSpecifier *Qualifier = 0;
4959 if (SS.isSet())
4960 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4961
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004962 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004963 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4964 LookupParsedName(R, S, &SS);
4965 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004966 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004967
Douglas Gregor66992202010-06-29 17:53:46 +00004968 if (R.empty()) {
4969 // Allow "using namespace std;" or "using namespace ::std;" even if
4970 // "std" hasn't been defined yet, for GCC compatibility.
4971 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4972 NamespcName->isStr("std")) {
4973 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004974 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004975 R.resolveKind();
4976 }
4977 // Otherwise, attempt typo correction.
4978 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4979 CTC_NoKeywords, 0)) {
4980 if (R.getAsSingle<NamespaceDecl>() ||
4981 R.getAsSingle<NamespaceAliasDecl>()) {
4982 if (DeclContext *DC = computeDeclContext(SS, false))
4983 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4984 << NamespcName << DC << Corrected << SS.getRange()
4985 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4986 else
4987 Diag(IdentLoc, diag::err_using_directive_suggest)
4988 << NamespcName << Corrected
4989 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4990 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4991 << Corrected;
4992
4993 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004994 } else {
4995 R.clear();
4996 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00004997 }
4998 }
4999 }
5000
John McCallf36e02d2009-10-09 21:13:30 +00005001 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005002 NamedDecl *Named = R.getFoundDecl();
5003 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5004 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005005 // C++ [namespace.udir]p1:
5006 // A using-directive specifies that the names in the nominated
5007 // namespace can be used in the scope in which the
5008 // using-directive appears after the using-directive. During
5009 // unqualified name lookup (3.4.1), the names appear as if they
5010 // were declared in the nearest enclosing namespace which
5011 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005012 // namespace. [Note: in this context, "contains" means "contains
5013 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005014
5015 // Find enclosing context containing both using-directive and
5016 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005017 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005018 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5019 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5020 CommonAncestor = CommonAncestor->getParent();
5021
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005022 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005023 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005024 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005025
Douglas Gregor9172aa62011-03-26 22:25:30 +00005026 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00005027 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005028 Diag(IdentLoc, diag::warn_using_directive_in_header);
5029 }
5030
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005031 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005032 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005033 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005034 }
5035
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005036 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005037 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005038}
5039
5040void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5041 // If scope has associated entity, then using directive is at namespace
5042 // or translation unit scope. We add UsingDirectiveDecls, into
5043 // it's lookup structure.
5044 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005045 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005046 else
5047 // Otherwise it is block-sope. using-directives will affect lookup
5048 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005049 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005050}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005051
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005052
John McCalld226f652010-08-21 09:40:31 +00005053Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005054 AccessSpecifier AS,
5055 bool HasUsingKeyword,
5056 SourceLocation UsingLoc,
5057 CXXScopeSpec &SS,
5058 UnqualifiedId &Name,
5059 AttributeList *AttrList,
5060 bool IsTypeName,
5061 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005062 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005063
Douglas Gregor12c118a2009-11-04 16:30:06 +00005064 switch (Name.getKind()) {
5065 case UnqualifiedId::IK_Identifier:
5066 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005067 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005068 case UnqualifiedId::IK_ConversionFunctionId:
5069 break;
5070
5071 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005072 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005073 // C++0x inherited constructors.
5074 if (getLangOptions().CPlusPlus0x) break;
5075
Douglas Gregor12c118a2009-11-04 16:30:06 +00005076 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5077 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005078 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005079
5080 case UnqualifiedId::IK_DestructorName:
5081 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5082 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005083 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005084
5085 case UnqualifiedId::IK_TemplateId:
5086 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5087 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005088 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005089 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005090
5091 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5092 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005093 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005094 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005095
John McCall60fa3cf2009-12-11 02:10:03 +00005096 // Warn about using declarations.
5097 // TODO: store that the declaration was written without 'using' and
5098 // talk about access decls instead of using decls in the
5099 // diagnostics.
5100 if (!HasUsingKeyword) {
5101 UsingLoc = Name.getSourceRange().getBegin();
5102
5103 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005104 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005105 }
5106
Douglas Gregor56c04582010-12-16 00:46:58 +00005107 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5108 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5109 return 0;
5110
John McCall9488ea12009-11-17 05:59:44 +00005111 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005112 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005113 /* IsInstantiation */ false,
5114 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005115 if (UD)
5116 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005117
John McCalld226f652010-08-21 09:40:31 +00005118 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005119}
5120
Douglas Gregor09acc982010-07-07 23:08:52 +00005121/// \brief Determine whether a using declaration considers the given
5122/// declarations as "equivalent", e.g., if they are redeclarations of
5123/// the same entity or are both typedefs of the same type.
5124static bool
5125IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5126 bool &SuppressRedeclaration) {
5127 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5128 SuppressRedeclaration = false;
5129 return true;
5130 }
5131
Richard Smith162e1c12011-04-15 14:24:37 +00005132 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5133 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005134 SuppressRedeclaration = true;
5135 return Context.hasSameType(TD1->getUnderlyingType(),
5136 TD2->getUnderlyingType());
5137 }
5138
5139 return false;
5140}
5141
5142
John McCall9f54ad42009-12-10 09:41:52 +00005143/// Determines whether to create a using shadow decl for a particular
5144/// decl, given the set of decls existing prior to this using lookup.
5145bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5146 const LookupResult &Previous) {
5147 // Diagnose finding a decl which is not from a base class of the
5148 // current class. We do this now because there are cases where this
5149 // function will silently decide not to build a shadow decl, which
5150 // will pre-empt further diagnostics.
5151 //
5152 // We don't need to do this in C++0x because we do the check once on
5153 // the qualifier.
5154 //
5155 // FIXME: diagnose the following if we care enough:
5156 // struct A { int foo; };
5157 // struct B : A { using A::foo; };
5158 // template <class T> struct C : A {};
5159 // template <class T> struct D : C<T> { using B::foo; } // <---
5160 // This is invalid (during instantiation) in C++03 because B::foo
5161 // resolves to the using decl in B, which is not a base class of D<T>.
5162 // We can't diagnose it immediately because C<T> is an unknown
5163 // specialization. The UsingShadowDecl in D<T> then points directly
5164 // to A::foo, which will look well-formed when we instantiate.
5165 // The right solution is to not collapse the shadow-decl chain.
5166 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5167 DeclContext *OrigDC = Orig->getDeclContext();
5168
5169 // Handle enums and anonymous structs.
5170 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5171 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5172 while (OrigRec->isAnonymousStructOrUnion())
5173 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5174
5175 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5176 if (OrigDC == CurContext) {
5177 Diag(Using->getLocation(),
5178 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005179 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005180 Diag(Orig->getLocation(), diag::note_using_decl_target);
5181 return true;
5182 }
5183
Douglas Gregordc355712011-02-25 00:36:19 +00005184 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005185 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005186 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005187 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005188 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005189 Diag(Orig->getLocation(), diag::note_using_decl_target);
5190 return true;
5191 }
5192 }
5193
5194 if (Previous.empty()) return false;
5195
5196 NamedDecl *Target = Orig;
5197 if (isa<UsingShadowDecl>(Target))
5198 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5199
John McCalld7533ec2009-12-11 02:33:26 +00005200 // If the target happens to be one of the previous declarations, we
5201 // don't have a conflict.
5202 //
5203 // FIXME: but we might be increasing its access, in which case we
5204 // should redeclare it.
5205 NamedDecl *NonTag = 0, *Tag = 0;
5206 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5207 I != E; ++I) {
5208 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005209 bool Result;
5210 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5211 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005212
5213 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5214 }
5215
John McCall9f54ad42009-12-10 09:41:52 +00005216 if (Target->isFunctionOrFunctionTemplate()) {
5217 FunctionDecl *FD;
5218 if (isa<FunctionTemplateDecl>(Target))
5219 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5220 else
5221 FD = cast<FunctionDecl>(Target);
5222
5223 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005224 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005225 case Ovl_Overload:
5226 return false;
5227
5228 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005229 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005230 break;
5231
5232 // We found a decl with the exact signature.
5233 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005234 // If we're in a record, we want to hide the target, so we
5235 // return true (without a diagnostic) to tell the caller not to
5236 // build a shadow decl.
5237 if (CurContext->isRecord())
5238 return true;
5239
5240 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005241 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005242 break;
5243 }
5244
5245 Diag(Target->getLocation(), diag::note_using_decl_target);
5246 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5247 return true;
5248 }
5249
5250 // Target is not a function.
5251
John McCall9f54ad42009-12-10 09:41:52 +00005252 if (isa<TagDecl>(Target)) {
5253 // No conflict between a tag and a non-tag.
5254 if (!Tag) return false;
5255
John McCall41ce66f2009-12-10 19:51:03 +00005256 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005257 Diag(Target->getLocation(), diag::note_using_decl_target);
5258 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5259 return true;
5260 }
5261
5262 // No conflict between a tag and a non-tag.
5263 if (!NonTag) return false;
5264
John McCall41ce66f2009-12-10 19:51:03 +00005265 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005266 Diag(Target->getLocation(), diag::note_using_decl_target);
5267 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5268 return true;
5269}
5270
John McCall9488ea12009-11-17 05:59:44 +00005271/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005272UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005273 UsingDecl *UD,
5274 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005275
5276 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005277 NamedDecl *Target = Orig;
5278 if (isa<UsingShadowDecl>(Target)) {
5279 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5280 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005281 }
5282
5283 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005284 = UsingShadowDecl::Create(Context, CurContext,
5285 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005286 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005287
5288 Shadow->setAccess(UD->getAccess());
5289 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5290 Shadow->setInvalidDecl();
5291
John McCall9488ea12009-11-17 05:59:44 +00005292 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005293 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005294 else
John McCall604e7f12009-12-08 07:46:18 +00005295 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005296
John McCall604e7f12009-12-08 07:46:18 +00005297
John McCall9f54ad42009-12-10 09:41:52 +00005298 return Shadow;
5299}
John McCall604e7f12009-12-08 07:46:18 +00005300
John McCall9f54ad42009-12-10 09:41:52 +00005301/// Hides a using shadow declaration. This is required by the current
5302/// using-decl implementation when a resolvable using declaration in a
5303/// class is followed by a declaration which would hide or override
5304/// one or more of the using decl's targets; for example:
5305///
5306/// struct Base { void foo(int); };
5307/// struct Derived : Base {
5308/// using Base::foo;
5309/// void foo(int);
5310/// };
5311///
5312/// The governing language is C++03 [namespace.udecl]p12:
5313///
5314/// When a using-declaration brings names from a base class into a
5315/// derived class scope, member functions in the derived class
5316/// override and/or hide member functions with the same name and
5317/// parameter types in a base class (rather than conflicting).
5318///
5319/// There are two ways to implement this:
5320/// (1) optimistically create shadow decls when they're not hidden
5321/// by existing declarations, or
5322/// (2) don't create any shadow decls (or at least don't make them
5323/// visible) until we've fully parsed/instantiated the class.
5324/// The problem with (1) is that we might have to retroactively remove
5325/// a shadow decl, which requires several O(n) operations because the
5326/// decl structures are (very reasonably) not designed for removal.
5327/// (2) avoids this but is very fiddly and phase-dependent.
5328void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005329 if (Shadow->getDeclName().getNameKind() ==
5330 DeclarationName::CXXConversionFunctionName)
5331 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5332
John McCall9f54ad42009-12-10 09:41:52 +00005333 // Remove it from the DeclContext...
5334 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005335
John McCall9f54ad42009-12-10 09:41:52 +00005336 // ...and the scope, if applicable...
5337 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005338 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005339 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005340 }
5341
John McCall9f54ad42009-12-10 09:41:52 +00005342 // ...and the using decl.
5343 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5344
5345 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005346 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005347}
5348
John McCall7ba107a2009-11-18 02:36:19 +00005349/// Builds a using declaration.
5350///
5351/// \param IsInstantiation - Whether this call arises from an
5352/// instantiation of an unresolved using declaration. We treat
5353/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005354NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5355 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005356 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005357 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005358 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005359 bool IsInstantiation,
5360 bool IsTypeName,
5361 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005362 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005363 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005364 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005365
Anders Carlsson550b14b2009-08-28 05:49:21 +00005366 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005367
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005368 if (SS.isEmpty()) {
5369 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005370 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005371 }
Mike Stump1eb44332009-09-09 15:08:12 +00005372
John McCall9f54ad42009-12-10 09:41:52 +00005373 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005374 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005375 ForRedeclaration);
5376 Previous.setHideTags(false);
5377 if (S) {
5378 LookupName(Previous, S);
5379
5380 // It is really dumb that we have to do this.
5381 LookupResult::Filter F = Previous.makeFilter();
5382 while (F.hasNext()) {
5383 NamedDecl *D = F.next();
5384 if (!isDeclInScope(D, CurContext, S))
5385 F.erase();
5386 }
5387 F.done();
5388 } else {
5389 assert(IsInstantiation && "no scope in non-instantiation");
5390 assert(CurContext->isRecord() && "scope not record in instantiation");
5391 LookupQualifiedName(Previous, CurContext);
5392 }
5393
John McCall9f54ad42009-12-10 09:41:52 +00005394 // Check for invalid redeclarations.
5395 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5396 return 0;
5397
5398 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005399 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5400 return 0;
5401
John McCallaf8e6ed2009-11-12 03:15:40 +00005402 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005403 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005404 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005405 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005406 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005407 // FIXME: not all declaration name kinds are legal here
5408 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5409 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005410 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005411 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005412 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005413 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5414 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005415 }
John McCalled976492009-12-04 22:46:56 +00005416 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005417 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5418 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005419 }
John McCalled976492009-12-04 22:46:56 +00005420 D->setAccess(AS);
5421 CurContext->addDecl(D);
5422
5423 if (!LookupContext) return D;
5424 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005425
John McCall77bb1aa2010-05-01 00:40:08 +00005426 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005427 UD->setInvalidDecl();
5428 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005429 }
5430
Sebastian Redlf677ea32011-02-05 19:23:19 +00005431 // Constructor inheriting using decls get special treatment.
5432 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005433 if (CheckInheritedConstructorUsingDecl(UD))
5434 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005435 return UD;
5436 }
5437
5438 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005439
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005440 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005441 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005442
John McCall604e7f12009-12-08 07:46:18 +00005443 // Unlike most lookups, we don't always want to hide tag
5444 // declarations: tag names are visible through the using declaration
5445 // even if hidden by ordinary names, *except* in a dependent context
5446 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005447 if (!IsInstantiation)
5448 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005449
John McCalla24dc2e2009-11-17 02:14:36 +00005450 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005451
John McCallf36e02d2009-10-09 21:13:30 +00005452 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005453 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005454 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005455 UD->setInvalidDecl();
5456 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005457 }
5458
John McCalled976492009-12-04 22:46:56 +00005459 if (R.isAmbiguous()) {
5460 UD->setInvalidDecl();
5461 return UD;
5462 }
Mike Stump1eb44332009-09-09 15:08:12 +00005463
John McCall7ba107a2009-11-18 02:36:19 +00005464 if (IsTypeName) {
5465 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005466 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005467 Diag(IdentLoc, diag::err_using_typename_non_type);
5468 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5469 Diag((*I)->getUnderlyingDecl()->getLocation(),
5470 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005471 UD->setInvalidDecl();
5472 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005473 }
5474 } else {
5475 // If we asked for a non-typename and we got a type, error out,
5476 // but only if this is an instantiation of an unresolved using
5477 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005478 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005479 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5480 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005481 UD->setInvalidDecl();
5482 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005483 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005484 }
5485
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005486 // C++0x N2914 [namespace.udecl]p6:
5487 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005488 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005489 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5490 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005491 UD->setInvalidDecl();
5492 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005493 }
Mike Stump1eb44332009-09-09 15:08:12 +00005494
John McCall9f54ad42009-12-10 09:41:52 +00005495 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5496 if (!CheckUsingShadowDecl(UD, *I, Previous))
5497 BuildUsingShadowDecl(S, UD, *I);
5498 }
John McCall9488ea12009-11-17 05:59:44 +00005499
5500 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005501}
5502
Sebastian Redlf677ea32011-02-05 19:23:19 +00005503/// Additional checks for a using declaration referring to a constructor name.
5504bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5505 if (UD->isTypeName()) {
5506 // FIXME: Cannot specify typename when specifying constructor
5507 return true;
5508 }
5509
Douglas Gregordc355712011-02-25 00:36:19 +00005510 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005511 assert(SourceType &&
5512 "Using decl naming constructor doesn't have type in scope spec.");
5513 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5514
5515 // Check whether the named type is a direct base class.
5516 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5517 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5518 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5519 BaseIt != BaseE; ++BaseIt) {
5520 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5521 if (CanonicalSourceType == BaseType)
5522 break;
5523 }
5524
5525 if (BaseIt == BaseE) {
5526 // Did not find SourceType in the bases.
5527 Diag(UD->getUsingLocation(),
5528 diag::err_using_decl_constructor_not_in_direct_base)
5529 << UD->getNameInfo().getSourceRange()
5530 << QualType(SourceType, 0) << TargetClass;
5531 return true;
5532 }
5533
5534 BaseIt->setInheritConstructors();
5535
5536 return false;
5537}
5538
John McCall9f54ad42009-12-10 09:41:52 +00005539/// Checks that the given using declaration is not an invalid
5540/// redeclaration. Note that this is checking only for the using decl
5541/// itself, not for any ill-formedness among the UsingShadowDecls.
5542bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5543 bool isTypeName,
5544 const CXXScopeSpec &SS,
5545 SourceLocation NameLoc,
5546 const LookupResult &Prev) {
5547 // C++03 [namespace.udecl]p8:
5548 // C++0x [namespace.udecl]p10:
5549 // A using-declaration is a declaration and can therefore be used
5550 // repeatedly where (and only where) multiple declarations are
5551 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005552 //
John McCall8a726212010-11-29 18:01:58 +00005553 // That's in non-member contexts.
5554 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005555 return false;
5556
5557 NestedNameSpecifier *Qual
5558 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5559
5560 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5561 NamedDecl *D = *I;
5562
5563 bool DTypename;
5564 NestedNameSpecifier *DQual;
5565 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5566 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00005567 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005568 } else if (UnresolvedUsingValueDecl *UD
5569 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5570 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00005571 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005572 } else if (UnresolvedUsingTypenameDecl *UD
5573 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5574 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00005575 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005576 } else continue;
5577
5578 // using decls differ if one says 'typename' and the other doesn't.
5579 // FIXME: non-dependent using decls?
5580 if (isTypeName != DTypename) continue;
5581
5582 // using decls differ if they name different scopes (but note that
5583 // template instantiation can cause this check to trigger when it
5584 // didn't before instantiation).
5585 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5586 Context.getCanonicalNestedNameSpecifier(DQual))
5587 continue;
5588
5589 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00005590 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00005591 return true;
5592 }
5593
5594 return false;
5595}
5596
John McCall604e7f12009-12-08 07:46:18 +00005597
John McCalled976492009-12-04 22:46:56 +00005598/// Checks that the given nested-name qualifier used in a using decl
5599/// in the current context is appropriately related to the current
5600/// scope. If an error is found, diagnoses it and returns true.
5601bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5602 const CXXScopeSpec &SS,
5603 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00005604 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005605
John McCall604e7f12009-12-08 07:46:18 +00005606 if (!CurContext->isRecord()) {
5607 // C++03 [namespace.udecl]p3:
5608 // C++0x [namespace.udecl]p8:
5609 // A using-declaration for a class member shall be a member-declaration.
5610
5611 // If we weren't able to compute a valid scope, it must be a
5612 // dependent class scope.
5613 if (!NamedContext || NamedContext->isRecord()) {
5614 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5615 << SS.getRange();
5616 return true;
5617 }
5618
5619 // Otherwise, everything is known to be fine.
5620 return false;
5621 }
5622
5623 // The current scope is a record.
5624
5625 // If the named context is dependent, we can't decide much.
5626 if (!NamedContext) {
5627 // FIXME: in C++0x, we can diagnose if we can prove that the
5628 // nested-name-specifier does not refer to a base class, which is
5629 // still possible in some cases.
5630
5631 // Otherwise we have to conservatively report that things might be
5632 // okay.
5633 return false;
5634 }
5635
5636 if (!NamedContext->isRecord()) {
5637 // Ideally this would point at the last name in the specifier,
5638 // but we don't have that level of source info.
5639 Diag(SS.getRange().getBegin(),
5640 diag::err_using_decl_nested_name_specifier_is_not_class)
5641 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5642 return true;
5643 }
5644
Douglas Gregor6fb07292010-12-21 07:41:49 +00005645 if (!NamedContext->isDependentContext() &&
5646 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5647 return true;
5648
John McCall604e7f12009-12-08 07:46:18 +00005649 if (getLangOptions().CPlusPlus0x) {
5650 // C++0x [namespace.udecl]p3:
5651 // In a using-declaration used as a member-declaration, the
5652 // nested-name-specifier shall name a base class of the class
5653 // being defined.
5654
5655 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5656 cast<CXXRecordDecl>(NamedContext))) {
5657 if (CurContext == NamedContext) {
5658 Diag(NameLoc,
5659 diag::err_using_decl_nested_name_specifier_is_current_class)
5660 << SS.getRange();
5661 return true;
5662 }
5663
5664 Diag(SS.getRange().getBegin(),
5665 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5666 << (NestedNameSpecifier*) SS.getScopeRep()
5667 << cast<CXXRecordDecl>(CurContext)
5668 << SS.getRange();
5669 return true;
5670 }
5671
5672 return false;
5673 }
5674
5675 // C++03 [namespace.udecl]p4:
5676 // A using-declaration used as a member-declaration shall refer
5677 // to a member of a base class of the class being defined [etc.].
5678
5679 // Salient point: SS doesn't have to name a base class as long as
5680 // lookup only finds members from base classes. Therefore we can
5681 // diagnose here only if we can prove that that can't happen,
5682 // i.e. if the class hierarchies provably don't intersect.
5683
5684 // TODO: it would be nice if "definitely valid" results were cached
5685 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5686 // need to be repeated.
5687
5688 struct UserData {
5689 llvm::DenseSet<const CXXRecordDecl*> Bases;
5690
5691 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5692 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5693 Data->Bases.insert(Base);
5694 return true;
5695 }
5696
5697 bool hasDependentBases(const CXXRecordDecl *Class) {
5698 return !Class->forallBases(collect, this);
5699 }
5700
5701 /// Returns true if the base is dependent or is one of the
5702 /// accumulated base classes.
5703 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5704 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5705 return !Data->Bases.count(Base);
5706 }
5707
5708 bool mightShareBases(const CXXRecordDecl *Class) {
5709 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5710 }
5711 };
5712
5713 UserData Data;
5714
5715 // Returns false if we find a dependent base.
5716 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5717 return false;
5718
5719 // Returns false if the class has a dependent base or if it or one
5720 // of its bases is present in the base set of the current context.
5721 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5722 return false;
5723
5724 Diag(SS.getRange().getBegin(),
5725 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5726 << (NestedNameSpecifier*) SS.getScopeRep()
5727 << cast<CXXRecordDecl>(CurContext)
5728 << SS.getRange();
5729
5730 return true;
John McCalled976492009-12-04 22:46:56 +00005731}
5732
Richard Smith162e1c12011-04-15 14:24:37 +00005733Decl *Sema::ActOnAliasDeclaration(Scope *S,
5734 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005735 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005736 SourceLocation UsingLoc,
5737 UnqualifiedId &Name,
5738 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005739 // Skip up to the relevant declaration scope.
5740 while (S->getFlags() & Scope::TemplateParamScope)
5741 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005742 assert((S->getFlags() & Scope::DeclScope) &&
5743 "got alias-declaration outside of declaration scope");
5744
5745 if (Type.isInvalid())
5746 return 0;
5747
5748 bool Invalid = false;
5749 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5750 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005751 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005752
5753 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5754 return 0;
5755
5756 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005757 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005758 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005759 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5760 TInfo->getTypeLoc().getBeginLoc());
5761 }
Richard Smith162e1c12011-04-15 14:24:37 +00005762
5763 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5764 LookupName(Previous, S);
5765
5766 // Warn about shadowing the name of a template parameter.
5767 if (Previous.isSingleResult() &&
5768 Previous.getFoundDecl()->isTemplateParameter()) {
5769 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5770 Previous.getFoundDecl()))
5771 Invalid = true;
5772 Previous.clear();
5773 }
5774
5775 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5776 "name in alias declaration must be an identifier");
5777 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5778 Name.StartLocation,
5779 Name.Identifier, TInfo);
5780
5781 NewTD->setAccess(AS);
5782
5783 if (Invalid)
5784 NewTD->setInvalidDecl();
5785
Richard Smith3e4c6c42011-05-05 21:57:07 +00005786 CheckTypedefForVariablyModifiedType(S, NewTD);
5787 Invalid |= NewTD->isInvalidDecl();
5788
Richard Smith162e1c12011-04-15 14:24:37 +00005789 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005790
5791 NamedDecl *NewND;
5792 if (TemplateParamLists.size()) {
5793 TypeAliasTemplateDecl *OldDecl = 0;
5794 TemplateParameterList *OldTemplateParams = 0;
5795
5796 if (TemplateParamLists.size() != 1) {
5797 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5798 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5799 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5800 }
5801 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5802
5803 // Only consider previous declarations in the same scope.
5804 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5805 /*ExplicitInstantiationOrSpecialization*/false);
5806 if (!Previous.empty()) {
5807 Redeclaration = true;
5808
5809 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5810 if (!OldDecl && !Invalid) {
5811 Diag(UsingLoc, diag::err_redefinition_different_kind)
5812 << Name.Identifier;
5813
5814 NamedDecl *OldD = Previous.getRepresentativeDecl();
5815 if (OldD->getLocation().isValid())
5816 Diag(OldD->getLocation(), diag::note_previous_definition);
5817
5818 Invalid = true;
5819 }
5820
5821 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5822 if (TemplateParameterListsAreEqual(TemplateParams,
5823 OldDecl->getTemplateParameters(),
5824 /*Complain=*/true,
5825 TPL_TemplateMatch))
5826 OldTemplateParams = OldDecl->getTemplateParameters();
5827 else
5828 Invalid = true;
5829
5830 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5831 if (!Invalid &&
5832 !Context.hasSameType(OldTD->getUnderlyingType(),
5833 NewTD->getUnderlyingType())) {
5834 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5835 // but we can't reasonably accept it.
5836 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5837 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5838 if (OldTD->getLocation().isValid())
5839 Diag(OldTD->getLocation(), diag::note_previous_definition);
5840 Invalid = true;
5841 }
5842 }
5843 }
5844
5845 // Merge any previous default template arguments into our parameters,
5846 // and check the parameter list.
5847 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5848 TPC_TypeAliasTemplate))
5849 return 0;
5850
5851 TypeAliasTemplateDecl *NewDecl =
5852 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5853 Name.Identifier, TemplateParams,
5854 NewTD);
5855
5856 NewDecl->setAccess(AS);
5857
5858 if (Invalid)
5859 NewDecl->setInvalidDecl();
5860 else if (OldDecl)
5861 NewDecl->setPreviousDeclaration(OldDecl);
5862
5863 NewND = NewDecl;
5864 } else {
5865 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5866 NewND = NewTD;
5867 }
Richard Smith162e1c12011-04-15 14:24:37 +00005868
5869 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005870 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005871
Richard Smith3e4c6c42011-05-05 21:57:07 +00005872 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005873}
5874
John McCalld226f652010-08-21 09:40:31 +00005875Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005876 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005877 SourceLocation AliasLoc,
5878 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005879 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005880 SourceLocation IdentLoc,
5881 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005882
Anders Carlsson81c85c42009-03-28 23:53:49 +00005883 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005884 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5885 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005886
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005887 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005888 NamedDecl *PrevDecl
5889 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5890 ForRedeclaration);
5891 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5892 PrevDecl = 0;
5893
5894 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005895 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005896 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005897 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005898 // FIXME: At some point, we'll want to create the (redundant)
5899 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005900 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005901 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005902 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005903 }
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005905 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5906 diag::err_redefinition_different_kind;
5907 Diag(AliasLoc, DiagID) << Alias;
5908 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005909 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005910 }
5911
John McCalla24dc2e2009-11-17 02:14:36 +00005912 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005913 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005914
John McCallf36e02d2009-10-09 21:13:30 +00005915 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005916 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5917 CTC_NoKeywords, 0)) {
5918 if (R.getAsSingle<NamespaceDecl>() ||
5919 R.getAsSingle<NamespaceAliasDecl>()) {
5920 if (DeclContext *DC = computeDeclContext(SS, false))
5921 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5922 << Ident << DC << Corrected << SS.getRange()
5923 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5924 else
5925 Diag(IdentLoc, diag::err_using_directive_suggest)
5926 << Ident << Corrected
5927 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5928
5929 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5930 << Corrected;
5931
5932 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00005933 } else {
5934 R.clear();
5935 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005936 }
5937 }
5938
5939 if (R.empty()) {
5940 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005941 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005942 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005943 }
Mike Stump1eb44332009-09-09 15:08:12 +00005944
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005945 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005946 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005947 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005948 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005949
John McCall3dbd3d52010-02-16 06:53:13 +00005950 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005951 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005952}
5953
Douglas Gregor39957dc2010-05-01 15:04:51 +00005954namespace {
5955 /// \brief Scoped object used to handle the state changes required in Sema
5956 /// to implicitly define the body of a C++ member function;
5957 class ImplicitlyDefinedFunctionScope {
5958 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005959 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005960
5961 public:
5962 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005963 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005964 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005965 S.PushFunctionScope();
5966 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5967 }
5968
5969 ~ImplicitlyDefinedFunctionScope() {
5970 S.PopExpressionEvaluationContext();
5971 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005972 }
5973 };
5974}
5975
Sean Hunt001cad92011-05-10 00:49:42 +00005976Sema::ImplicitExceptionSpecification
5977Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005978 // C++ [except.spec]p14:
5979 // An implicitly declared special member function (Clause 12) shall have an
5980 // exception-specification. [...]
5981 ImplicitExceptionSpecification ExceptSpec(Context);
5982
Sebastian Redl60618fa2011-03-12 11:50:43 +00005983 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005984 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5985 BEnd = ClassDecl->bases_end();
5986 B != BEnd; ++B) {
5987 if (B->isVirtual()) // Handled below.
5988 continue;
5989
Douglas Gregor18274032010-07-03 00:47:00 +00005990 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5991 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005992 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5993 // If this is a deleted function, add it anyway. This might be conformant
5994 // with the standard. This might not. I'm not sure. It might not matter.
5995 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005996 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00005997 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005998 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00005999
6000 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006001 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6002 BEnd = ClassDecl->vbases_end();
6003 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006004 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6005 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006006 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6007 // If this is a deleted function, add it anyway. This might be conformant
6008 // with the standard. This might not. I'm not sure. It might not matter.
6009 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006010 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006011 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006012 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006013
6014 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006015 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6016 FEnd = ClassDecl->field_end();
6017 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006018 if (F->hasInClassInitializer()) {
6019 if (Expr *E = F->getInClassInitializer())
6020 ExceptSpec.CalledExpr(E);
6021 else if (!F->isInvalidDecl())
6022 ExceptSpec.SetDelayed();
6023 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006024 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006025 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6026 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6027 // If this is a deleted function, add it anyway. This might be conformant
6028 // with the standard. This might not. I'm not sure. It might not matter.
6029 // In particular, the problem is that this function never gets called. It
6030 // might just be ill-formed because this function attempts to refer to
6031 // a deleted function here.
6032 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006033 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006034 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006035 }
John McCalle23cf432010-12-14 08:05:40 +00006036
Sean Hunt001cad92011-05-10 00:49:42 +00006037 return ExceptSpec;
6038}
6039
6040CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6041 CXXRecordDecl *ClassDecl) {
6042 // C++ [class.ctor]p5:
6043 // A default constructor for a class X is a constructor of class X
6044 // that can be called without an argument. If there is no
6045 // user-declared constructor for class X, a default constructor is
6046 // implicitly declared. An implicitly-declared default constructor
6047 // is an inline public member of its class.
6048 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6049 "Should not build implicit default constructor!");
6050
6051 ImplicitExceptionSpecification Spec =
6052 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6053 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006054
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006055 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006056 CanQualType ClassType
6057 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006058 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006059 DeclarationName Name
6060 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006061 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006062 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006063 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006064 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006065 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006066 /*TInfo=*/0,
6067 /*isExplicit=*/false,
6068 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006069 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006070 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006071 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006072 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006073 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006074
6075 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006076 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6077
Douglas Gregor23c94db2010-07-02 17:43:08 +00006078 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006079 PushOnScopeChains(DefaultCon, S, false);
6080 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006081
6082 if (ShouldDeleteDefaultConstructor(DefaultCon))
6083 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006084
Douglas Gregor32df23e2010-07-01 22:02:46 +00006085 return DefaultCon;
6086}
6087
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006088void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6089 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006090 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006091 !Constructor->doesThisDeclarationHaveABody() &&
6092 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006093 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006094
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006095 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006096 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006097
Douglas Gregor39957dc2010-05-01 15:04:51 +00006098 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006099 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006100 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006101 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006102 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006103 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006104 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006105 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006106 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006107
6108 SourceLocation Loc = Constructor->getLocation();
6109 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6110
6111 Constructor->setUsed();
6112 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006113
6114 if (ASTMutationListener *L = getASTMutationListener()) {
6115 L->CompletedImplicitDefinition(Constructor);
6116 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006117}
6118
Richard Smith7a614d82011-06-11 17:19:42 +00006119/// Get any existing defaulted default constructor for the given class. Do not
6120/// implicitly define one if it does not exist.
6121static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6122 CXXRecordDecl *D) {
6123 ASTContext &Context = Self.Context;
6124 QualType ClassType = Context.getTypeDeclType(D);
6125 DeclarationName ConstructorName
6126 = Context.DeclarationNames.getCXXConstructorName(
6127 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6128
6129 DeclContext::lookup_const_iterator Con, ConEnd;
6130 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6131 Con != ConEnd; ++Con) {
6132 // A function template cannot be defaulted.
6133 if (isa<FunctionTemplateDecl>(*Con))
6134 continue;
6135
6136 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6137 if (Constructor->isDefaultConstructor())
6138 return Constructor->isDefaulted() ? Constructor : 0;
6139 }
6140 return 0;
6141}
6142
6143void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6144 if (!D) return;
6145 AdjustDeclIfTemplate(D);
6146
6147 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6148 CXXConstructorDecl *CtorDecl
6149 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6150
6151 if (!CtorDecl) return;
6152
6153 // Compute the exception specification for the default constructor.
6154 const FunctionProtoType *CtorTy =
6155 CtorDecl->getType()->castAs<FunctionProtoType>();
6156 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6157 ImplicitExceptionSpecification Spec =
6158 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6159 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6160 assert(EPI.ExceptionSpecType != EST_Delayed);
6161
6162 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6163 }
6164
6165 // If the default constructor is explicitly defaulted, checking the exception
6166 // specification is deferred until now.
6167 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6168 !ClassDecl->isDependentType())
6169 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6170}
6171
Sebastian Redlf677ea32011-02-05 19:23:19 +00006172void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6173 // We start with an initial pass over the base classes to collect those that
6174 // inherit constructors from. If there are none, we can forgo all further
6175 // processing.
6176 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6177 BasesVector BasesToInheritFrom;
6178 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6179 BaseE = ClassDecl->bases_end();
6180 BaseIt != BaseE; ++BaseIt) {
6181 if (BaseIt->getInheritConstructors()) {
6182 QualType Base = BaseIt->getType();
6183 if (Base->isDependentType()) {
6184 // If we inherit constructors from anything that is dependent, just
6185 // abort processing altogether. We'll get another chance for the
6186 // instantiations.
6187 return;
6188 }
6189 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6190 }
6191 }
6192 if (BasesToInheritFrom.empty())
6193 return;
6194
6195 // Now collect the constructors that we already have in the current class.
6196 // Those take precedence over inherited constructors.
6197 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6198 // unless there is a user-declared constructor with the same signature in
6199 // the class where the using-declaration appears.
6200 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6201 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6202 CtorE = ClassDecl->ctor_end();
6203 CtorIt != CtorE; ++CtorIt) {
6204 ExistingConstructors.insert(
6205 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6206 }
6207
6208 Scope *S = getScopeForContext(ClassDecl);
6209 DeclarationName CreatedCtorName =
6210 Context.DeclarationNames.getCXXConstructorName(
6211 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6212
6213 // Now comes the true work.
6214 // First, we keep a map from constructor types to the base that introduced
6215 // them. Needed for finding conflicting constructors. We also keep the
6216 // actually inserted declarations in there, for pretty diagnostics.
6217 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6218 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6219 ConstructorToSourceMap InheritedConstructors;
6220 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6221 BaseE = BasesToInheritFrom.end();
6222 BaseIt != BaseE; ++BaseIt) {
6223 const RecordType *Base = *BaseIt;
6224 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6225 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6226 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6227 CtorE = BaseDecl->ctor_end();
6228 CtorIt != CtorE; ++CtorIt) {
6229 // Find the using declaration for inheriting this base's constructors.
6230 DeclarationName Name =
6231 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6232 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6233 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6234 SourceLocation UsingLoc = UD ? UD->getLocation() :
6235 ClassDecl->getLocation();
6236
6237 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6238 // from the class X named in the using-declaration consists of actual
6239 // constructors and notional constructors that result from the
6240 // transformation of defaulted parameters as follows:
6241 // - all non-template default constructors of X, and
6242 // - for each non-template constructor of X that has at least one
6243 // parameter with a default argument, the set of constructors that
6244 // results from omitting any ellipsis parameter specification and
6245 // successively omitting parameters with a default argument from the
6246 // end of the parameter-type-list.
6247 CXXConstructorDecl *BaseCtor = *CtorIt;
6248 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6249 const FunctionProtoType *BaseCtorType =
6250 BaseCtor->getType()->getAs<FunctionProtoType>();
6251
6252 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6253 maxParams = BaseCtor->getNumParams();
6254 params <= maxParams; ++params) {
6255 // Skip default constructors. They're never inherited.
6256 if (params == 0)
6257 continue;
6258 // Skip copy and move constructors for the same reason.
6259 if (CanBeCopyOrMove && params == 1)
6260 continue;
6261
6262 // Build up a function type for this particular constructor.
6263 // FIXME: The working paper does not consider that the exception spec
6264 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006265 // source. This code doesn't yet, either. When it does, this code will
6266 // need to be delayed until after exception specifications and in-class
6267 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006268 const Type *NewCtorType;
6269 if (params == maxParams)
6270 NewCtorType = BaseCtorType;
6271 else {
6272 llvm::SmallVector<QualType, 16> Args;
6273 for (unsigned i = 0; i < params; ++i) {
6274 Args.push_back(BaseCtorType->getArgType(i));
6275 }
6276 FunctionProtoType::ExtProtoInfo ExtInfo =
6277 BaseCtorType->getExtProtoInfo();
6278 ExtInfo.Variadic = false;
6279 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6280 Args.data(), params, ExtInfo)
6281 .getTypePtr();
6282 }
6283 const Type *CanonicalNewCtorType =
6284 Context.getCanonicalType(NewCtorType);
6285
6286 // Now that we have the type, first check if the class already has a
6287 // constructor with this signature.
6288 if (ExistingConstructors.count(CanonicalNewCtorType))
6289 continue;
6290
6291 // Then we check if we have already declared an inherited constructor
6292 // with this signature.
6293 std::pair<ConstructorToSourceMap::iterator, bool> result =
6294 InheritedConstructors.insert(std::make_pair(
6295 CanonicalNewCtorType,
6296 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6297 if (!result.second) {
6298 // Already in the map. If it came from a different class, that's an
6299 // error. Not if it's from the same.
6300 CanQualType PreviousBase = result.first->second.first;
6301 if (CanonicalBase != PreviousBase) {
6302 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6303 const CXXConstructorDecl *PrevBaseCtor =
6304 PrevCtor->getInheritedConstructor();
6305 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6306
6307 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6308 Diag(BaseCtor->getLocation(),
6309 diag::note_using_decl_constructor_conflict_current_ctor);
6310 Diag(PrevBaseCtor->getLocation(),
6311 diag::note_using_decl_constructor_conflict_previous_ctor);
6312 Diag(PrevCtor->getLocation(),
6313 diag::note_using_decl_constructor_conflict_previous_using);
6314 }
6315 continue;
6316 }
6317
6318 // OK, we're there, now add the constructor.
6319 // C++0x [class.inhctor]p8: [...] that would be performed by a
6320 // user-writtern inline constructor [...]
6321 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6322 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006323 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6324 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006325 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006326 NewCtor->setAccess(BaseCtor->getAccess());
6327
6328 // Build up the parameter decls and add them.
6329 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6330 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006331 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6332 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006333 /*IdentifierInfo=*/0,
6334 BaseCtorType->getArgType(i),
6335 /*TInfo=*/0, SC_None,
6336 SC_None, /*DefaultArg=*/0));
6337 }
6338 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6339 NewCtor->setInheritedConstructor(BaseCtor);
6340
6341 PushOnScopeChains(NewCtor, S, false);
6342 ClassDecl->addDecl(NewCtor);
6343 result.first->second.second = NewCtor;
6344 }
6345 }
6346 }
6347}
6348
Sean Huntcb45a0f2011-05-12 22:46:25 +00006349Sema::ImplicitExceptionSpecification
6350Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006351 // C++ [except.spec]p14:
6352 // An implicitly declared special member function (Clause 12) shall have
6353 // an exception-specification.
6354 ImplicitExceptionSpecification ExceptSpec(Context);
6355
6356 // Direct base-class destructors.
6357 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6358 BEnd = ClassDecl->bases_end();
6359 B != BEnd; ++B) {
6360 if (B->isVirtual()) // Handled below.
6361 continue;
6362
6363 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6364 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006365 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006366 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006367
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006368 // Virtual base-class destructors.
6369 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6370 BEnd = ClassDecl->vbases_end();
6371 B != BEnd; ++B) {
6372 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6373 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006374 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006375 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006376
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006377 // Field destructors.
6378 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6379 FEnd = ClassDecl->field_end();
6380 F != FEnd; ++F) {
6381 if (const RecordType *RecordTy
6382 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6383 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006384 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006385 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006386
Sean Huntcb45a0f2011-05-12 22:46:25 +00006387 return ExceptSpec;
6388}
6389
6390CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6391 // C++ [class.dtor]p2:
6392 // If a class has no user-declared destructor, a destructor is
6393 // declared implicitly. An implicitly-declared destructor is an
6394 // inline public member of its class.
6395
6396 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006397 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006398 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6399
Douglas Gregor4923aa22010-07-02 20:37:36 +00006400 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006401 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006402
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006403 CanQualType ClassType
6404 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006405 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006406 DeclarationName Name
6407 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006408 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006409 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006410 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6411 /*isInline=*/true,
6412 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006413 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006414 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006415 Destructor->setImplicit();
6416 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006417
6418 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006419 ++ASTContext::NumImplicitDestructorsDeclared;
6420
6421 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006422 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006423 PushOnScopeChains(Destructor, S, false);
6424 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006425
6426 // This could be uniqued if it ever proves significant.
6427 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006428
6429 if (ShouldDeleteDestructor(Destructor))
6430 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006431
6432 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006433
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006434 return Destructor;
6435}
6436
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006437void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006438 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006439 assert((Destructor->isDefaulted() &&
6440 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006441 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006442 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006443 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006444
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006445 if (Destructor->isInvalidDecl())
6446 return;
6447
Douglas Gregor39957dc2010-05-01 15:04:51 +00006448 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006449
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006450 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006451 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6452 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006453
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006454 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006455 Diag(CurrentLocation, diag::note_member_synthesized_at)
6456 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6457
6458 Destructor->setInvalidDecl();
6459 return;
6460 }
6461
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006462 SourceLocation Loc = Destructor->getLocation();
6463 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6464
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006465 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006466 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006467
6468 if (ASTMutationListener *L = getASTMutationListener()) {
6469 L->CompletedImplicitDefinition(Destructor);
6470 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006471}
6472
Sebastian Redl0ee33912011-05-19 05:13:44 +00006473void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6474 CXXDestructorDecl *destructor) {
6475 // C++11 [class.dtor]p3:
6476 // A declaration of a destructor that does not have an exception-
6477 // specification is implicitly considered to have the same exception-
6478 // specification as an implicit declaration.
6479 const FunctionProtoType *dtorType = destructor->getType()->
6480 getAs<FunctionProtoType>();
6481 if (dtorType->hasExceptionSpec())
6482 return;
6483
6484 ImplicitExceptionSpecification exceptSpec =
6485 ComputeDefaultedDtorExceptionSpec(classDecl);
6486
6487 // Replace the destructor's type.
6488 FunctionProtoType::ExtProtoInfo epi;
6489 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6490 epi.NumExceptions = exceptSpec.size();
6491 epi.Exceptions = exceptSpec.data();
6492 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6493
6494 destructor->setType(ty);
6495
6496 // FIXME: If the destructor has a body that could throw, and the newly created
6497 // spec doesn't allow exceptions, we should emit a warning, because this
6498 // change in behavior can break conforming C++03 programs at runtime.
6499 // However, we don't have a body yet, so it needs to be done somewhere else.
6500}
6501
Douglas Gregor06a9f362010-05-01 20:49:11 +00006502/// \brief Builds a statement that copies the given entity from \p From to
6503/// \c To.
6504///
6505/// This routine is used to copy the members of a class with an
6506/// implicitly-declared copy assignment operator. When the entities being
6507/// copied are arrays, this routine builds for loops to copy them.
6508///
6509/// \param S The Sema object used for type-checking.
6510///
6511/// \param Loc The location where the implicit copy is being generated.
6512///
6513/// \param T The type of the expressions being copied. Both expressions must
6514/// have this type.
6515///
6516/// \param To The expression we are copying to.
6517///
6518/// \param From The expression we are copying from.
6519///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006520/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6521/// Otherwise, it's a non-static member subobject.
6522///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006523/// \param Depth Internal parameter recording the depth of the recursion.
6524///
6525/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006526static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006527BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006528 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006529 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006530 // C++0x [class.copy]p30:
6531 // Each subobject is assigned in the manner appropriate to its type:
6532 //
6533 // - if the subobject is of class type, the copy assignment operator
6534 // for the class is used (as if by explicit qualification; that is,
6535 // ignoring any possible virtual overriding functions in more derived
6536 // classes);
6537 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6538 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6539
6540 // Look for operator=.
6541 DeclarationName Name
6542 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6543 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6544 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6545
6546 // Filter out any result that isn't a copy-assignment operator.
6547 LookupResult::Filter F = OpLookup.makeFilter();
6548 while (F.hasNext()) {
6549 NamedDecl *D = F.next();
6550 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6551 if (Method->isCopyAssignmentOperator())
6552 continue;
6553
6554 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006555 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006556 F.done();
6557
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006558 // Suppress the protected check (C++ [class.protected]) for each of the
6559 // assignment operators we found. This strange dance is required when
6560 // we're assigning via a base classes's copy-assignment operator. To
6561 // ensure that we're getting the right base class subobject (without
6562 // ambiguities), we need to cast "this" to that subobject type; to
6563 // ensure that we don't go through the virtual call mechanism, we need
6564 // to qualify the operator= name with the base class (see below). However,
6565 // this means that if the base class has a protected copy assignment
6566 // operator, the protected member access check will fail. So, we
6567 // rewrite "protected" access to "public" access in this case, since we
6568 // know by construction that we're calling from a derived class.
6569 if (CopyingBaseSubobject) {
6570 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6571 L != LEnd; ++L) {
6572 if (L.getAccess() == AS_protected)
6573 L.setAccess(AS_public);
6574 }
6575 }
6576
Douglas Gregor06a9f362010-05-01 20:49:11 +00006577 // Create the nested-name-specifier that will be used to qualify the
6578 // reference to operator=; this is required to suppress the virtual
6579 // call mechanism.
6580 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00006581 SS.MakeTrivial(S.Context,
6582 NestedNameSpecifier::Create(S.Context, 0, false,
6583 T.getTypePtr()),
6584 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006585
6586 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00006587 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00006588 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006589 /*FirstQualifierInScope=*/0, OpLookup,
6590 /*TemplateArgs=*/0,
6591 /*SuppressQualifierCheck=*/true);
6592 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006593 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006594
6595 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00006596
John McCall60d7b3a2010-08-24 06:29:42 +00006597 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00006598 OpEqualRef.takeAs<Expr>(),
6599 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006600 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006601 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006602
6603 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006604 }
John McCallb0207482010-03-16 06:11:48 +00006605
Douglas Gregor06a9f362010-05-01 20:49:11 +00006606 // - if the subobject is of scalar type, the built-in assignment
6607 // operator is used.
6608 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6609 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00006610 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006611 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006612 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006613
6614 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006615 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006616
6617 // - if the subobject is an array, each element is assigned, in the
6618 // manner appropriate to the element type;
6619
6620 // Construct a loop over the array bounds, e.g.,
6621 //
6622 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6623 //
6624 // that will copy each of the array elements.
6625 QualType SizeType = S.Context.getSizeType();
6626
6627 // Create the iteration variable.
6628 IdentifierInfo *IterationVarName = 0;
6629 {
6630 llvm::SmallString<8> Str;
6631 llvm::raw_svector_ostream OS(Str);
6632 OS << "__i" << Depth;
6633 IterationVarName = &S.Context.Idents.get(OS.str());
6634 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006635 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006636 IterationVarName, SizeType,
6637 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00006638 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006639
6640 // Initialize the iteration variable to zero.
6641 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006642 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006643
6644 // Create a reference to the iteration variable; we'll use this several
6645 // times throughout.
6646 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00006647 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006648 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6649
6650 // Create the DeclStmt that holds the iteration variable.
6651 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6652
6653 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006654 llvm::APInt Upper
6655 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00006656 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00006657 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00006658 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6659 BO_NE, S.Context.BoolTy,
6660 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006661
6662 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006663 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00006664 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6665 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006666
6667 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006668 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6669 IterationVarRef, Loc));
6670 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6671 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006672
6673 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00006674 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6675 To, From, CopyingBaseSubobject,
6676 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00006677 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006678 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006679
6680 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00006681 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006682 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00006683 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00006684 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006685}
6686
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006687/// \brief Determine whether the given class has a copy assignment operator
6688/// that accepts a const-qualified argument.
6689static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6690 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6691
6692 if (!Class->hasDeclaredCopyAssignment())
6693 S.DeclareImplicitCopyAssignment(Class);
6694
6695 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6696 DeclarationName OpName
6697 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6698
6699 DeclContext::lookup_const_iterator Op, OpEnd;
6700 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6701 // C++ [class.copy]p9:
6702 // A user-declared copy assignment operator is a non-static non-template
6703 // member function of class X with exactly one parameter of type X, X&,
6704 // const X&, volatile X& or const volatile X&.
6705 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6706 if (!Method)
6707 continue;
6708
6709 if (Method->isStatic())
6710 continue;
6711 if (Method->getPrimaryTemplate())
6712 continue;
6713 const FunctionProtoType *FnType =
6714 Method->getType()->getAs<FunctionProtoType>();
6715 assert(FnType && "Overloaded operator has no prototype.");
6716 // Don't assert on this; an invalid decl might have been left in the AST.
6717 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6718 continue;
6719 bool AcceptsConst = true;
6720 QualType ArgType = FnType->getArgType(0);
6721 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6722 ArgType = Ref->getPointeeType();
6723 // Is it a non-const lvalue reference?
6724 if (!ArgType.isConstQualified())
6725 AcceptsConst = false;
6726 }
6727 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6728 continue;
6729
6730 // We have a single argument of type cv X or cv X&, i.e. we've found the
6731 // copy assignment operator. Return whether it accepts const arguments.
6732 return AcceptsConst;
6733 }
6734 assert(Class->isInvalidDecl() &&
6735 "No copy assignment operator declared in valid code.");
6736 return false;
6737}
6738
Sean Hunt30de05c2011-05-14 05:23:20 +00006739std::pair<Sema::ImplicitExceptionSpecification, bool>
6740Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6741 CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00006742 // C++ [class.copy]p10:
6743 // If the class definition does not explicitly declare a copy
6744 // assignment operator, one is declared implicitly.
6745 // The implicitly-defined copy assignment operator for a class X
6746 // will have the form
6747 //
6748 // X& X::operator=(const X&)
6749 //
6750 // if
6751 bool HasConstCopyAssignment = true;
6752
6753 // -- each direct base class B of X has a copy assignment operator
6754 // whose parameter is of type const B&, const volatile B& or B,
6755 // and
6756 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6757 BaseEnd = ClassDecl->bases_end();
6758 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6759 assert(!Base->getType()->isDependentType() &&
6760 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006761 const CXXRecordDecl *BaseClassDecl
6762 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6763 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006764 }
6765
6766 // -- for all the nonstatic data members of X that are of a class
6767 // type M (or array thereof), each such class type has a copy
6768 // assignment operator whose parameter is of type const M&,
6769 // const volatile M& or M.
6770 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6771 FieldEnd = ClassDecl->field_end();
6772 HasConstCopyAssignment && Field != FieldEnd;
6773 ++Field) {
6774 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006775 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6776 const CXXRecordDecl *FieldClassDecl
6777 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6778 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006779 }
6780 }
6781
6782 // Otherwise, the implicitly declared copy assignment operator will
6783 // have the form
6784 //
6785 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00006786
Douglas Gregorb87786f2010-07-01 17:48:08 +00006787 // C++ [except.spec]p14:
6788 // An implicitly declared special member function (Clause 12) shall have an
6789 // exception-specification. [...]
6790 ImplicitExceptionSpecification ExceptSpec(Context);
6791 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6792 BaseEnd = ClassDecl->bases_end();
6793 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00006794 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006796
6797 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6798 DeclareImplicitCopyAssignment(BaseClassDecl);
6799
6800 if (CXXMethodDecl *CopyAssign
6801 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
Douglas Gregorb87786f2010-07-01 17:48:08 +00006802 ExceptSpec.CalledDecl(CopyAssign);
6803 }
6804 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6805 FieldEnd = ClassDecl->field_end();
6806 Field != FieldEnd;
6807 ++Field) {
6808 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006809 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6810 CXXRecordDecl *FieldClassDecl
6811 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6812
6813 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6814 DeclareImplicitCopyAssignment(FieldClassDecl);
6815
6816 if (CXXMethodDecl *CopyAssign
6817 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6818 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00006819 }
6820 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006821
Sean Hunt30de05c2011-05-14 05:23:20 +00006822 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6823}
6824
6825CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6826 // Note: The following rules are largely analoguous to the copy
6827 // constructor rules. Note that virtual bases are not taken into account
6828 // for determining the argument type of the operator. Note also that
6829 // operators taking an object instead of a reference are allowed.
6830
6831 ImplicitExceptionSpecification Spec(Context);
6832 bool Const;
6833 llvm::tie(Spec, Const) =
6834 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6835
6836 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6837 QualType RetType = Context.getLValueReferenceType(ArgType);
6838 if (Const)
6839 ArgType = ArgType.withConst();
6840 ArgType = Context.getLValueReferenceType(ArgType);
6841
Douglas Gregord3c35902010-07-01 16:36:15 +00006842 // An implicitly-declared copy assignment operator is an inline public
6843 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00006844 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00006845 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006846 SourceLocation ClassLoc = ClassDecl->getLocation();
6847 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006848 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006849 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006850 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006851 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006852 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006853 /*isInline=*/true,
6854 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006855 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00006856 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00006857 CopyAssignment->setImplicit();
6858 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006859
6860 // Add the parameter to the operator.
6861 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006862 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006863 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006864 SC_None,
6865 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006866 CopyAssignment->setParams(&FromParam, 1);
6867
Douglas Gregora376d102010-07-02 21:50:04 +00006868 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006869 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00006870
Douglas Gregor23c94db2010-07-02 17:43:08 +00006871 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006872 PushOnScopeChains(CopyAssignment, S, false);
6873 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006874
Sean Hunt71a682f2011-05-18 03:41:58 +00006875 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6876 CopyAssignment->setDeletedAsWritten();
6877
Douglas Gregord3c35902010-07-01 16:36:15 +00006878 AddOverriddenMethods(ClassDecl, CopyAssignment);
6879 return CopyAssignment;
6880}
6881
Douglas Gregor06a9f362010-05-01 20:49:11 +00006882void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6883 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00006884 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006885 CopyAssignOperator->isOverloadedOperator() &&
6886 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006887 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006888 "DefineImplicitCopyAssignment called for wrong function");
6889
6890 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6891
6892 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6893 CopyAssignOperator->setInvalidDecl();
6894 return;
6895 }
6896
6897 CopyAssignOperator->setUsed();
6898
6899 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006900 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006901
6902 // C++0x [class.copy]p30:
6903 // The implicitly-defined or explicitly-defaulted copy assignment operator
6904 // for a non-union class X performs memberwise copy assignment of its
6905 // subobjects. The direct base classes of X are assigned first, in the
6906 // order of their declaration in the base-specifier-list, and then the
6907 // immediate non-static data members of X are assigned, in the order in
6908 // which they were declared in the class definition.
6909
6910 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006911 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006912
6913 // The parameter for the "other" object, which we are copying from.
6914 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6915 Qualifiers OtherQuals = Other->getType().getQualifiers();
6916 QualType OtherRefType = Other->getType();
6917 if (const LValueReferenceType *OtherRef
6918 = OtherRefType->getAs<LValueReferenceType>()) {
6919 OtherRefType = OtherRef->getPointeeType();
6920 OtherQuals = OtherRefType.getQualifiers();
6921 }
6922
6923 // Our location for everything implicitly-generated.
6924 SourceLocation Loc = CopyAssignOperator->getLocation();
6925
6926 // Construct a reference to the "other" object. We'll be using this
6927 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006928 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006929 assert(OtherRef && "Reference to parameter cannot fail!");
6930
6931 // Construct the "this" pointer. We'll be using this throughout the generated
6932 // ASTs.
6933 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6934 assert(This && "Reference to this cannot fail!");
6935
6936 // Assign base classes.
6937 bool Invalid = false;
6938 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6939 E = ClassDecl->bases_end(); Base != E; ++Base) {
6940 // Form the assignment:
6941 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6942 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006943 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006944 Invalid = true;
6945 continue;
6946 }
6947
John McCallf871d0c2010-08-07 06:22:56 +00006948 CXXCastPath BasePath;
6949 BasePath.push_back(Base);
6950
Douglas Gregor06a9f362010-05-01 20:49:11 +00006951 // Construct the "from" expression, which is an implicit cast to the
6952 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006953 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006954 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6955 CK_UncheckedDerivedToBase,
6956 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006957
6958 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006959 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006960
6961 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006962 To = ImpCastExprToType(To.take(),
6963 Context.getCVRQualifiedType(BaseType,
6964 CopyAssignOperator->getTypeQualifiers()),
6965 CK_UncheckedDerivedToBase,
6966 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006967
6968 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006969 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006970 To.get(), From,
6971 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006972 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006973 Diag(CurrentLocation, diag::note_member_synthesized_at)
6974 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6975 CopyAssignOperator->setInvalidDecl();
6976 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006977 }
6978
6979 // Success! Record the copy.
6980 Statements.push_back(Copy.takeAs<Expr>());
6981 }
6982
6983 // \brief Reference to the __builtin_memcpy function.
6984 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006985 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006986 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006987
6988 // Assign non-static members.
6989 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6990 FieldEnd = ClassDecl->field_end();
6991 Field != FieldEnd; ++Field) {
6992 // Check for members of reference type; we can't copy those.
6993 if (Field->getType()->isReferenceType()) {
6994 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6995 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6996 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006997 Diag(CurrentLocation, diag::note_member_synthesized_at)
6998 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006999 Invalid = true;
7000 continue;
7001 }
7002
7003 // Check for members of const-qualified, non-class type.
7004 QualType BaseType = Context.getBaseElementType(Field->getType());
7005 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7006 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7007 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7008 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007009 Diag(CurrentLocation, diag::note_member_synthesized_at)
7010 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007011 Invalid = true;
7012 continue;
7013 }
7014
7015 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007016 if (FieldType->isIncompleteArrayType()) {
7017 assert(ClassDecl->hasFlexibleArrayMember() &&
7018 "Incomplete array type is not valid");
7019 continue;
7020 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007021
7022 // Build references to the field in the object we're copying from and to.
7023 CXXScopeSpec SS; // Intentionally empty
7024 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7025 LookupMemberName);
7026 MemberLookup.addDecl(*Field);
7027 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007028 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007029 Loc, /*IsArrow=*/false,
7030 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007031 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007032 Loc, /*IsArrow=*/true,
7033 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007034 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7035 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7036
7037 // If the field should be copied with __builtin_memcpy rather than via
7038 // explicit assignments, do so. This optimization only applies for arrays
7039 // of scalars and arrays of class type with trivial copy-assignment
7040 // operators.
John McCallf85e1932011-06-15 23:02:42 +00007041 if (FieldType->isArrayType() &&
7042 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007043 // Compute the size of the memory buffer to be copied.
7044 QualType SizeType = Context.getSizeType();
7045 llvm::APInt Size(Context.getTypeSize(SizeType),
7046 Context.getTypeSizeInChars(BaseType).getQuantity());
7047 for (const ConstantArrayType *Array
7048 = Context.getAsConstantArrayType(FieldType);
7049 Array;
7050 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007051 llvm::APInt ArraySize
7052 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007053 Size *= ArraySize;
7054 }
7055
7056 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007057 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7058 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007059
7060 bool NeedsCollectableMemCpy =
7061 (BaseType->isRecordType() &&
7062 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7063
7064 if (NeedsCollectableMemCpy) {
7065 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007066 // Create a reference to the __builtin_objc_memmove_collectable function.
7067 LookupResult R(*this,
7068 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007069 Loc, LookupOrdinaryName);
7070 LookupName(R, TUScope, true);
7071
7072 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7073 if (!CollectableMemCpy) {
7074 // Something went horribly wrong earlier, and we will have
7075 // complained about it.
7076 Invalid = true;
7077 continue;
7078 }
7079
7080 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7081 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007082 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007083 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7084 }
7085 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007086 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007087 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007088 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7089 LookupOrdinaryName);
7090 LookupName(R, TUScope, true);
7091
7092 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7093 if (!BuiltinMemCpy) {
7094 // Something went horribly wrong earlier, and we will have complained
7095 // about it.
7096 Invalid = true;
7097 continue;
7098 }
7099
7100 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7101 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007102 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007103 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7104 }
7105
John McCallca0408f2010-08-23 06:44:23 +00007106 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007107 CallArgs.push_back(To.takeAs<Expr>());
7108 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007109 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007110 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007111 if (NeedsCollectableMemCpy)
7112 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007113 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007114 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007115 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007116 else
7117 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007118 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007119 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007120 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007121
Douglas Gregor06a9f362010-05-01 20:49:11 +00007122 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7123 Statements.push_back(Call.takeAs<Expr>());
7124 continue;
7125 }
7126
7127 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007128 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00007129 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007130 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007131 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007132 Diag(CurrentLocation, diag::note_member_synthesized_at)
7133 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7134 CopyAssignOperator->setInvalidDecl();
7135 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007136 }
7137
7138 // Success! Record the copy.
7139 Statements.push_back(Copy.takeAs<Stmt>());
7140 }
7141
7142 if (!Invalid) {
7143 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007144 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007145
John McCall60d7b3a2010-08-24 06:29:42 +00007146 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007147 if (Return.isInvalid())
7148 Invalid = true;
7149 else {
7150 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007151
7152 if (Trap.hasErrorOccurred()) {
7153 Diag(CurrentLocation, diag::note_member_synthesized_at)
7154 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7155 Invalid = true;
7156 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007157 }
7158 }
7159
7160 if (Invalid) {
7161 CopyAssignOperator->setInvalidDecl();
7162 return;
7163 }
7164
John McCall60d7b3a2010-08-24 06:29:42 +00007165 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007166 /*isStmtExpr=*/false);
7167 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7168 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007169
7170 if (ASTMutationListener *L = getASTMutationListener()) {
7171 L->CompletedImplicitDefinition(CopyAssignOperator);
7172 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007173}
7174
Sean Hunt49634cf2011-05-13 06:10:58 +00007175std::pair<Sema::ImplicitExceptionSpecification, bool>
7176Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007177 // C++ [class.copy]p5:
7178 // The implicitly-declared copy constructor for a class X will
7179 // have the form
7180 //
7181 // X::X(const X&)
7182 //
7183 // if
Sean Huntc530d172011-06-10 04:44:37 +00007184 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007185 bool HasConstCopyConstructor = true;
7186
7187 // -- each direct or virtual base class B of X has a copy
7188 // constructor whose first parameter is of type const B& or
7189 // const volatile B&, and
7190 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7191 BaseEnd = ClassDecl->bases_end();
7192 HasConstCopyConstructor && Base != BaseEnd;
7193 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007194 // Virtual bases are handled below.
7195 if (Base->isVirtual())
7196 continue;
7197
Douglas Gregor22584312010-07-02 23:41:54 +00007198 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007200 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7201 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00007202 }
7203
7204 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7205 BaseEnd = ClassDecl->vbases_end();
7206 HasConstCopyConstructor && Base != BaseEnd;
7207 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007208 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007209 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007210 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7211 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007212 }
7213
7214 // -- for all the nonstatic data members of X that are of a
7215 // class type M (or array thereof), each such class type
7216 // has a copy constructor whose first parameter is of type
7217 // const M& or const volatile M&.
7218 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7219 FieldEnd = ClassDecl->field_end();
7220 HasConstCopyConstructor && Field != FieldEnd;
7221 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007222 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007223 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007224 LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7225 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007226 }
7227 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007228 // Otherwise, the implicitly declared copy constructor will have
7229 // the form
7230 //
7231 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00007232
Douglas Gregor0d405db2010-07-01 20:59:04 +00007233 // C++ [except.spec]p14:
7234 // An implicitly declared special member function (Clause 12) shall have an
7235 // exception-specification. [...]
7236 ImplicitExceptionSpecification ExceptSpec(Context);
7237 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7238 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7239 BaseEnd = ClassDecl->bases_end();
7240 Base != BaseEnd;
7241 ++Base) {
7242 // Virtual bases are handled below.
7243 if (Base->isVirtual())
7244 continue;
7245
Douglas Gregor22584312010-07-02 23:41:54 +00007246 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007247 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007248 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007249 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007250 ExceptSpec.CalledDecl(CopyConstructor);
7251 }
7252 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7253 BaseEnd = ClassDecl->vbases_end();
7254 Base != BaseEnd;
7255 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007256 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007257 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007258 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007259 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007260 ExceptSpec.CalledDecl(CopyConstructor);
7261 }
7262 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7263 FieldEnd = ClassDecl->field_end();
7264 Field != FieldEnd;
7265 ++Field) {
7266 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007267 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7268 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007269 LookupCopyConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00007270 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00007271 }
7272 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007273
Sean Hunt49634cf2011-05-13 06:10:58 +00007274 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7275}
7276
7277CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7278 CXXRecordDecl *ClassDecl) {
7279 // C++ [class.copy]p4:
7280 // If the class definition does not explicitly declare a copy
7281 // constructor, one is declared implicitly.
7282
7283 ImplicitExceptionSpecification Spec(Context);
7284 bool Const;
7285 llvm::tie(Spec, Const) =
7286 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7287
7288 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7289 QualType ArgType = ClassType;
7290 if (Const)
7291 ArgType = ArgType.withConst();
7292 ArgType = Context.getLValueReferenceType(ArgType);
7293
7294 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7295
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007296 DeclarationName Name
7297 = Context.DeclarationNames.getCXXConstructorName(
7298 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007299 SourceLocation ClassLoc = ClassDecl->getLocation();
7300 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00007301
7302 // An implicitly-declared copy constructor is an inline public
7303 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007304 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007305 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007306 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007307 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007308 /*TInfo=*/0,
7309 /*isExplicit=*/false,
7310 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00007311 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007312 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00007313 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007314 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7315
Douglas Gregor22584312010-07-02 23:41:54 +00007316 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00007317 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7318
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007319 // Add the parameter to the constructor.
7320 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007321 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007322 /*IdentifierInfo=*/0,
7323 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007324 SC_None,
7325 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007326 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00007327
Douglas Gregor23c94db2010-07-02 17:43:08 +00007328 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00007329 PushOnScopeChains(CopyConstructor, S, false);
7330 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00007331
7332 if (ShouldDeleteCopyConstructor(CopyConstructor))
7333 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007334
7335 return CopyConstructor;
7336}
7337
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007338void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00007339 CXXConstructorDecl *CopyConstructor) {
7340 assert((CopyConstructor->isDefaulted() &&
7341 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007342 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007343 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007344
Anders Carlsson63010a72010-04-23 16:24:12 +00007345 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007346 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007347
Douglas Gregor39957dc2010-05-01 15:04:51 +00007348 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007349 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007350
Sean Huntcbb67482011-01-08 20:30:50 +00007351 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007352 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00007353 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007354 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00007355 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007356 } else {
7357 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7358 CopyConstructor->getLocation(),
7359 MultiStmtArg(*this, 0, 0),
7360 /*isStmtExpr=*/false)
7361 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00007362 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007363
7364 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007365
7366 if (ASTMutationListener *L = getASTMutationListener()) {
7367 L->CompletedImplicitDefinition(CopyConstructor);
7368 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007369}
7370
John McCall60d7b3a2010-08-24 06:29:42 +00007371ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007372Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00007373 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00007374 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007375 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007376 unsigned ConstructKind,
7377 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007378 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007379
Douglas Gregor2f599792010-04-02 18:24:57 +00007380 // C++0x [class.copy]p34:
7381 // When certain criteria are met, an implementation is allowed to
7382 // omit the copy/move construction of a class object, even if the
7383 // copy/move constructor and/or destructor for the object have
7384 // side effects. [...]
7385 // - when a temporary class object that has not been bound to a
7386 // reference (12.2) would be copied/moved to a class object
7387 // with the same cv-unqualified type, the copy/move operation
7388 // can be omitted by constructing the temporary object
7389 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00007390 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00007391 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00007392 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00007393 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007394 }
Mike Stump1eb44332009-09-09 15:08:12 +00007395
7396 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007397 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007398 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007399}
7400
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007401/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7402/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007403ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007404Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7405 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00007406 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007407 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007408 unsigned ConstructKind,
7409 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00007410 unsigned NumExprs = ExprArgs.size();
7411 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00007412
Nick Lewycky909a70d2011-03-25 01:44:32 +00007413 for (specific_attr_iterator<NonNullAttr>
7414 i = Constructor->specific_attr_begin<NonNullAttr>(),
7415 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7416 const NonNullAttr *NonNull = *i;
7417 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7418 }
7419
Douglas Gregor7edfb692009-11-23 12:27:39 +00007420 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00007421 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00007422 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00007423 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007424 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7425 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007426}
7427
Mike Stump1eb44332009-09-09 15:08:12 +00007428bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007429 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00007430 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00007431 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00007432 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00007433 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007434 move(Exprs), false, CXXConstructExpr::CK_Complete,
7435 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00007436 if (TempResult.isInvalid())
7437 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007438
Anders Carlssonda3f4e22009-08-25 05:12:04 +00007439 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00007440 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007441 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00007442 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00007443 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00007444
Anders Carlssonfe2de492009-08-25 05:18:00 +00007445 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00007446}
7447
John McCall68c6c9a2010-02-02 09:10:11 +00007448void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007449 if (VD->isInvalidDecl()) return;
7450
John McCall68c6c9a2010-02-02 09:10:11 +00007451 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007452 if (ClassDecl->isInvalidDecl()) return;
7453 if (ClassDecl->hasTrivialDestructor()) return;
7454 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00007455
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007456 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7457 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7458 CheckDestructorAccess(VD->getLocation(), Destructor,
7459 PDiag(diag::err_access_dtor_var)
7460 << VD->getDeclName()
7461 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00007462
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007463 if (!VD->hasGlobalStorage()) return;
7464
7465 // Emit warning for non-trivial dtor in global scope (a real global,
7466 // class-static, function-static).
7467 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7468
7469 // TODO: this should be re-enabled for static locals by !CXAAtExit
7470 if (!VD->isStaticLocal())
7471 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007472}
7473
Mike Stump1eb44332009-09-09 15:08:12 +00007474/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007475/// ActOnDeclarator, when a C++ direct initializer is present.
7476/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00007477void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007478 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007479 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00007480 SourceLocation RParenLoc,
7481 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00007482 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007483
7484 // If there is no declaration, there was an error parsing it. Just ignore
7485 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00007486 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007487 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007488
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007489 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7490 if (!VDecl) {
7491 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7492 RealDecl->setInvalidDecl();
7493 return;
7494 }
7495
Richard Smith34b41d92011-02-20 03:19:35 +00007496 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7497 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00007498 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7499 if (Exprs.size() > 1) {
7500 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7501 diag::err_auto_var_init_multiple_expressions)
7502 << VDecl->getDeclName() << VDecl->getType()
7503 << VDecl->getSourceRange();
7504 RealDecl->setInvalidDecl();
7505 return;
7506 }
7507
7508 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00007509 TypeSourceInfo *DeducedType = 0;
7510 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00007511 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7512 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7513 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00007514 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00007515 RealDecl->setInvalidDecl();
7516 return;
7517 }
Richard Smitha085da82011-03-17 16:11:59 +00007518 VDecl->setTypeSourceInfo(DeducedType);
7519 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00007520
John McCallf85e1932011-06-15 23:02:42 +00007521 // In ARC, infer lifetime.
7522 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7523 VDecl->setInvalidDecl();
7524
Richard Smith34b41d92011-02-20 03:19:35 +00007525 // If this is a redeclaration, check that the type we just deduced matches
7526 // the previously declared type.
7527 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7528 MergeVarDeclTypes(VDecl, Old);
7529 }
7530
Douglas Gregor83ddad32009-08-26 21:14:46 +00007531 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007532 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007533 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7534 //
7535 // Clients that want to distinguish between the two forms, can check for
7536 // direct initializer using VarDecl::hasCXXDirectInitializer().
7537 // A major benefit is that clients that don't particularly care about which
7538 // exactly form was it (like the CodeGen) can handle both cases without
7539 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007540
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007541 // C++ 8.5p11:
7542 // The form of initialization (using parentheses or '=') is generally
7543 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007544 // class type.
7545
Douglas Gregor4dffad62010-02-11 22:55:30 +00007546 if (!VDecl->getType()->isDependentType() &&
7547 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00007548 diag::err_typecheck_decl_incomplete_type)) {
7549 VDecl->setInvalidDecl();
7550 return;
7551 }
7552
Douglas Gregor90f93822009-12-22 22:17:25 +00007553 // The variable can not have an abstract class type.
7554 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7555 diag::err_abstract_type_in_decl,
7556 AbstractVariableType))
7557 VDecl->setInvalidDecl();
7558
Sebastian Redl31310a22010-02-01 20:16:42 +00007559 const VarDecl *Def;
7560 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00007561 Diag(VDecl->getLocation(), diag::err_redefinition)
7562 << VDecl->getDeclName();
7563 Diag(Def->getLocation(), diag::note_previous_definition);
7564 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007565 return;
7566 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00007567
Douglas Gregor3a91abf2010-08-24 05:27:49 +00007568 // C++ [class.static.data]p4
7569 // If a static data member is of const integral or const
7570 // enumeration type, its declaration in the class definition can
7571 // specify a constant-initializer which shall be an integral
7572 // constant expression (5.19). In that case, the member can appear
7573 // in integral constant expressions. The member shall still be
7574 // defined in a namespace scope if it is used in the program and the
7575 // namespace scope definition shall not contain an initializer.
7576 //
7577 // We already performed a redefinition check above, but for static
7578 // data members we also need to check whether there was an in-class
7579 // declaration with an initializer.
7580 const VarDecl* PrevInit = 0;
7581 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7582 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7583 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7584 return;
7585 }
7586
Douglas Gregora31040f2010-12-16 01:31:22 +00007587 bool IsDependent = false;
7588 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7589 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7590 VDecl->setInvalidDecl();
7591 return;
7592 }
7593
7594 if (Exprs.get()[I]->isTypeDependent())
7595 IsDependent = true;
7596 }
7597
Douglas Gregor4dffad62010-02-11 22:55:30 +00007598 // If either the declaration has a dependent type or if any of the
7599 // expressions is type-dependent, we represent the initialization
7600 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00007601 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00007602 // Let clients know that initialization was done with a direct initializer.
7603 VDecl->setCXXDirectInitializer(true);
7604
7605 // Store the initialization expressions as a ParenListExpr.
7606 unsigned NumExprs = Exprs.size();
7607 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7608 (Expr **)Exprs.release(),
7609 NumExprs, RParenLoc));
7610 return;
7611 }
Douglas Gregor90f93822009-12-22 22:17:25 +00007612
7613 // Capture the variable that is being initialized and the style of
7614 // initialization.
7615 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7616
7617 // FIXME: Poor source location information.
7618 InitializationKind Kind
7619 = InitializationKind::CreateDirect(VDecl->getLocation(),
7620 LParenLoc, RParenLoc);
7621
7622 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00007623 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00007624 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00007625 if (Result.isInvalid()) {
7626 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007627 return;
7628 }
John McCallb4eb64d2010-10-08 02:01:28 +00007629
7630 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00007631
Douglas Gregor53c374f2010-12-07 00:41:46 +00007632 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00007633 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007634 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007635
John McCall2998d6b2011-01-19 11:48:09 +00007636 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007637}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00007638
Douglas Gregor39da0b82009-09-09 23:08:42 +00007639/// \brief Given a constructor and the set of arguments provided for the
7640/// constructor, convert the arguments and add any required default arguments
7641/// to form a proper call to this constructor.
7642///
7643/// \returns true if an error occurred, false otherwise.
7644bool
7645Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7646 MultiExprArg ArgsPtr,
7647 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00007648 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00007649 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7650 unsigned NumArgs = ArgsPtr.size();
7651 Expr **Args = (Expr **)ArgsPtr.get();
7652
7653 const FunctionProtoType *Proto
7654 = Constructor->getType()->getAs<FunctionProtoType>();
7655 assert(Proto && "Constructor without a prototype?");
7656 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00007657
7658 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007659 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00007660 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007661 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00007662 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007663
7664 VariadicCallType CallType =
7665 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7666 llvm::SmallVector<Expr *, 8> AllArgs;
7667 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7668 Proto, 0, Args, NumArgs, AllArgs,
7669 CallType);
7670 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7671 ConvertedArgs.push_back(AllArgs[i]);
7672 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00007673}
7674
Anders Carlsson20d45d22009-12-12 00:32:00 +00007675static inline bool
7676CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7677 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007678 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00007679 if (isa<NamespaceDecl>(DC)) {
7680 return SemaRef.Diag(FnDecl->getLocation(),
7681 diag::err_operator_new_delete_declared_in_namespace)
7682 << FnDecl->getDeclName();
7683 }
7684
7685 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00007686 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007687 return SemaRef.Diag(FnDecl->getLocation(),
7688 diag::err_operator_new_delete_declared_static)
7689 << FnDecl->getDeclName();
7690 }
7691
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00007692 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00007693}
7694
Anders Carlsson156c78e2009-12-13 17:53:43 +00007695static inline bool
7696CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7697 CanQualType ExpectedResultType,
7698 CanQualType ExpectedFirstParamType,
7699 unsigned DependentParamTypeDiag,
7700 unsigned InvalidParamTypeDiag) {
7701 QualType ResultType =
7702 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7703
7704 // Check that the result type is not dependent.
7705 if (ResultType->isDependentType())
7706 return SemaRef.Diag(FnDecl->getLocation(),
7707 diag::err_operator_new_delete_dependent_result_type)
7708 << FnDecl->getDeclName() << ExpectedResultType;
7709
7710 // Check that the result type is what we expect.
7711 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7712 return SemaRef.Diag(FnDecl->getLocation(),
7713 diag::err_operator_new_delete_invalid_result_type)
7714 << FnDecl->getDeclName() << ExpectedResultType;
7715
7716 // A function template must have at least 2 parameters.
7717 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7718 return SemaRef.Diag(FnDecl->getLocation(),
7719 diag::err_operator_new_delete_template_too_few_parameters)
7720 << FnDecl->getDeclName();
7721
7722 // The function decl must have at least 1 parameter.
7723 if (FnDecl->getNumParams() == 0)
7724 return SemaRef.Diag(FnDecl->getLocation(),
7725 diag::err_operator_new_delete_too_few_parameters)
7726 << FnDecl->getDeclName();
7727
7728 // Check the the first parameter type is not dependent.
7729 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7730 if (FirstParamType->isDependentType())
7731 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7732 << FnDecl->getDeclName() << ExpectedFirstParamType;
7733
7734 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00007735 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00007736 ExpectedFirstParamType)
7737 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7738 << FnDecl->getDeclName() << ExpectedFirstParamType;
7739
7740 return false;
7741}
7742
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007743static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00007744CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007745 // C++ [basic.stc.dynamic.allocation]p1:
7746 // A program is ill-formed if an allocation function is declared in a
7747 // namespace scope other than global scope or declared static in global
7748 // scope.
7749 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7750 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007751
7752 CanQualType SizeTy =
7753 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7754
7755 // C++ [basic.stc.dynamic.allocation]p1:
7756 // The return type shall be void*. The first parameter shall have type
7757 // std::size_t.
7758 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7759 SizeTy,
7760 diag::err_operator_new_dependent_param_type,
7761 diag::err_operator_new_param_type))
7762 return true;
7763
7764 // C++ [basic.stc.dynamic.allocation]p1:
7765 // The first parameter shall not have an associated default argument.
7766 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007767 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007768 diag::err_operator_new_default_arg)
7769 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7770
7771 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007772}
7773
7774static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007775CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7776 // C++ [basic.stc.dynamic.deallocation]p1:
7777 // A program is ill-formed if deallocation functions are declared in a
7778 // namespace scope other than global scope or declared static in global
7779 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007780 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7781 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007782
7783 // C++ [basic.stc.dynamic.deallocation]p2:
7784 // Each deallocation function shall return void and its first parameter
7785 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007786 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7787 SemaRef.Context.VoidPtrTy,
7788 diag::err_operator_delete_dependent_param_type,
7789 diag::err_operator_delete_param_type))
7790 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007791
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007792 return false;
7793}
7794
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007795/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7796/// of this overloaded operator is well-formed. If so, returns false;
7797/// otherwise, emits appropriate diagnostics and returns true.
7798bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007799 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007800 "Expected an overloaded operator declaration");
7801
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007802 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7803
Mike Stump1eb44332009-09-09 15:08:12 +00007804 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007805 // The allocation and deallocation functions, operator new,
7806 // operator new[], operator delete and operator delete[], are
7807 // described completely in 3.7.3. The attributes and restrictions
7808 // found in the rest of this subclause do not apply to them unless
7809 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007810 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007811 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007812
Anders Carlssona3ccda52009-12-12 00:26:23 +00007813 if (Op == OO_New || Op == OO_Array_New)
7814 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007815
7816 // C++ [over.oper]p6:
7817 // An operator function shall either be a non-static member
7818 // function or be a non-member function and have at least one
7819 // parameter whose type is a class, a reference to a class, an
7820 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007821 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7822 if (MethodDecl->isStatic())
7823 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007824 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007825 } else {
7826 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007827 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7828 ParamEnd = FnDecl->param_end();
7829 Param != ParamEnd; ++Param) {
7830 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007831 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7832 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007833 ClassOrEnumParam = true;
7834 break;
7835 }
7836 }
7837
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007838 if (!ClassOrEnumParam)
7839 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007840 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007841 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007842 }
7843
7844 // C++ [over.oper]p8:
7845 // An operator function cannot have default arguments (8.3.6),
7846 // except where explicitly stated below.
7847 //
Mike Stump1eb44332009-09-09 15:08:12 +00007848 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007849 // (C++ [over.call]p1).
7850 if (Op != OO_Call) {
7851 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7852 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007853 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007854 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007855 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007856 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007857 }
7858 }
7859
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007860 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7861 { false, false, false }
7862#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7863 , { Unary, Binary, MemberOnly }
7864#include "clang/Basic/OperatorKinds.def"
7865 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007866
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007867 bool CanBeUnaryOperator = OperatorUses[Op][0];
7868 bool CanBeBinaryOperator = OperatorUses[Op][1];
7869 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007870
7871 // C++ [over.oper]p8:
7872 // [...] Operator functions cannot have more or fewer parameters
7873 // than the number required for the corresponding operator, as
7874 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007875 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007876 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007877 if (Op != OO_Call &&
7878 ((NumParams == 1 && !CanBeUnaryOperator) ||
7879 (NumParams == 2 && !CanBeBinaryOperator) ||
7880 (NumParams < 1) || (NumParams > 2))) {
7881 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007882 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007883 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007884 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007885 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007886 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007887 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007888 assert(CanBeBinaryOperator &&
7889 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007890 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007891 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007892
Chris Lattner416e46f2008-11-21 07:57:12 +00007893 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007894 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007895 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007896
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007897 // Overloaded operators other than operator() cannot be variadic.
7898 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007899 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007900 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007901 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007902 }
7903
7904 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007905 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7906 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007907 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007908 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007909 }
7910
7911 // C++ [over.inc]p1:
7912 // The user-defined function called operator++ implements the
7913 // prefix and postfix ++ operator. If this function is a member
7914 // function with no parameters, or a non-member function with one
7915 // parameter of class or enumeration type, it defines the prefix
7916 // increment operator ++ for objects of that type. If the function
7917 // is a member function with one parameter (which shall be of type
7918 // int) or a non-member function with two parameters (the second
7919 // of which shall be of type int), it defines the postfix
7920 // increment operator ++ for objects of that type.
7921 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7922 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7923 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007924 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007925 ParamIsInt = BT->getKind() == BuiltinType::Int;
7926
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007927 if (!ParamIsInt)
7928 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007929 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007930 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007931 }
7932
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007933 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007934}
Chris Lattner5a003a42008-12-17 07:09:26 +00007935
Sean Hunta6c058d2010-01-13 09:01:02 +00007936/// CheckLiteralOperatorDeclaration - Check whether the declaration
7937/// of this literal operator function is well-formed. If so, returns
7938/// false; otherwise, emits appropriate diagnostics and returns true.
7939bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7940 DeclContext *DC = FnDecl->getDeclContext();
7941 Decl::Kind Kind = DC->getDeclKind();
7942 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7943 Kind != Decl::LinkageSpec) {
7944 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7945 << FnDecl->getDeclName();
7946 return true;
7947 }
7948
7949 bool Valid = false;
7950
Sean Hunt216c2782010-04-07 23:11:06 +00007951 // template <char...> type operator "" name() is the only valid template
7952 // signature, and the only valid signature with no parameters.
7953 if (FnDecl->param_size() == 0) {
7954 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7955 // Must have only one template parameter
7956 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7957 if (Params->size() == 1) {
7958 NonTypeTemplateParmDecl *PmDecl =
7959 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007960
Sean Hunt216c2782010-04-07 23:11:06 +00007961 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007962 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7963 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7964 Valid = true;
7965 }
7966 }
7967 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007968 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007969 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7970
Sean Hunta6c058d2010-01-13 09:01:02 +00007971 QualType T = (*Param)->getType();
7972
Sean Hunt30019c02010-04-07 22:57:35 +00007973 // unsigned long long int, long double, and any character type are allowed
7974 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007975 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7976 Context.hasSameType(T, Context.LongDoubleTy) ||
7977 Context.hasSameType(T, Context.CharTy) ||
7978 Context.hasSameType(T, Context.WCharTy) ||
7979 Context.hasSameType(T, Context.Char16Ty) ||
7980 Context.hasSameType(T, Context.Char32Ty)) {
7981 if (++Param == FnDecl->param_end())
7982 Valid = true;
7983 goto FinishedParams;
7984 }
7985
Sean Hunt30019c02010-04-07 22:57:35 +00007986 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007987 const PointerType *PT = T->getAs<PointerType>();
7988 if (!PT)
7989 goto FinishedParams;
7990 T = PT->getPointeeType();
7991 if (!T.isConstQualified())
7992 goto FinishedParams;
7993 T = T.getUnqualifiedType();
7994
7995 // Move on to the second parameter;
7996 ++Param;
7997
7998 // If there is no second parameter, the first must be a const char *
7999 if (Param == FnDecl->param_end()) {
8000 if (Context.hasSameType(T, Context.CharTy))
8001 Valid = true;
8002 goto FinishedParams;
8003 }
8004
8005 // const char *, const wchar_t*, const char16_t*, and const char32_t*
8006 // are allowed as the first parameter to a two-parameter function
8007 if (!(Context.hasSameType(T, Context.CharTy) ||
8008 Context.hasSameType(T, Context.WCharTy) ||
8009 Context.hasSameType(T, Context.Char16Ty) ||
8010 Context.hasSameType(T, Context.Char32Ty)))
8011 goto FinishedParams;
8012
8013 // The second and final parameter must be an std::size_t
8014 T = (*Param)->getType().getUnqualifiedType();
8015 if (Context.hasSameType(T, Context.getSizeType()) &&
8016 ++Param == FnDecl->param_end())
8017 Valid = true;
8018 }
8019
8020 // FIXME: This diagnostic is absolutely terrible.
8021FinishedParams:
8022 if (!Valid) {
8023 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8024 << FnDecl->getDeclName();
8025 return true;
8026 }
8027
8028 return false;
8029}
8030
Douglas Gregor074149e2009-01-05 19:45:36 +00008031/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8032/// linkage specification, including the language and (if present)
8033/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8034/// the location of the language string literal, which is provided
8035/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8036/// the '{' brace. Otherwise, this linkage specification does not
8037/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00008038Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8039 SourceLocation LangLoc,
8040 llvm::StringRef Lang,
8041 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00008042 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00008043 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00008044 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00008045 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00008046 Language = LinkageSpecDecl::lang_cxx;
8047 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00008048 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00008049 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00008050 }
Mike Stump1eb44332009-09-09 15:08:12 +00008051
Chris Lattnercc98eac2008-12-17 07:13:27 +00008052 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00008053
Douglas Gregor074149e2009-01-05 19:45:36 +00008054 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008055 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008056 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00008057 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00008058 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00008059}
8060
Abramo Bagnara35f9a192010-07-30 16:47:02 +00008061/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00008062/// the C++ linkage specification LinkageSpec. If RBraceLoc is
8063/// valid, it's the position of the closing '}' brace in a linkage
8064/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00008065Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008066 Decl *LinkageSpec,
8067 SourceLocation RBraceLoc) {
8068 if (LinkageSpec) {
8069 if (RBraceLoc.isValid()) {
8070 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8071 LSDecl->setRBraceLoc(RBraceLoc);
8072 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008073 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008074 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008075 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00008076}
8077
Douglas Gregord308e622009-05-18 20:51:54 +00008078/// \brief Perform semantic analysis for the variable declaration that
8079/// occurs within a C++ catch clause, returning the newly-created
8080/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008081VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00008082 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008083 SourceLocation StartLoc,
8084 SourceLocation Loc,
8085 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00008086 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00008087 QualType ExDeclType = TInfo->getType();
8088
Sebastian Redl4b07b292008-12-22 19:15:10 +00008089 // Arrays and functions decay.
8090 if (ExDeclType->isArrayType())
8091 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8092 else if (ExDeclType->isFunctionType())
8093 ExDeclType = Context.getPointerType(ExDeclType);
8094
8095 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8096 // The exception-declaration shall not denote a pointer or reference to an
8097 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008098 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00008099 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00008100 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008101 Invalid = true;
8102 }
Douglas Gregord308e622009-05-18 20:51:54 +00008103
Douglas Gregora2762912010-03-08 01:47:36 +00008104 // GCC allows catching pointers and references to incomplete types
8105 // as an extension; so do we, but we warn by default.
8106
Sebastian Redl4b07b292008-12-22 19:15:10 +00008107 QualType BaseType = ExDeclType;
8108 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008109 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00008110 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00008111 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008112 BaseType = Ptr->getPointeeType();
8113 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00008114 DK = diag::ext_catch_incomplete_ptr;
8115 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008116 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008117 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008118 BaseType = Ref->getPointeeType();
8119 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00008120 DK = diag::ext_catch_incomplete_ref;
8121 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008122 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008123 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00008124 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8125 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00008126 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008127
Mike Stump1eb44332009-09-09 15:08:12 +00008128 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00008129 RequireNonAbstractType(Loc, ExDeclType,
8130 diag::err_abstract_type_in_decl,
8131 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00008132 Invalid = true;
8133
John McCall5a180392010-07-24 00:37:23 +00008134 // Only the non-fragile NeXT runtime currently supports C++ catches
8135 // of ObjC types, and no runtime supports catching ObjC types by value.
8136 if (!Invalid && getLangOptions().ObjC1) {
8137 QualType T = ExDeclType;
8138 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8139 T = RT->getPointeeType();
8140
8141 if (T->isObjCObjectType()) {
8142 Diag(Loc, diag::err_objc_object_catch);
8143 Invalid = true;
8144 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00008145 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00008146 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8147 Invalid = true;
8148 }
8149 }
8150 }
8151
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008152 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8153 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00008154 ExDecl->setExceptionVariable(true);
8155
Douglas Gregor6d182892010-03-05 23:38:39 +00008156 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00008157 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00008158 // C++ [except.handle]p16:
8159 // The object declared in an exception-declaration or, if the
8160 // exception-declaration does not specify a name, a temporary (12.2) is
8161 // copy-initialized (8.5) from the exception object. [...]
8162 // The object is destroyed when the handler exits, after the destruction
8163 // of any automatic objects initialized within the handler.
8164 //
8165 // We just pretend to initialize the object with itself, then make sure
8166 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00008167 QualType initType = ExDeclType;
8168
8169 InitializedEntity entity =
8170 InitializedEntity::InitializeVariable(ExDecl);
8171 InitializationKind initKind =
8172 InitializationKind::CreateCopy(Loc, SourceLocation());
8173
8174 Expr *opaqueValue =
8175 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8176 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8177 ExprResult result = sequence.Perform(*this, entity, initKind,
8178 MultiExprArg(&opaqueValue, 1));
8179 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00008180 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00008181 else {
8182 // If the constructor used was non-trivial, set this as the
8183 // "initializer".
8184 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8185 if (!construct->getConstructor()->isTrivial()) {
8186 Expr *init = MaybeCreateExprWithCleanups(construct);
8187 ExDecl->setInit(init);
8188 }
8189
8190 // And make sure it's destructable.
8191 FinalizeVarWithDestructor(ExDecl, recordType);
8192 }
Douglas Gregor6d182892010-03-05 23:38:39 +00008193 }
8194 }
8195
Douglas Gregord308e622009-05-18 20:51:54 +00008196 if (Invalid)
8197 ExDecl->setInvalidDecl();
8198
8199 return ExDecl;
8200}
8201
8202/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8203/// handler.
John McCalld226f652010-08-21 09:40:31 +00008204Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00008205 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00008206 bool Invalid = D.isInvalidType();
8207
8208 // Check for unexpanded parameter packs.
8209 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8210 UPPC_ExceptionType)) {
8211 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8212 D.getIdentifierLoc());
8213 Invalid = true;
8214 }
8215
Sebastian Redl4b07b292008-12-22 19:15:10 +00008216 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00008217 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00008218 LookupOrdinaryName,
8219 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008220 // The scope should be freshly made just for us. There is just no way
8221 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00008222 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00008223 if (PrevDecl->isTemplateParameter()) {
8224 // Maybe we will complain about the shadowed template parameter.
8225 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008226 }
8227 }
8228
Chris Lattnereaaebc72009-04-25 08:06:05 +00008229 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008230 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8231 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00008232 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008233 }
8234
Douglas Gregor83cb9422010-09-09 17:09:21 +00008235 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008236 D.getSourceRange().getBegin(),
8237 D.getIdentifierLoc(),
8238 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00008239 if (Invalid)
8240 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00008241
Sebastian Redl4b07b292008-12-22 19:15:10 +00008242 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008243 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00008244 PushOnScopeChains(ExDecl, S);
8245 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008246 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008247
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008248 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00008249 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008250}
Anders Carlssonfb311762009-03-14 00:25:26 +00008251
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008252Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008253 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008254 Expr *AssertMessageExpr_,
8255 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00008256 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00008257
Anders Carlssonc3082412009-03-14 00:33:21 +00008258 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8259 llvm::APSInt Value(32);
8260 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008261 Diag(StaticAssertLoc,
8262 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00008263 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008264 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00008265 }
Anders Carlssonfb311762009-03-14 00:25:26 +00008266
Anders Carlssonc3082412009-03-14 00:33:21 +00008267 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008268 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00008269 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00008270 }
8271 }
Mike Stump1eb44332009-09-09 15:08:12 +00008272
Douglas Gregor399ad972010-12-15 23:55:21 +00008273 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8274 return 0;
8275
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008276 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8277 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008278
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008279 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00008280 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00008281}
Sebastian Redl50de12f2009-03-24 22:27:57 +00008282
Douglas Gregor1d869352010-04-07 16:53:43 +00008283/// \brief Perform semantic analysis of the given friend type declaration.
8284///
8285/// \returns A friend declaration that.
8286FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8287 TypeSourceInfo *TSInfo) {
8288 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8289
8290 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008291 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00008292
Douglas Gregor06245bf2010-04-07 17:57:12 +00008293 if (!getLangOptions().CPlusPlus0x) {
8294 // C++03 [class.friend]p2:
8295 // An elaborated-type-specifier shall be used in a friend declaration
8296 // for a class.*
8297 //
8298 // * The class-key of the elaborated-type-specifier is required.
8299 if (!ActiveTemplateInstantiations.empty()) {
8300 // Do not complain about the form of friend template types during
8301 // template instantiation; we will already have complained when the
8302 // template was declared.
8303 } else if (!T->isElaboratedTypeSpecifier()) {
8304 // If we evaluated the type to a record type, suggest putting
8305 // a tag in front.
8306 if (const RecordType *RT = T->getAs<RecordType>()) {
8307 RecordDecl *RD = RT->getDecl();
8308
8309 std::string InsertionText = std::string(" ") + RD->getKindName();
8310
8311 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8312 << (unsigned) RD->getTagKind()
8313 << T
8314 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8315 InsertionText);
8316 } else {
8317 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8318 << T
8319 << SourceRange(FriendLoc, TypeRange.getEnd());
8320 }
8321 } else if (T->getAs<EnumType>()) {
8322 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00008323 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00008324 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00008325 }
8326 }
8327
Douglas Gregor06245bf2010-04-07 17:57:12 +00008328 // C++0x [class.friend]p3:
8329 // If the type specifier in a friend declaration designates a (possibly
8330 // cv-qualified) class type, that class is declared as a friend; otherwise,
8331 // the friend declaration is ignored.
8332
8333 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8334 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00008335
8336 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8337}
8338
John McCall9a34edb2010-10-19 01:40:49 +00008339/// Handle a friend tag declaration where the scope specifier was
8340/// templated.
8341Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8342 unsigned TagSpec, SourceLocation TagLoc,
8343 CXXScopeSpec &SS,
8344 IdentifierInfo *Name, SourceLocation NameLoc,
8345 AttributeList *Attr,
8346 MultiTemplateParamsArg TempParamLists) {
8347 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8348
8349 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00008350 bool Invalid = false;
8351
8352 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00008353 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00008354 TempParamLists.get(),
8355 TempParamLists.size(),
8356 /*friend*/ true,
8357 isExplicitSpecialization,
8358 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00008359 if (TemplateParams->size() > 0) {
8360 // This is a declaration of a class template.
8361 if (Invalid)
8362 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008363
John McCall9a34edb2010-10-19 01:40:49 +00008364 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8365 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008366 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008367 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008368 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00008369 } else {
8370 // The "template<>" header is extraneous.
8371 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8372 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8373 isExplicitSpecialization = true;
8374 }
8375 }
8376
8377 if (Invalid) return 0;
8378
8379 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8380
8381 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008382 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00008383 if (TempParamLists.get()[I]->size()) {
8384 isAllExplicitSpecializations = false;
8385 break;
8386 }
8387 }
8388
8389 // FIXME: don't ignore attributes.
8390
8391 // If it's explicit specializations all the way down, just forget
8392 // about the template header and build an appropriate non-templated
8393 // friend. TODO: for source fidelity, remember the headers.
8394 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00008395 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00008396 ElaboratedTypeKeyword Keyword
8397 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008398 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00008399 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008400 if (T.isNull())
8401 return 0;
8402
8403 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8404 if (isa<DependentNameType>(T)) {
8405 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8406 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008407 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008408 TL.setNameLoc(NameLoc);
8409 } else {
8410 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8411 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00008412 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008413 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8414 }
8415
8416 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8417 TSI, FriendLoc);
8418 Friend->setAccess(AS_public);
8419 CurContext->addDecl(Friend);
8420 return Friend;
8421 }
8422
8423 // Handle the case of a templated-scope friend class. e.g.
8424 // template <class T> class A<T>::B;
8425 // FIXME: we don't support these right now.
8426 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8427 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8428 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8429 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8430 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008431 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00008432 TL.setNameLoc(NameLoc);
8433
8434 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8435 TSI, FriendLoc);
8436 Friend->setAccess(AS_public);
8437 Friend->setUnsupportedFriend(true);
8438 CurContext->addDecl(Friend);
8439 return Friend;
8440}
8441
8442
John McCalldd4a3b02009-09-16 22:47:08 +00008443/// Handle a friend type declaration. This works in tandem with
8444/// ActOnTag.
8445///
8446/// Notes on friend class templates:
8447///
8448/// We generally treat friend class declarations as if they were
8449/// declaring a class. So, for example, the elaborated type specifier
8450/// in a friend declaration is required to obey the restrictions of a
8451/// class-head (i.e. no typedefs in the scope chain), template
8452/// parameters are required to match up with simple template-ids, &c.
8453/// However, unlike when declaring a template specialization, it's
8454/// okay to refer to a template specialization without an empty
8455/// template parameter declaration, e.g.
8456/// friend class A<T>::B<unsigned>;
8457/// We permit this as a special case; if there are any template
8458/// parameters present at all, require proper matching, i.e.
8459/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00008460Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00008461 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00008462 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00008463
8464 assert(DS.isFriendSpecified());
8465 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8466
John McCalldd4a3b02009-09-16 22:47:08 +00008467 // Try to convert the decl specifier to a type. This works for
8468 // friend templates because ActOnTag never produces a ClassTemplateDecl
8469 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00008470 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00008471 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8472 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00008473 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00008474 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008475
Douglas Gregor6ccab972010-12-16 01:14:37 +00008476 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8477 return 0;
8478
John McCalldd4a3b02009-09-16 22:47:08 +00008479 // This is definitely an error in C++98. It's probably meant to
8480 // be forbidden in C++0x, too, but the specification is just
8481 // poorly written.
8482 //
8483 // The problem is with declarations like the following:
8484 // template <T> friend A<T>::foo;
8485 // where deciding whether a class C is a friend or not now hinges
8486 // on whether there exists an instantiation of A that causes
8487 // 'foo' to equal C. There are restrictions on class-heads
8488 // (which we declare (by fiat) elaborated friend declarations to
8489 // be) that makes this tractable.
8490 //
8491 // FIXME: handle "template <> friend class A<T>;", which
8492 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00008493 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00008494 Diag(Loc, diag::err_tagless_friend_type_template)
8495 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008496 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00008497 }
Douglas Gregor1d869352010-04-07 16:53:43 +00008498
John McCall02cace72009-08-28 07:59:38 +00008499 // C++98 [class.friend]p1: A friend of a class is a function
8500 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00008501 // This is fixed in DR77, which just barely didn't make the C++03
8502 // deadline. It's also a very silly restriction that seriously
8503 // affects inner classes and which nobody else seems to implement;
8504 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00008505 //
8506 // But note that we could warn about it: it's always useless to
8507 // friend one of your own members (it's not, however, worthless to
8508 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00008509
John McCalldd4a3b02009-09-16 22:47:08 +00008510 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00008511 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00008512 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00008513 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00008514 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00008515 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00008516 DS.getFriendSpecLoc());
8517 else
Douglas Gregor1d869352010-04-07 16:53:43 +00008518 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8519
8520 if (!D)
John McCalld226f652010-08-21 09:40:31 +00008521 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00008522
John McCalldd4a3b02009-09-16 22:47:08 +00008523 D->setAccess(AS_public);
8524 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00008525
John McCalld226f652010-08-21 09:40:31 +00008526 return D;
John McCall02cace72009-08-28 07:59:38 +00008527}
8528
John McCall337ec3d2010-10-12 23:13:28 +00008529Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8530 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00008531 const DeclSpec &DS = D.getDeclSpec();
8532
8533 assert(DS.isFriendSpecified());
8534 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8535
8536 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00008537 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8538 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00008539
8540 // C++ [class.friend]p1
8541 // A friend of a class is a function or class....
8542 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00008543 // It *doesn't* see through dependent types, which is correct
8544 // according to [temp.arg.type]p3:
8545 // If a declaration acquires a function type through a
8546 // type dependent on a template-parameter and this causes
8547 // a declaration that does not use the syntactic form of a
8548 // function declarator to have a function type, the program
8549 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00008550 if (!T->isFunctionType()) {
8551 Diag(Loc, diag::err_unexpected_friend);
8552
8553 // It might be worthwhile to try to recover by creating an
8554 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00008555 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008556 }
8557
8558 // C++ [namespace.memdef]p3
8559 // - If a friend declaration in a non-local class first declares a
8560 // class or function, the friend class or function is a member
8561 // of the innermost enclosing namespace.
8562 // - The name of the friend is not found by simple name lookup
8563 // until a matching declaration is provided in that namespace
8564 // scope (either before or after the class declaration granting
8565 // friendship).
8566 // - If a friend function is called, its name may be found by the
8567 // name lookup that considers functions from namespaces and
8568 // classes associated with the types of the function arguments.
8569 // - When looking for a prior declaration of a class or a function
8570 // declared as a friend, scopes outside the innermost enclosing
8571 // namespace scope are not considered.
8572
John McCall337ec3d2010-10-12 23:13:28 +00008573 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00008574 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8575 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00008576 assert(Name);
8577
Douglas Gregor6ccab972010-12-16 01:14:37 +00008578 // Check for unexpanded parameter packs.
8579 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8580 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8581 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8582 return 0;
8583
John McCall67d1a672009-08-06 02:15:43 +00008584 // The context we found the declaration in, or in which we should
8585 // create the declaration.
8586 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00008587 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00008588 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00008589 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00008590
John McCall337ec3d2010-10-12 23:13:28 +00008591 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00008592
John McCall337ec3d2010-10-12 23:13:28 +00008593 // There are four cases here.
8594 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00008595 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00008596 // there as appropriate.
8597 // Recover from invalid scope qualifiers as if they just weren't there.
8598 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00008599 // C++0x [namespace.memdef]p3:
8600 // If the name in a friend declaration is neither qualified nor
8601 // a template-id and the declaration is a function or an
8602 // elaborated-type-specifier, the lookup to determine whether
8603 // the entity has been previously declared shall not consider
8604 // any scopes outside the innermost enclosing namespace.
8605 // C++0x [class.friend]p11:
8606 // If a friend declaration appears in a local class and the name
8607 // specified is an unqualified name, a prior declaration is
8608 // looked up without considering scopes that are outside the
8609 // innermost enclosing non-class scope. For a friend function
8610 // declaration, if there is no prior declaration, the program is
8611 // ill-formed.
8612 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00008613 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00008614
John McCall29ae6e52010-10-13 05:45:15 +00008615 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00008616 DC = CurContext;
8617 while (true) {
8618 // Skip class contexts. If someone can cite chapter and verse
8619 // for this behavior, that would be nice --- it's what GCC and
8620 // EDG do, and it seems like a reasonable intent, but the spec
8621 // really only says that checks for unqualified existing
8622 // declarations should stop at the nearest enclosing namespace,
8623 // not that they should only consider the nearest enclosing
8624 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00008625 while (DC->isRecord())
8626 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00008627
John McCall68263142009-11-18 22:49:29 +00008628 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00008629
8630 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00008631 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00008632 break;
John McCall29ae6e52010-10-13 05:45:15 +00008633
John McCall8a407372010-10-14 22:22:28 +00008634 if (isTemplateId) {
8635 if (isa<TranslationUnitDecl>(DC)) break;
8636 } else {
8637 if (DC->isFileContext()) break;
8638 }
John McCall67d1a672009-08-06 02:15:43 +00008639 DC = DC->getParent();
8640 }
8641
8642 // C++ [class.friend]p1: A friend of a class is a function or
8643 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00008644 // C++0x changes this for both friend types and functions.
8645 // Most C++ 98 compilers do seem to give an error here, so
8646 // we do, too.
John McCall68263142009-11-18 22:49:29 +00008647 if (!Previous.empty() && DC->Equals(CurContext)
8648 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00008649 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00008650
John McCall380aaa42010-10-13 06:22:15 +00008651 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00008652
John McCall337ec3d2010-10-12 23:13:28 +00008653 // - There's a non-dependent scope specifier, in which case we
8654 // compute it and do a previous lookup there for a function
8655 // or function template.
8656 } else if (!SS.getScopeRep()->isDependent()) {
8657 DC = computeDeclContext(SS);
8658 if (!DC) return 0;
8659
8660 if (RequireCompleteDeclContext(SS, DC)) return 0;
8661
8662 LookupQualifiedName(Previous, DC);
8663
8664 // Ignore things found implicitly in the wrong scope.
8665 // TODO: better diagnostics for this case. Suggesting the right
8666 // qualified scope would be nice...
8667 LookupResult::Filter F = Previous.makeFilter();
8668 while (F.hasNext()) {
8669 NamedDecl *D = F.next();
8670 if (!DC->InEnclosingNamespaceSetOf(
8671 D->getDeclContext()->getRedeclContext()))
8672 F.erase();
8673 }
8674 F.done();
8675
8676 if (Previous.empty()) {
8677 D.setInvalidType();
8678 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8679 return 0;
8680 }
8681
8682 // C++ [class.friend]p1: A friend of a class is a function or
8683 // class that is not a member of the class . . .
8684 if (DC->Equals(CurContext))
8685 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8686
8687 // - There's a scope specifier that does not match any template
8688 // parameter lists, in which case we use some arbitrary context,
8689 // create a method or method template, and wait for instantiation.
8690 // - There's a scope specifier that does match some template
8691 // parameter lists, which we don't handle right now.
8692 } else {
8693 DC = CurContext;
8694 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00008695 }
8696
John McCall29ae6e52010-10-13 05:45:15 +00008697 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00008698 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008699 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8700 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8701 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00008702 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008703 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8704 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00008705 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008706 }
John McCall67d1a672009-08-06 02:15:43 +00008707 }
8708
Douglas Gregor182ddf02009-09-28 00:08:27 +00008709 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00008710 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00008711 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00008712 IsDefinition,
8713 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00008714 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00008715
Douglas Gregor182ddf02009-09-28 00:08:27 +00008716 assert(ND->getDeclContext() == DC);
8717 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00008718
John McCallab88d972009-08-31 22:39:49 +00008719 // Add the function declaration to the appropriate lookup tables,
8720 // adjusting the redeclarations list as necessary. We don't
8721 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00008722 //
John McCallab88d972009-08-31 22:39:49 +00008723 // Also update the scope-based lookup if the target context's
8724 // lookup context is in lexical scope.
8725 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008726 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00008727 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008728 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00008729 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008730 }
John McCall02cace72009-08-28 07:59:38 +00008731
8732 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00008733 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00008734 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00008735 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00008736 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00008737
John McCall337ec3d2010-10-12 23:13:28 +00008738 if (ND->isInvalidDecl())
8739 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00008740 else {
8741 FunctionDecl *FD;
8742 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8743 FD = FTD->getTemplatedDecl();
8744 else
8745 FD = cast<FunctionDecl>(ND);
8746
8747 // Mark templated-scope function declarations as unsupported.
8748 if (FD->getNumTemplateParameterLists())
8749 FrD->setUnsupportedFriend(true);
8750 }
John McCall337ec3d2010-10-12 23:13:28 +00008751
John McCalld226f652010-08-21 09:40:31 +00008752 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008753}
8754
John McCalld226f652010-08-21 09:40:31 +00008755void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8756 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008757
Sebastian Redl50de12f2009-03-24 22:27:57 +00008758 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8759 if (!Fn) {
8760 Diag(DelLoc, diag::err_deleted_non_function);
8761 return;
8762 }
8763 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8764 Diag(DelLoc, diag::err_deleted_decl_not_first);
8765 Diag(Prev->getLocation(), diag::note_previous_declaration);
8766 // If the declaration wasn't the first, we delete the function anyway for
8767 // recovery.
8768 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008769 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008770}
Sebastian Redl13e88542009-04-27 21:33:24 +00008771
Sean Hunte4246a62011-05-12 06:15:49 +00008772void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8773 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8774
8775 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00008776 if (MD->getParent()->isDependentType()) {
8777 MD->setDefaulted();
8778 MD->setExplicitlyDefaulted();
8779 return;
8780 }
8781
Sean Hunte4246a62011-05-12 06:15:49 +00008782 CXXSpecialMember Member = getSpecialMember(MD);
8783 if (Member == CXXInvalid) {
8784 Diag(DefaultLoc, diag::err_default_special_members);
8785 return;
8786 }
8787
8788 MD->setDefaulted();
8789 MD->setExplicitlyDefaulted();
8790
Sean Huntcd10dec2011-05-23 23:14:04 +00008791 // If this definition appears within the record, do the checking when
8792 // the record is complete.
8793 const FunctionDecl *Primary = MD;
8794 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8795 // Find the uninstantiated declaration that actually had the '= default'
8796 // on it.
8797 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8798
8799 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00008800 return;
8801
8802 switch (Member) {
8803 case CXXDefaultConstructor: {
8804 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8805 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008806 if (!CD->isInvalidDecl())
8807 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8808 break;
8809 }
8810
8811 case CXXCopyConstructor: {
8812 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8813 CheckExplicitlyDefaultedCopyConstructor(CD);
8814 if (!CD->isInvalidDecl())
8815 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00008816 break;
8817 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008818
Sean Hunt2b188082011-05-14 05:23:28 +00008819 case CXXCopyAssignment: {
8820 CheckExplicitlyDefaultedCopyAssignment(MD);
8821 if (!MD->isInvalidDecl())
8822 DefineImplicitCopyAssignment(DefaultLoc, MD);
8823 break;
8824 }
8825
Sean Huntcb45a0f2011-05-12 22:46:25 +00008826 case CXXDestructor: {
8827 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8828 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008829 if (!DD->isInvalidDecl())
8830 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008831 break;
8832 }
8833
Sean Hunt82713172011-05-25 23:16:36 +00008834 case CXXMoveConstructor:
8835 case CXXMoveAssignment:
8836 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8837 break;
8838
Sean Hunte4246a62011-05-12 06:15:49 +00008839 default:
Sean Hunt2b188082011-05-14 05:23:28 +00008840 // FIXME: Do the rest once we have move functions
Sean Hunte4246a62011-05-12 06:15:49 +00008841 break;
8842 }
8843 } else {
8844 Diag(DefaultLoc, diag::err_default_special_members);
8845 }
8846}
8847
Sebastian Redl13e88542009-04-27 21:33:24 +00008848static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008849 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008850 Stmt *SubStmt = *CI;
8851 if (!SubStmt)
8852 continue;
8853 if (isa<ReturnStmt>(SubStmt))
8854 Self.Diag(SubStmt->getSourceRange().getBegin(),
8855 diag::err_return_in_constructor_handler);
8856 if (!isa<Expr>(SubStmt))
8857 SearchForReturnInStmt(Self, SubStmt);
8858 }
8859}
8860
8861void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8862 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8863 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8864 SearchForReturnInStmt(*this, Handler);
8865 }
8866}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008867
Mike Stump1eb44332009-09-09 15:08:12 +00008868bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008869 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008870 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8871 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008872
Chandler Carruth73857792010-02-15 11:53:20 +00008873 if (Context.hasSameType(NewTy, OldTy) ||
8874 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008875 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008876
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008877 // Check if the return types are covariant
8878 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008879
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008880 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008881 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8882 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008883 NewClassTy = NewPT->getPointeeType();
8884 OldClassTy = OldPT->getPointeeType();
8885 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008886 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8887 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8888 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8889 NewClassTy = NewRT->getPointeeType();
8890 OldClassTy = OldRT->getPointeeType();
8891 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008892 }
8893 }
Mike Stump1eb44332009-09-09 15:08:12 +00008894
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008895 // The return types aren't either both pointers or references to a class type.
8896 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008897 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008898 diag::err_different_return_type_for_overriding_virtual_function)
8899 << New->getDeclName() << NewTy << OldTy;
8900 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008901
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008902 return true;
8903 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008904
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008905 // C++ [class.virtual]p6:
8906 // If the return type of D::f differs from the return type of B::f, the
8907 // class type in the return type of D::f shall be complete at the point of
8908 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008909 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8910 if (!RT->isBeingDefined() &&
8911 RequireCompleteType(New->getLocation(), NewClassTy,
8912 PDiag(diag::err_covariant_return_incomplete)
8913 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008914 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008915 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008916
Douglas Gregora4923eb2009-11-16 21:35:15 +00008917 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008918 // Check if the new class derives from the old class.
8919 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8920 Diag(New->getLocation(),
8921 diag::err_covariant_return_not_derived)
8922 << New->getDeclName() << NewTy << OldTy;
8923 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8924 return true;
8925 }
Mike Stump1eb44332009-09-09 15:08:12 +00008926
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008927 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008928 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008929 diag::err_covariant_return_inaccessible_base,
8930 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8931 // FIXME: Should this point to the return type?
8932 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008933 // FIXME: this note won't trigger for delayed access control
8934 // diagnostics, and it's impossible to get an undelayed error
8935 // here from access control during the original parse because
8936 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008937 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8938 return true;
8939 }
8940 }
Mike Stump1eb44332009-09-09 15:08:12 +00008941
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008942 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008943 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008944 Diag(New->getLocation(),
8945 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008946 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008947 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8948 return true;
8949 };
Mike Stump1eb44332009-09-09 15:08:12 +00008950
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008951
8952 // The new class type must have the same or less qualifiers as the old type.
8953 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8954 Diag(New->getLocation(),
8955 diag::err_covariant_return_type_class_type_more_qualified)
8956 << New->getDeclName() << NewTy << OldTy;
8957 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8958 return true;
8959 };
Mike Stump1eb44332009-09-09 15:08:12 +00008960
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008961 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008962}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008963
Douglas Gregor4ba31362009-12-01 17:24:26 +00008964/// \brief Mark the given method pure.
8965///
8966/// \param Method the method to be marked pure.
8967///
8968/// \param InitRange the source range that covers the "0" initializer.
8969bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008970 SourceLocation EndLoc = InitRange.getEnd();
8971 if (EndLoc.isValid())
8972 Method->setRangeEnd(EndLoc);
8973
Douglas Gregor4ba31362009-12-01 17:24:26 +00008974 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8975 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008976 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008977 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008978
8979 if (!Method->isInvalidDecl())
8980 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8981 << Method->getDeclName() << InitRange;
8982 return true;
8983}
8984
John McCall731ad842009-12-19 09:28:58 +00008985/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8986/// an initializer for the out-of-line declaration 'Dcl'. The scope
8987/// is a fresh scope pushed for just this purpose.
8988///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008989/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8990/// static data member of class X, names should be looked up in the scope of
8991/// class X.
John McCalld226f652010-08-21 09:40:31 +00008992void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008993 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00008994 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008995
John McCall731ad842009-12-19 09:28:58 +00008996 // We should only get called for declarations with scope specifiers, like:
8997 // int foo::bar;
8998 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00008999 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009000}
9001
9002/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00009003/// initializer for the out-of-line declaration 'D'.
9004void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009005 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00009006 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009007
John McCall731ad842009-12-19 09:28:58 +00009008 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00009009 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009010}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009011
9012/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9013/// C++ if/switch/while/for statement.
9014/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00009015DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009016 // C++ 6.4p2:
9017 // The declarator shall not specify a function or an array.
9018 // The type-specifier-seq shall not contain typedef and shall not declare a
9019 // new class or enumeration.
9020 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9021 "Parser allowed 'typedef' as storage class of condition decl.");
9022
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009023 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00009024 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9025 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009026
9027 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9028 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9029 // would be created and CXXConditionDeclExpr wants a VarDecl.
9030 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9031 << D.getSourceRange();
9032 return DeclResult();
9033 } else if (OwnedTag && OwnedTag->isDefinition()) {
9034 // The type-specifier-seq shall not declare a new class or enumeration.
9035 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9036 }
9037
John McCalld226f652010-08-21 09:40:31 +00009038 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009039 if (!Dcl)
9040 return DeclResult();
9041
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009042 return Dcl;
9043}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009044
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009045void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9046 bool DefinitionRequired) {
9047 // Ignore any vtable uses in unevaluated operands or for classes that do
9048 // not have a vtable.
9049 if (!Class->isDynamicClass() || Class->isDependentContext() ||
9050 CurContext->isDependentContext() ||
9051 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00009052 return;
9053
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009054 // Try to insert this class into the map.
9055 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9056 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9057 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9058 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00009059 // If we already had an entry, check to see if we are promoting this vtable
9060 // to required a definition. If so, we need to reappend to the VTableUses
9061 // list, since we may have already processed the first entry.
9062 if (DefinitionRequired && !Pos.first->second) {
9063 Pos.first->second = true;
9064 } else {
9065 // Otherwise, we can early exit.
9066 return;
9067 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009068 }
9069
9070 // Local classes need to have their virtual members marked
9071 // immediately. For all other classes, we mark their virtual members
9072 // at the end of the translation unit.
9073 if (Class->isLocalClass())
9074 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00009075 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009076 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00009077}
9078
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009079bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009080 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00009081 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00009082
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009083 // Note: The VTableUses vector could grow as a result of marking
9084 // the members of a class as "used", so we check the size each
9085 // time through the loop and prefer indices (with are stable) to
9086 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00009087 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009088 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00009089 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009090 if (!Class)
9091 continue;
9092
9093 SourceLocation Loc = VTableUses[I].second;
9094
9095 // If this class has a key function, but that key function is
9096 // defined in another translation unit, we don't need to emit the
9097 // vtable even though we're using it.
9098 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009099 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009100 switch (KeyFunction->getTemplateSpecializationKind()) {
9101 case TSK_Undeclared:
9102 case TSK_ExplicitSpecialization:
9103 case TSK_ExplicitInstantiationDeclaration:
9104 // The key function is in another translation unit.
9105 continue;
9106
9107 case TSK_ExplicitInstantiationDefinition:
9108 case TSK_ImplicitInstantiation:
9109 // We will be instantiating the key function.
9110 break;
9111 }
9112 } else if (!KeyFunction) {
9113 // If we have a class with no key function that is the subject
9114 // of an explicit instantiation declaration, suppress the
9115 // vtable; it will live with the explicit instantiation
9116 // definition.
9117 bool IsExplicitInstantiationDeclaration
9118 = Class->getTemplateSpecializationKind()
9119 == TSK_ExplicitInstantiationDeclaration;
9120 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9121 REnd = Class->redecls_end();
9122 R != REnd; ++R) {
9123 TemplateSpecializationKind TSK
9124 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9125 if (TSK == TSK_ExplicitInstantiationDeclaration)
9126 IsExplicitInstantiationDeclaration = true;
9127 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9128 IsExplicitInstantiationDeclaration = false;
9129 break;
9130 }
9131 }
9132
9133 if (IsExplicitInstantiationDeclaration)
9134 continue;
9135 }
9136
9137 // Mark all of the virtual members of this class as referenced, so
9138 // that we can build a vtable. Then, tell the AST consumer that a
9139 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00009140 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009141 MarkVirtualMembersReferenced(Loc, Class);
9142 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9143 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9144
9145 // Optionally warn if we're emitting a weak vtable.
9146 if (Class->getLinkage() == ExternalLinkage &&
9147 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009148 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009149 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9150 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009151 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009152 VTableUses.clear();
9153
Douglas Gregor78844032011-04-22 22:25:37 +00009154 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009155}
Anders Carlssond6a637f2009-12-07 08:24:59 +00009156
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009157void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9158 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00009159 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9160 e = RD->method_end(); i != e; ++i) {
9161 CXXMethodDecl *MD = *i;
9162
9163 // C++ [basic.def.odr]p2:
9164 // [...] A virtual member function is used if it is not pure. [...]
9165 if (MD->isVirtual() && !MD->isPure())
9166 MarkDeclarationReferenced(Loc, MD);
9167 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009168
9169 // Only classes that have virtual bases need a VTT.
9170 if (RD->getNumVBases() == 0)
9171 return;
9172
9173 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9174 e = RD->bases_end(); i != e; ++i) {
9175 const CXXRecordDecl *Base =
9176 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009177 if (Base->getNumVBases() == 0)
9178 continue;
9179 MarkVirtualMembersReferenced(Loc, Base);
9180 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00009181}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009182
9183/// SetIvarInitializers - This routine builds initialization ASTs for the
9184/// Objective-C implementation whose ivars need be initialized.
9185void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9186 if (!getLangOptions().CPlusPlus)
9187 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00009188 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009189 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9190 CollectIvarsToConstructOrDestruct(OID, ivars);
9191 if (ivars.empty())
9192 return;
Sean Huntcbb67482011-01-08 20:30:50 +00009193 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009194 for (unsigned i = 0; i < ivars.size(); i++) {
9195 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009196 if (Field->isInvalidDecl())
9197 continue;
9198
Sean Huntcbb67482011-01-08 20:30:50 +00009199 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009200 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9201 InitializationKind InitKind =
9202 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9203
9204 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009205 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00009206 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00009207 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009208 // Note, MemberInit could actually come back empty if no initialization
9209 // is required (e.g., because it would call a trivial default constructor)
9210 if (!MemberInit.get() || MemberInit.isInvalid())
9211 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00009212
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009213 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00009214 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9215 SourceLocation(),
9216 MemberInit.takeAs<Expr>(),
9217 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009218 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009219
9220 // Be sure that the destructor is accessible and is marked as referenced.
9221 if (const RecordType *RecordTy
9222 = Context.getBaseElementType(Field->getType())
9223 ->getAs<RecordType>()) {
9224 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00009225 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009226 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9227 CheckDestructorAccess(Field->getLocation(), Destructor,
9228 PDiag(diag::err_access_dtor_ivar)
9229 << Context.getBaseElementType(Field->getType()));
9230 }
9231 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009232 }
9233 ObjCImplementation->setIvarInitializers(Context,
9234 AllToInit.data(), AllToInit.size());
9235 }
9236}
Sean Huntfe57eef2011-05-04 05:57:24 +00009237
Sean Huntebcbe1d2011-05-04 23:29:54 +00009238static
9239void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9240 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9241 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9242 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9243 Sema &S) {
9244 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9245 CE = Current.end();
9246 if (Ctor->isInvalidDecl())
9247 return;
9248
9249 const FunctionDecl *FNTarget = 0;
9250 CXXConstructorDecl *Target;
9251
9252 // We ignore the result here since if we don't have a body, Target will be
9253 // null below.
9254 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9255 Target
9256= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9257
9258 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9259 // Avoid dereferencing a null pointer here.
9260 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9261
9262 if (!Current.insert(Canonical))
9263 return;
9264
9265 // We know that beyond here, we aren't chaining into a cycle.
9266 if (!Target || !Target->isDelegatingConstructor() ||
9267 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9268 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9269 Valid.insert(*CI);
9270 Current.clear();
9271 // We've hit a cycle.
9272 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9273 Current.count(TCanonical)) {
9274 // If we haven't diagnosed this cycle yet, do so now.
9275 if (!Invalid.count(TCanonical)) {
9276 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00009277 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00009278 << Ctor;
9279
9280 // Don't add a note for a function delegating directo to itself.
9281 if (TCanonical != Canonical)
9282 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9283
9284 CXXConstructorDecl *C = Target;
9285 while (C->getCanonicalDecl() != Canonical) {
9286 (void)C->getTargetConstructor()->hasBody(FNTarget);
9287 assert(FNTarget && "Ctor cycle through bodiless function");
9288
9289 C
9290 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9291 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9292 }
9293 }
9294
9295 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9296 Invalid.insert(*CI);
9297 Current.clear();
9298 } else {
9299 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9300 }
9301}
9302
9303
Sean Huntfe57eef2011-05-04 05:57:24 +00009304void Sema::CheckDelegatingCtorCycles() {
9305 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9306
Sean Huntebcbe1d2011-05-04 23:29:54 +00009307 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9308 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00009309
9310 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00009311 I = DelegatingCtorDecls.begin(),
9312 E = DelegatingCtorDecls.end();
9313 I != E; ++I) {
9314 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00009315 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00009316
9317 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9318 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00009319}