blob: 571cbf2c2437949fc30108f0b745a8a39ce9a187 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000036#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000037#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner8123a952008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattner9e979552008-04-12 23:52:44 +000045namespace {
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 public:
Mike Stump1eb44332009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000063 };
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000071 }
72
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000078 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000098 }
Chris Lattner8123a952008-04-10 02:22:51 +000099
Douglas Gregor3996f232008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattner9e979552008-04-12 23:52:44 +0000102
Douglas Gregor796da182008-11-04 14:32:21 +0000103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
107 // member function.
108 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000111 }
Chris Lattner8123a952008-04-10 02:22:51 +0000112}
113
Sean Hunt001cad92011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000118 return;
119
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
122
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith7a614d82011-06-11 17:19:42 +0000132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
134
Sean Hunt001cad92011-05-10 00:49:42 +0000135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
137 return;
138
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
141 return;
142
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
148 return;
149 }
150
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
159
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
162 ClearExceptions();
163 ComputedEST = EST_None;
164 }
165 // noexcept(true) won't change anything either.
166 return;
167 }
168
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
176 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith7a614d82011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssoned961f92009-08-25 02:29:20 +0000210bool
John McCall9ae2f072010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
216 return true;
217 }
218
Anders Carlssoned961f92009-08-25 02:29:20 +0000219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000233 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000235
John McCallb4eb64d2010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Anders Carlssoned961f92009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
252 }
253
Anders Carlsson9351c172009-08-25 03:18:48 +0000254 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000255}
256
Chris Lattner8123a952008-04-10 02:22:51 +0000257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260void
John McCalld226f652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000264 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000265
John McCalld226f652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6f526752010-12-16 08:48:57 +0000277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
280 return;
281 }
282
Anders Carlsson66e30672009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump1eb44332009-09-09 15:08:12 +0000289
John McCall9ae2f072010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000291}
292
Douglas Gregor61366e92008-12-24 00:01:03 +0000293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
John McCalld226f652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000308}
309
Douglas Gregor72b505b2008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
John McCalld226f652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Anders Carlsson5e300d12009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000321}
322
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346 delete Toks;
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
364
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000377 //
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
386
Douglas Gregor6cc15182009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000388
Francois Pichet8d051e02011-04-10 03:03:52 +0000389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
391
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
394 Invalid = true;
395 if (getLangOptions().Microsoft) {
396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
403 else
404 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000409
Francois Pichet8cf90492011-04-10 04:58:30 +0000410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000420
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
426 break;
427
428 OldParam = Older->getParamDecl(p);
429 }
430
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCall3d6c1782010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
450 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
462 // instantiated.
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
472 //
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
476 // dependent type.
477 int WhichKind = 2;
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
481 WhichKind = 0;
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483 WhichKind = 1;
484 else
485 WhichKind = 2;
486 }
487
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
490 << WhichKind
491 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
499 << OldSM;
500 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000501 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregore13ad832010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000507
Douglas Gregorcda9c672009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000509}
510
Sebastian Redl60618fa2011-03-12 11:50:43 +0000511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
519 return;
520
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
523
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
526
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538 }
539
540 if (!NewType->isFunctionProtoType())
541 return;
542
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
545 // workarounds.
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
550 }
551}
552
Chris Lattner3d1cee32008-04-08 05:04:30 +0000553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
558 unsigned p;
559
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 break;
565 }
566
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000583 else
Mike Stump1eb44332009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner3d1cee32008-04-08 05:04:30 +0000587 LastMissingDefaultArg = p;
588 }
589 }
590
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604
Douglas Gregorb48fe382008-10-31 09:07:45 +0000605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617 } else
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
642 << SpecifierRange;
643 return 0;
644 }
645
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
651 }
652
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663 return 0;
664 }
665
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670 return 0;
671 }
672
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
675 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 return 0;
John McCall572fc622010-08-17 07:23:57 +0000681 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000682
Eli Friedman1d954f62009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000690
Anders Carlsson1d209272011-03-25 14:55:14 +0000691 // C++ [class]p3:
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +0000695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
699 return 0;
700 }
701
John McCall572fc622010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +0000709}
710
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000716BaseResult
John McCalld226f652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregor40808ce2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky56062202010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +0000731
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000736
Douglas Gregor2943aed2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2943aed2009-03-03 04:44:36 +0000742 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000743}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000744
Douglas Gregor2943aed2009-03-03 04:44:36 +0000745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748 unsigned NumBases) {
749 if (NumBases == 0)
750 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000751
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
John McCalld226f652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000809
John McCall3cb0ebd2010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregora8f32e02009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000827 return false;
828
John McCall3cb0ebd2010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000831 return false;
832
John McCall86ff3082010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCall3cb0ebd2010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000845 return false;
846
John McCall3cb0ebd2010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregora8f32e02009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000875}
876
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregora8f32e02009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000926 }
John McCall6b2accb2010-02-10 09:31:12 +0000927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnara6206d532010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +00001016}
1017
Anders Carlsson9e682d92011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlsson9e682d92011-01-20 05:57:14 +00001020 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlsson9e682d92011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlsson69a87352011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith7a614d82011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001077
John McCall4bde1e12010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith7a614d82011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall67d1a672009-08-06 02:15:43 +00001081
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();
John McCallb77115d2011-06-17 00:18:42 +00001975
1976 // Suppress copying zero-width bitfields.
1977 if (const Expr *Width = Field->getBitWidth())
1978 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1979 return false;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001980
1981 Expr *MemberExprBase =
Douglas Gregor40d96a62011-02-28 21:54:11 +00001982 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00001983 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001984
1985 // Build a reference to this field within the parameter.
1986 CXXScopeSpec SS;
1987 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1988 Sema::LookupMemberName);
1989 MemberLookup.addDecl(Field, AS_public);
1990 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001991 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001992 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001993 ParamType, Loc,
1994 /*IsArrow=*/false,
1995 SS,
1996 /*FirstQualifierInScope=*/0,
1997 MemberLookup,
1998 /*TemplateArgs=*/0);
1999 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002000 return true;
2001
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002002 // When the field we are copying is an array, create index variables for
2003 // each dimension of the array. We use these index variables to subscript
2004 // the source array, and other clients (e.g., CodeGen) will perform the
2005 // necessary iteration with these index variables.
2006 llvm::SmallVector<VarDecl *, 4> IndexVariables;
2007 QualType BaseType = Field->getType();
2008 QualType SizeType = SemaRef.Context.getSizeType();
2009 while (const ConstantArrayType *Array
2010 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2011 // Create the iteration variable for this array index.
2012 IdentifierInfo *IterationVarName = 0;
2013 {
2014 llvm::SmallString<8> Str;
2015 llvm::raw_svector_ostream OS(Str);
2016 OS << "__i" << IndexVariables.size();
2017 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2018 }
2019 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002020 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002021 IterationVarName, SizeType,
2022 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002023 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002024 IndexVariables.push_back(IterationVar);
2025
2026 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002027 ExprResult IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00002028 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002029 assert(!IterationVarRef.isInvalid() &&
2030 "Reference to invented variable cannot fail!");
2031
2032 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00002033 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002034 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002035 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002036 Loc);
2037 if (CopyCtorArg.isInvalid())
2038 return true;
2039
2040 BaseType = Array->getElementType();
2041 }
2042
2043 // Construct the entity that we will be initializing. For an array, this
2044 // will be first element in the array, which may require several levels
2045 // of array-subscript entities.
2046 llvm::SmallVector<InitializedEntity, 4> Entities;
2047 Entities.reserve(1 + IndexVariables.size());
2048 Entities.push_back(InitializedEntity::InitializeMember(Field));
2049 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2050 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2051 0,
2052 Entities.back()));
2053
2054 // Direct-initialize to use the copy constructor.
2055 InitializationKind InitKind =
2056 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2057
2058 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2059 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2060 &CopyCtorArgE, 1);
2061
John McCall60d7b3a2010-08-24 06:29:42 +00002062 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002063 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002064 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002065 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002066 if (MemberInit.isInvalid())
2067 return true;
2068
2069 CXXMemberInit
Sean Huntcbb67482011-01-08 20:30:50 +00002070 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002071 MemberInit.takeAs<Expr>(), Loc,
2072 IndexVariables.data(),
2073 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002074 return false;
2075 }
2076
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002077 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2078
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002079 QualType FieldBaseElementType =
2080 SemaRef.Context.getBaseElementType(Field->getType());
2081
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002082 if (FieldBaseElementType->isRecordType()) {
2083 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002084 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002085 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002086
2087 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002088 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002089 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002090
Douglas Gregor53c374f2010-12-07 00:41:46 +00002091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002092 if (MemberInit.isInvalid())
2093 return true;
2094
2095 CXXMemberInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002096 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00002097 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002098 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00002099 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002100 return false;
2101 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002102
Sean Hunt1f2f3842011-05-17 00:19:05 +00002103 if (!Field->getParent()->isUnion()) {
2104 if (FieldBaseElementType->isReferenceType()) {
2105 SemaRef.Diag(Constructor->getLocation(),
2106 diag::err_uninitialized_member_in_ctor)
2107 << (int)Constructor->isImplicit()
2108 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2109 << 0 << Field->getDeclName();
2110 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2111 return true;
2112 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002113
Sean Hunt1f2f3842011-05-17 00:19:05 +00002114 if (FieldBaseElementType.isConstQualified()) {
2115 SemaRef.Diag(Constructor->getLocation(),
2116 diag::err_uninitialized_member_in_ctor)
2117 << (int)Constructor->isImplicit()
2118 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2119 << 1 << Field->getDeclName();
2120 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2121 return true;
2122 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002123 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002124
John McCallf85e1932011-06-15 23:02:42 +00002125 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2126 FieldBaseElementType->isObjCRetainableType() &&
2127 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2128 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2129 // Instant objects:
2130 // Default-initialize Objective-C pointers to NULL.
2131 CXXMemberInit
2132 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2133 Loc, Loc,
2134 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2135 Loc);
2136 return false;
2137 }
2138
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002139 // Nothing to initialize.
2140 CXXMemberInit = 0;
2141 return false;
2142}
John McCallf1860e52010-05-20 23:23:51 +00002143
2144namespace {
2145struct BaseAndFieldInfo {
2146 Sema &S;
2147 CXXConstructorDecl *Ctor;
2148 bool AnyErrorsInInits;
2149 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002150 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2151 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002152
2153 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2154 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2155 // FIXME: Handle implicit move constructors.
2156 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2157 IIK = IIK_Copy;
2158 else
2159 IIK = IIK_Default;
2160 }
2161};
2162}
2163
Richard Smith7a614d82011-06-11 17:19:42 +00002164static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallf1860e52010-05-20 23:23:51 +00002165 FieldDecl *Top, FieldDecl *Field) {
2166
Chandler Carruthe861c602010-06-30 02:59:29 +00002167 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002168 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002169 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002170 return false;
2171 }
2172
Richard Smith7a614d82011-06-11 17:19:42 +00002173 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2174 // has a brace-or-equal-initializer, the entity is initialized as specified
2175 // in [dcl.init].
2176 if (Field->hasInClassInitializer()) {
2177 Info.AllToInit.push_back(
2178 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2179 SourceLocation(),
2180 SourceLocation(), 0,
2181 SourceLocation()));
2182 return false;
2183 }
2184
John McCallf1860e52010-05-20 23:23:51 +00002185 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2186 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2187 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00002188 CXXRecordDecl *FieldClassDecl
2189 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00002190
2191 // Even though union members never have non-trivial default
2192 // constructions in C++03, we still build member initializers for aggregate
2193 // record types which can be union members, and C++0x allows non-trivial
2194 // default constructors for union members, so we ensure that only one
2195 // member is initialized for these.
2196 if (FieldClassDecl->isUnion()) {
2197 // First check for an explicit initializer for one field.
2198 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2199 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002200 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002201 Info.AllToInit.push_back(Init);
Chandler Carruthe861c602010-06-30 02:59:29 +00002202
2203 // Once we've initialized a field of an anonymous union, the union
2204 // field in the class is also initialized, so exit immediately.
2205 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002206 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith7a614d82011-06-11 17:19:42 +00002207 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00002208 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00002209 }
2210 }
2211
2212 // Fallthrough and construct a default initializer for the union as
2213 // a whole, which can call its default constructor if such a thing exists
2214 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2215 // behavior going forward with C++0x, when anonymous unions there are
2216 // finalized, we should revisit this.
2217 } else {
2218 // For structs, we simply descend through to initialize all members where
2219 // necessary.
2220 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2221 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith7a614d82011-06-11 17:19:42 +00002222 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruthe861c602010-06-30 02:59:29 +00002223 return true;
2224 }
2225 }
John McCallf1860e52010-05-20 23:23:51 +00002226 }
2227
2228 // Don't try to build an implicit initializer if there were semantic
2229 // errors in any of the initializers (and therefore we might be
2230 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002231 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002232 return false;
2233
Sean Huntcbb67482011-01-08 20:30:50 +00002234 CXXCtorInitializer *Init = 0;
John McCallf1860e52010-05-20 23:23:51 +00002235 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2236 return true;
John McCallf1860e52010-05-20 23:23:51 +00002237
Francois Pichet00eb3f92010-12-04 09:14:42 +00002238 if (Init)
2239 Info.AllToInit.push_back(Init);
2240
John McCallf1860e52010-05-20 23:23:51 +00002241 return false;
2242}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002243
2244bool
2245Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2246 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002247 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002248 Constructor->setNumCtorInitializers(1);
2249 CXXCtorInitializer **initializer =
2250 new (Context) CXXCtorInitializer*[1];
2251 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2252 Constructor->setCtorInitializers(initializer);
2253
Sean Huntb76af9c2011-05-03 23:05:34 +00002254 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2255 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2256 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2257 }
2258
Sean Huntc1598702011-05-05 00:05:47 +00002259 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002260
Sean Hunt059ce0d2011-05-01 07:04:31 +00002261 return false;
2262}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002263
John McCallb77115d2011-06-17 00:18:42 +00002264bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2265 CXXCtorInitializer **Initializers,
2266 unsigned NumInitializers,
2267 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00002268 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002269 // Just store the initializers as written, they will be checked during
2270 // instantiation.
2271 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002272 Constructor->setNumCtorInitializers(NumInitializers);
2273 CXXCtorInitializer **baseOrMemberInitializers =
2274 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002275 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002276 NumInitializers * sizeof(CXXCtorInitializer*));
2277 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002278 }
2279
2280 return false;
2281 }
2282
John McCallf1860e52010-05-20 23:23:51 +00002283 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002284
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002285 // We need to build the initializer AST according to order of construction
2286 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002287 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002288 if (!ClassDecl)
2289 return true;
2290
Eli Friedman80c30da2009-11-09 19:20:36 +00002291 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002293 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002294 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002295
2296 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002297 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002298 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002299 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002300 }
2301
Anders Carlsson711f34a2010-04-21 19:52:01 +00002302 // Keep track of the direct virtual bases.
2303 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2304 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2305 E = ClassDecl->bases_end(); I != E; ++I) {
2306 if (I->isVirtual())
2307 DirectVBases.insert(I);
2308 }
2309
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002310 // Push virtual bases before others.
2311 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2312 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2313
Sean Huntcbb67482011-01-08 20:30:50 +00002314 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002315 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2316 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002317 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002318 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002319 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002320 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002321 VBase, IsInheritedVirtualBase,
2322 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002323 HadError = true;
2324 continue;
2325 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002326
John McCallf1860e52010-05-20 23:23:51 +00002327 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002328 }
2329 }
Mike Stump1eb44332009-09-09 15:08:12 +00002330
John McCallf1860e52010-05-20 23:23:51 +00002331 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002332 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2333 E = ClassDecl->bases_end(); Base != E; ++Base) {
2334 // Virtuals are in the virtual base list and already constructed.
2335 if (Base->isVirtual())
2336 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Sean Huntcbb67482011-01-08 20:30:50 +00002338 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002339 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2340 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002341 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002342 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002343 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002344 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002345 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002346 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002347 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002348 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002349
John McCallf1860e52010-05-20 23:23:51 +00002350 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002351 }
2352 }
Mike Stump1eb44332009-09-09 15:08:12 +00002353
John McCallf1860e52010-05-20 23:23:51 +00002354 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002355 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002356 E = ClassDecl->field_end(); Field != E; ++Field) {
2357 if ((*Field)->getType()->isIncompleteArrayType()) {
2358 assert(ClassDecl->hasFlexibleArrayMember() &&
2359 "Incomplete array type is not valid");
2360 continue;
2361 }
Richard Smith7a614d82011-06-11 17:19:42 +00002362 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002363 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
John McCallf1860e52010-05-20 23:23:51 +00002366 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002367 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002368 Constructor->setNumCtorInitializers(NumInitializers);
2369 CXXCtorInitializer **baseOrMemberInitializers =
2370 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002371 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002372 NumInitializers * sizeof(CXXCtorInitializer*));
2373 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002374
John McCallef027fe2010-03-16 21:39:52 +00002375 // Constructors implicitly reference the base and member
2376 // destructors.
2377 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2378 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002379 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002380
2381 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002382}
2383
Eli Friedman6347f422009-07-21 19:28:10 +00002384static void *GetKeyForTopLevelField(FieldDecl *Field) {
2385 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002386 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002387 if (RT->getDecl()->isAnonymousStructOrUnion())
2388 return static_cast<void *>(RT->getDecl());
2389 }
2390 return static_cast<void *>(Field);
2391}
2392
Anders Carlssonea356fb2010-04-02 05:42:15 +00002393static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002394 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002395}
2396
Anders Carlssonea356fb2010-04-02 05:42:15 +00002397static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002398 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002399 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002400 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002401
Eli Friedman6347f422009-07-21 19:28:10 +00002402 // For fields injected into the class via declaration of an anonymous union,
2403 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002404 FieldDecl *Field = Member->getAnyMember();
2405
John McCall3c3ccdb2010-04-10 09:28:51 +00002406 // If the field is a member of an anonymous struct or union, our key
2407 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002408 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002409 if (RD->isAnonymousStructOrUnion()) {
2410 while (true) {
2411 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2412 if (Parent->isAnonymousStructOrUnion())
2413 RD = Parent;
2414 else
2415 break;
2416 }
2417
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002418 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002419 }
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002421 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002422}
2423
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002424static void
2425DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002426 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00002427 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00002428 unsigned NumInits) {
2429 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002430 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002432 // Don't check initializers order unless the warning is enabled at the
2433 // location of at least one initializer.
2434 bool ShouldCheckOrder = false;
2435 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002436 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002437 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2438 Init->getSourceLocation())
2439 != Diagnostic::Ignored) {
2440 ShouldCheckOrder = true;
2441 break;
2442 }
2443 }
2444 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002445 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002446
John McCalld6ca8da2010-04-10 07:37:23 +00002447 // Build the list of bases and members in the order that they'll
2448 // actually be initialized. The explicit initializers should be in
2449 // this same order but may be missing things.
2450 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Anders Carlsson071d6102010-04-02 03:38:04 +00002452 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2453
John McCalld6ca8da2010-04-10 07:37:23 +00002454 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002455 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002456 ClassDecl->vbases_begin(),
2457 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002458 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002459
John McCalld6ca8da2010-04-10 07:37:23 +00002460 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002461 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002462 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002463 if (Base->isVirtual())
2464 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002465 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002466 }
Mike Stump1eb44332009-09-09 15:08:12 +00002467
John McCalld6ca8da2010-04-10 07:37:23 +00002468 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002469 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2470 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002471 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002472
John McCalld6ca8da2010-04-10 07:37:23 +00002473 unsigned NumIdealInits = IdealInitKeys.size();
2474 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002475
Sean Huntcbb67482011-01-08 20:30:50 +00002476 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00002477 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00002478 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00002479 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00002480
2481 // Scan forward to try to find this initializer in the idealized
2482 // initializers list.
2483 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2484 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002485 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002486
2487 // If we didn't find this initializer, it must be because we
2488 // scanned past it on a previous iteration. That can only
2489 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002490 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002491 Sema::SemaDiagnosticBuilder D =
2492 SemaRef.Diag(PrevInit->getSourceLocation(),
2493 diag::warn_initializer_out_of_order);
2494
Francois Pichet00eb3f92010-12-04 09:14:42 +00002495 if (PrevInit->isAnyMemberInitializer())
2496 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002497 else
2498 D << 1 << PrevInit->getBaseClassInfo()->getType();
2499
Francois Pichet00eb3f92010-12-04 09:14:42 +00002500 if (Init->isAnyMemberInitializer())
2501 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00002502 else
2503 D << 1 << Init->getBaseClassInfo()->getType();
2504
2505 // Move back to the initializer's location in the ideal list.
2506 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2507 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002508 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002509
2510 assert(IdealIndex != NumIdealInits &&
2511 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002512 }
John McCalld6ca8da2010-04-10 07:37:23 +00002513
2514 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002515 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002516}
2517
John McCall3c3ccdb2010-04-10 09:28:51 +00002518namespace {
2519bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002520 CXXCtorInitializer *Init,
2521 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002522 if (!PrevInit) {
2523 PrevInit = Init;
2524 return false;
2525 }
2526
2527 if (FieldDecl *Field = Init->getMember())
2528 S.Diag(Init->getSourceLocation(),
2529 diag::err_multiple_mem_initialization)
2530 << Field->getDeclName()
2531 << Init->getSourceRange();
2532 else {
John McCallf4c73712011-01-19 06:33:43 +00002533 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00002534 assert(BaseClass && "neither field nor base");
2535 S.Diag(Init->getSourceLocation(),
2536 diag::err_multiple_base_initialization)
2537 << QualType(BaseClass, 0)
2538 << Init->getSourceRange();
2539 }
2540 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2541 << 0 << PrevInit->getSourceRange();
2542
2543 return true;
2544}
2545
Sean Huntcbb67482011-01-08 20:30:50 +00002546typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00002547typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2548
2549bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00002550 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00002551 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002552 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002553 RecordDecl *Parent = Field->getParent();
2554 if (!Parent->isAnonymousStructOrUnion())
2555 return false;
2556
2557 NamedDecl *Child = Field;
2558 do {
2559 if (Parent->isUnion()) {
2560 UnionEntry &En = Unions[Parent];
2561 if (En.first && En.first != Child) {
2562 S.Diag(Init->getSourceLocation(),
2563 diag::err_multiple_mem_union_initialization)
2564 << Field->getDeclName()
2565 << Init->getSourceRange();
2566 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2567 << 0 << En.second->getSourceRange();
2568 return true;
2569 } else if (!En.first) {
2570 En.first = Child;
2571 En.second = Init;
2572 }
2573 }
2574
2575 Child = Parent;
2576 Parent = cast<RecordDecl>(Parent->getDeclContext());
2577 } while (Parent->isAnonymousStructOrUnion());
2578
2579 return false;
2580}
2581}
2582
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002583/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002584void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002585 SourceLocation ColonLoc,
2586 MemInitTy **meminits, unsigned NumMemInits,
2587 bool AnyErrors) {
2588 if (!ConstructorDecl)
2589 return;
2590
2591 AdjustDeclIfTemplate(ConstructorDecl);
2592
2593 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002594 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002595
2596 if (!Constructor) {
2597 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2598 return;
2599 }
2600
Sean Huntcbb67482011-01-08 20:30:50 +00002601 CXXCtorInitializer **MemInits =
2602 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002603
2604 // Mapping for the duplicate initializers check.
2605 // For member initializers, this is keyed with a FieldDecl*.
2606 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00002607 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002608
2609 // Mapping for the inconsistent anonymous-union initializers check.
2610 RedundantUnionMap MemberUnions;
2611
Anders Carlssonea356fb2010-04-02 05:42:15 +00002612 bool HadError = false;
2613 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002614 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002615
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002616 // Set the source order index.
2617 Init->setSourceOrder(i);
2618
Francois Pichet00eb3f92010-12-04 09:14:42 +00002619 if (Init->isAnyMemberInitializer()) {
2620 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00002621 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2622 CheckRedundantUnionInit(*this, Init, MemberUnions))
2623 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002624 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002625 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2626 if (CheckRedundantInit(*this, Init, Members[Key]))
2627 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00002628 } else {
2629 assert(Init->isDelegatingInitializer());
2630 // This must be the only initializer
2631 if (i != 0 || NumMemInits > 1) {
2632 Diag(MemInits[0]->getSourceLocation(),
2633 diag::err_delegating_initializer_alone)
2634 << MemInits[0]->getSourceRange();
2635 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00002636 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00002637 }
Sean Huntfe57eef2011-05-04 05:57:24 +00002638 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00002639 // Return immediately as the initializer is set.
2640 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002641 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002642 }
2643
Anders Carlssonea356fb2010-04-02 05:42:15 +00002644 if (HadError)
2645 return;
2646
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002647 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002648
Sean Huntcbb67482011-01-08 20:30:50 +00002649 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002650}
2651
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002652void
John McCallef027fe2010-03-16 21:39:52 +00002653Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2654 CXXRecordDecl *ClassDecl) {
2655 // Ignore dependent contexts.
2656 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002657 return;
John McCall58e6f342010-03-16 05:22:47 +00002658
2659 // FIXME: all the access-control diagnostics are positioned on the
2660 // field/base declaration. That's probably good; that said, the
2661 // user might reasonably want to know why the destructor is being
2662 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002663
Anders Carlsson9f853df2009-11-17 04:44:12 +00002664 // Non-static data members.
2665 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2666 E = ClassDecl->field_end(); I != E; ++I) {
2667 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002668 if (Field->isInvalidDecl())
2669 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002670 QualType FieldType = Context.getBaseElementType(Field->getType());
2671
2672 const RecordType* RT = FieldType->getAs<RecordType>();
2673 if (!RT)
2674 continue;
2675
2676 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002677 if (FieldClassDecl->isInvalidDecl())
2678 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002679 if (FieldClassDecl->hasTrivialDestructor())
2680 continue;
2681
Douglas Gregordb89f282010-07-01 22:47:18 +00002682 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002683 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002684 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002685 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002686 << Field->getDeclName()
2687 << FieldType);
2688
John McCallef027fe2010-03-16 21:39:52 +00002689 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002690 }
2691
John McCall58e6f342010-03-16 05:22:47 +00002692 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2693
Anders Carlsson9f853df2009-11-17 04:44:12 +00002694 // Bases.
2695 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2696 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002697 // Bases are always records in a well-formed non-dependent class.
2698 const RecordType *RT = Base->getType()->getAs<RecordType>();
2699
2700 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002701 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002702 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002703
John McCall58e6f342010-03-16 05:22:47 +00002704 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002705 // If our base class is invalid, we probably can't get its dtor anyway.
2706 if (BaseClassDecl->isInvalidDecl())
2707 continue;
2708 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002709 if (BaseClassDecl->hasTrivialDestructor())
2710 continue;
John McCall58e6f342010-03-16 05:22:47 +00002711
Douglas Gregordb89f282010-07-01 22:47:18 +00002712 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002713 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002714
2715 // FIXME: caret should be on the start of the class name
2716 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002717 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002718 << Base->getType()
2719 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002720
John McCallef027fe2010-03-16 21:39:52 +00002721 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002722 }
2723
2724 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002725 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2726 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002727
2728 // Bases are always records in a well-formed non-dependent class.
2729 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2730
2731 // Ignore direct virtual bases.
2732 if (DirectVirtualBases.count(RT))
2733 continue;
2734
John McCall58e6f342010-03-16 05:22:47 +00002735 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002736 // If our base class is invalid, we probably can't get its dtor anyway.
2737 if (BaseClassDecl->isInvalidDecl())
2738 continue;
2739 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002740 if (BaseClassDecl->hasTrivialDestructor())
2741 continue;
John McCall58e6f342010-03-16 05:22:47 +00002742
Douglas Gregordb89f282010-07-01 22:47:18 +00002743 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00002744 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00002745 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002746 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002747 << VBase->getType());
2748
John McCallef027fe2010-03-16 21:39:52 +00002749 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002750 }
2751}
2752
John McCalld226f652010-08-21 09:40:31 +00002753void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002754 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002755 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Mike Stump1eb44332009-09-09 15:08:12 +00002757 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002758 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00002759 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002760}
2761
Mike Stump1eb44332009-09-09 15:08:12 +00002762bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002763 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002764 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002765 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002766 else
John McCall94c3b562010-08-18 09:41:07 +00002767 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002768}
2769
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002770bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002771 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002772 if (!getLangOptions().CPlusPlus)
2773 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Anders Carlsson11f21a02009-03-23 19:10:31 +00002775 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002776 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Ted Kremenek6217b802009-07-29 21:53:49 +00002778 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002779 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002780 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002781 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002783 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002784 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002785 }
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Ted Kremenek6217b802009-07-29 21:53:49 +00002787 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002788 if (!RT)
2789 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002790
John McCall86ff3082010-02-04 22:26:26 +00002791 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002792
John McCall94c3b562010-08-18 09:41:07 +00002793 // We can't answer whether something is abstract until it has a
2794 // definition. If it's currently being defined, we'll walk back
2795 // over all the declarations when we have a full definition.
2796 const CXXRecordDecl *Def = RD->getDefinition();
2797 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002798 return false;
2799
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002800 if (!RD->isAbstract())
2801 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002803 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002804 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002805
John McCall94c3b562010-08-18 09:41:07 +00002806 return true;
2807}
2808
2809void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2810 // Check if we've already emitted the list of pure virtual functions
2811 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002812 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002813 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002815 CXXFinalOverriderMap FinalOverriders;
2816 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002818 // Keep a set of seen pure methods so we won't diagnose the same method
2819 // more than once.
2820 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2821
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002822 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2823 MEnd = FinalOverriders.end();
2824 M != MEnd;
2825 ++M) {
2826 for (OverridingMethods::iterator SO = M->second.begin(),
2827 SOEnd = M->second.end();
2828 SO != SOEnd; ++SO) {
2829 // C++ [class.abstract]p4:
2830 // A class is abstract if it contains or inherits at least one
2831 // pure virtual function for which the final overrider is pure
2832 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002834 //
2835 if (SO->second.size() != 1)
2836 continue;
2837
2838 if (!SO->second.front().Method->isPure())
2839 continue;
2840
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002841 if (!SeenPureMethods.insert(SO->second.front().Method))
2842 continue;
2843
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002844 Diag(SO->second.front().Method->getLocation(),
2845 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00002846 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002847 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002848 }
2849
2850 if (!PureVirtualClassDiagSet)
2851 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2852 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002853}
2854
Anders Carlsson8211eff2009-03-24 01:19:16 +00002855namespace {
John McCall94c3b562010-08-18 09:41:07 +00002856struct AbstractUsageInfo {
2857 Sema &S;
2858 CXXRecordDecl *Record;
2859 CanQualType AbstractType;
2860 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002861
John McCall94c3b562010-08-18 09:41:07 +00002862 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2863 : S(S), Record(Record),
2864 AbstractType(S.Context.getCanonicalType(
2865 S.Context.getTypeDeclType(Record))),
2866 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002867
John McCall94c3b562010-08-18 09:41:07 +00002868 void DiagnoseAbstractType() {
2869 if (Invalid) return;
2870 S.DiagnoseAbstractType(Record);
2871 Invalid = true;
2872 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002873
John McCall94c3b562010-08-18 09:41:07 +00002874 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2875};
2876
2877struct CheckAbstractUsage {
2878 AbstractUsageInfo &Info;
2879 const NamedDecl *Ctx;
2880
2881 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2882 : Info(Info), Ctx(Ctx) {}
2883
2884 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2885 switch (TL.getTypeLocClass()) {
2886#define ABSTRACT_TYPELOC(CLASS, PARENT)
2887#define TYPELOC(CLASS, PARENT) \
2888 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2889#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002890 }
John McCall94c3b562010-08-18 09:41:07 +00002891 }
Mike Stump1eb44332009-09-09 15:08:12 +00002892
John McCall94c3b562010-08-18 09:41:07 +00002893 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2894 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2895 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00002896 if (!TL.getArg(I))
2897 continue;
2898
John McCall94c3b562010-08-18 09:41:07 +00002899 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2900 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002901 }
John McCall94c3b562010-08-18 09:41:07 +00002902 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002903
John McCall94c3b562010-08-18 09:41:07 +00002904 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2905 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2906 }
Mike Stump1eb44332009-09-09 15:08:12 +00002907
John McCall94c3b562010-08-18 09:41:07 +00002908 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2909 // Visit the type parameters from a permissive context.
2910 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2911 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2912 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2913 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2914 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2915 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002916 }
John McCall94c3b562010-08-18 09:41:07 +00002917 }
Mike Stump1eb44332009-09-09 15:08:12 +00002918
John McCall94c3b562010-08-18 09:41:07 +00002919 // Visit pointee types from a permissive context.
2920#define CheckPolymorphic(Type) \
2921 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2922 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2923 }
2924 CheckPolymorphic(PointerTypeLoc)
2925 CheckPolymorphic(ReferenceTypeLoc)
2926 CheckPolymorphic(MemberPointerTypeLoc)
2927 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002928
John McCall94c3b562010-08-18 09:41:07 +00002929 /// Handle all the types we haven't given a more specific
2930 /// implementation for above.
2931 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2932 // Every other kind of type that we haven't called out already
2933 // that has an inner type is either (1) sugar or (2) contains that
2934 // inner type in some way as a subobject.
2935 if (TypeLoc Next = TL.getNextTypeLoc())
2936 return Visit(Next, Sel);
2937
2938 // If there's no inner type and we're in a permissive context,
2939 // don't diagnose.
2940 if (Sel == Sema::AbstractNone) return;
2941
2942 // Check whether the type matches the abstract type.
2943 QualType T = TL.getType();
2944 if (T->isArrayType()) {
2945 Sel = Sema::AbstractArrayType;
2946 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002947 }
John McCall94c3b562010-08-18 09:41:07 +00002948 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2949 if (CT != Info.AbstractType) return;
2950
2951 // It matched; do some magic.
2952 if (Sel == Sema::AbstractArrayType) {
2953 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2954 << T << TL.getSourceRange();
2955 } else {
2956 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2957 << Sel << T << TL.getSourceRange();
2958 }
2959 Info.DiagnoseAbstractType();
2960 }
2961};
2962
2963void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2964 Sema::AbstractDiagSelID Sel) {
2965 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2966}
2967
2968}
2969
2970/// Check for invalid uses of an abstract type in a method declaration.
2971static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2972 CXXMethodDecl *MD) {
2973 // No need to do the check on definitions, which require that
2974 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00002975 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00002976 return;
2977
2978 // For safety's sake, just ignore it if we don't have type source
2979 // information. This should never happen for non-implicit methods,
2980 // but...
2981 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2982 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2983}
2984
2985/// Check for invalid uses of an abstract type within a class definition.
2986static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2987 CXXRecordDecl *RD) {
2988 for (CXXRecordDecl::decl_iterator
2989 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2990 Decl *D = *I;
2991 if (D->isImplicit()) continue;
2992
2993 // Methods and method templates.
2994 if (isa<CXXMethodDecl>(D)) {
2995 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2996 } else if (isa<FunctionTemplateDecl>(D)) {
2997 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2998 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2999
3000 // Fields and static variables.
3001 } else if (isa<FieldDecl>(D)) {
3002 FieldDecl *FD = cast<FieldDecl>(D);
3003 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3004 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3005 } else if (isa<VarDecl>(D)) {
3006 VarDecl *VD = cast<VarDecl>(D);
3007 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3008 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3009
3010 // Nested classes and class templates.
3011 } else if (isa<CXXRecordDecl>(D)) {
3012 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3013 } else if (isa<ClassTemplateDecl>(D)) {
3014 CheckAbstractClassUsage(Info,
3015 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3016 }
3017 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003018}
3019
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003020/// \brief Perform semantic checks on a class definition that has been
3021/// completing, introducing implicitly-declared members, checking for
3022/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003023void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003024 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003025 return;
3026
John McCall94c3b562010-08-18 09:41:07 +00003027 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3028 AbstractUsageInfo Info(*this, Record);
3029 CheckAbstractClassUsage(Info, Record);
3030 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003031
3032 // If this is not an aggregate type and has no user-declared constructor,
3033 // complain about any non-static data members of reference or const scalar
3034 // type, since they will never get initializers.
3035 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3036 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3037 bool Complained = false;
3038 for (RecordDecl::field_iterator F = Record->field_begin(),
3039 FEnd = Record->field_end();
3040 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00003041 if (F->hasInClassInitializer())
3042 continue;
3043
Douglas Gregor325e5932010-04-15 00:00:53 +00003044 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003045 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003046 if (!Complained) {
3047 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3048 << Record->getTagKind() << Record;
3049 Complained = true;
3050 }
3051
3052 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3053 << F->getType()->isReferenceType()
3054 << F->getDeclName();
3055 }
3056 }
3057 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003058
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003059 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003060 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003061
3062 if (Record->getIdentifier()) {
3063 // C++ [class.mem]p13:
3064 // If T is the name of a class, then each of the following shall have a
3065 // name different from T:
3066 // - every member of every anonymous union that is a member of class T.
3067 //
3068 // C++ [class.mem]p14:
3069 // In addition, if class T has a user-declared constructor (12.1), every
3070 // non-static data member of class T shall have a name different from T.
3071 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003072 R.first != R.second; ++R.first) {
3073 NamedDecl *D = *R.first;
3074 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3075 isa<IndirectFieldDecl>(D)) {
3076 Diag(D->getLocation(), diag::err_member_name_of_class)
3077 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003078 break;
3079 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003080 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003081 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003082
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003083 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003084 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003085 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003086 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003087 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3088 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3089 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003090
3091 // See if a method overloads virtual methods in a base
3092 /// class without overriding any.
3093 if (!Record->isDependentType()) {
3094 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3095 MEnd = Record->method_end();
3096 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003097 if (!(*M)->isStatic())
3098 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003099 }
3100 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003101
3102 // Declare inherited constructors. We do this eagerly here because:
3103 // - The standard requires an eager diagnostic for conflicting inherited
3104 // constructors from different classes.
3105 // - The lazy declaration of the other implicit constructors is so as to not
3106 // waste space and performance on classes that are not meant to be
3107 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3108 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003109 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003110
Sean Hunteb88ae52011-05-23 21:07:59 +00003111 if (!Record->isDependentType())
3112 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003113}
3114
3115void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003116 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3117 ME = Record->method_end();
3118 MI != ME; ++MI) {
3119 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3120 switch (getSpecialMember(*MI)) {
3121 case CXXDefaultConstructor:
3122 CheckExplicitlyDefaultedDefaultConstructor(
3123 cast<CXXConstructorDecl>(*MI));
3124 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003125
Sean Huntcb45a0f2011-05-12 22:46:25 +00003126 case CXXDestructor:
3127 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3128 break;
3129
3130 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003131 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3132 break;
3133
Sean Huntcb45a0f2011-05-12 22:46:25 +00003134 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003135 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003136 break;
3137
Sean Hunt82713172011-05-25 23:16:36 +00003138 case CXXMoveConstructor:
3139 case CXXMoveAssignment:
3140 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3141 break;
3142
Sean Huntcb45a0f2011-05-12 22:46:25 +00003143 default:
Sean Hunt2b188082011-05-14 05:23:28 +00003144 // FIXME: Do moves once they exist
Sean Huntcb45a0f2011-05-12 22:46:25 +00003145 llvm_unreachable("non-special member explicitly defaulted!");
3146 }
Sean Hunt001cad92011-05-10 00:49:42 +00003147 }
3148 }
3149
Sean Hunt001cad92011-05-10 00:49:42 +00003150}
3151
3152void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3153 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3154
3155 // Whether this was the first-declared instance of the constructor.
3156 // This affects whether we implicitly add an exception spec (and, eventually,
3157 // constexpr). It is also ill-formed to explicitly default a constructor such
3158 // that it would be deleted. (C++0x [decl.fct.def.default])
3159 bool First = CD == CD->getCanonicalDecl();
3160
Sean Hunt49634cf2011-05-13 06:10:58 +00003161 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003162 if (CD->getNumParams() != 0) {
3163 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3164 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003165 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003166 }
3167
3168 ImplicitExceptionSpecification Spec
3169 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3170 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003171 if (EPI.ExceptionSpecType == EST_Delayed) {
3172 // Exception specification depends on some deferred part of the class. We'll
3173 // try again when the class's definition has been fully processed.
3174 return;
3175 }
Sean Hunt001cad92011-05-10 00:49:42 +00003176 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3177 *ExceptionType = Context.getFunctionType(
3178 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3179
3180 if (CtorType->hasExceptionSpec()) {
3181 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003182 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003183 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003184 PDiag(),
3185 ExceptionType, SourceLocation(),
3186 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003187 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003188 }
3189 } else if (First) {
3190 // We set the declaration to have the computed exception spec here.
3191 // We know there are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003192 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003193 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3194 }
Sean Huntca46d132011-05-12 03:51:48 +00003195
Sean Hunt49634cf2011-05-13 06:10:58 +00003196 if (HadError) {
3197 CD->setInvalidDecl();
3198 return;
3199 }
3200
Sean Huntca46d132011-05-12 03:51:48 +00003201 if (ShouldDeleteDefaultConstructor(CD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003202 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003203 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003204 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003205 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003206 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003207 CD->setInvalidDecl();
3208 }
3209 }
3210}
3211
3212void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3213 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3214
3215 // Whether this was the first-declared instance of the constructor.
3216 bool First = CD == CD->getCanonicalDecl();
3217
3218 bool HadError = false;
3219 if (CD->getNumParams() != 1) {
3220 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3221 << CD->getSourceRange();
3222 HadError = true;
3223 }
3224
3225 ImplicitExceptionSpecification Spec(Context);
3226 bool Const;
3227 llvm::tie(Spec, Const) =
3228 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3229
3230 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3231 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3232 *ExceptionType = Context.getFunctionType(
3233 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3234
3235 // Check for parameter type matching.
3236 // This is a copy ctor so we know it's a cv-qualified reference to T.
3237 QualType ArgType = CtorType->getArgType(0);
3238 if (ArgType->getPointeeType().isVolatileQualified()) {
3239 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3240 HadError = true;
3241 }
3242 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3243 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3244 HadError = true;
3245 }
3246
3247 if (CtorType->hasExceptionSpec()) {
3248 if (CheckEquivalentExceptionSpec(
3249 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003250 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003251 PDiag(),
3252 ExceptionType, SourceLocation(),
3253 CtorType, CD->getLocation())) {
3254 HadError = true;
3255 }
3256 } else if (First) {
3257 // We set the declaration to have the computed exception spec here.
3258 // We duplicate the one parameter type.
Sean Hunt2b188082011-05-14 05:23:28 +00003259 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt49634cf2011-05-13 06:10:58 +00003260 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3261 }
3262
3263 if (HadError) {
3264 CD->setInvalidDecl();
3265 return;
3266 }
3267
3268 if (ShouldDeleteCopyConstructor(CD)) {
3269 if (First) {
3270 CD->setDeletedAsWritten();
3271 } else {
3272 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003273 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003274 CD->setInvalidDecl();
3275 }
Sean Huntca46d132011-05-12 03:51:48 +00003276 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003277}
Sean Hunt001cad92011-05-10 00:49:42 +00003278
Sean Hunt2b188082011-05-14 05:23:28 +00003279void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3280 assert(MD->isExplicitlyDefaulted());
3281
3282 // Whether this was the first-declared instance of the operator
3283 bool First = MD == MD->getCanonicalDecl();
3284
3285 bool HadError = false;
3286 if (MD->getNumParams() != 1) {
3287 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3288 << MD->getSourceRange();
3289 HadError = true;
3290 }
3291
3292 QualType ReturnType =
3293 MD->getType()->getAs<FunctionType>()->getResultType();
3294 if (!ReturnType->isLValueReferenceType() ||
3295 !Context.hasSameType(
3296 Context.getCanonicalType(ReturnType->getPointeeType()),
3297 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3298 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3299 HadError = true;
3300 }
3301
3302 ImplicitExceptionSpecification Spec(Context);
3303 bool Const;
3304 llvm::tie(Spec, Const) =
3305 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3306
3307 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3308 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3309 *ExceptionType = Context.getFunctionType(
3310 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3311
Sean Hunt2b188082011-05-14 05:23:28 +00003312 QualType ArgType = OperType->getArgType(0);
Sean Huntbe631222011-05-17 20:44:43 +00003313 if (!ArgType->isReferenceType()) {
3314 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00003315 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00003316 } else {
3317 if (ArgType->getPointeeType().isVolatileQualified()) {
3318 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3319 HadError = true;
3320 }
3321 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3322 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3323 HadError = true;
3324 }
Sean Hunt2b188082011-05-14 05:23:28 +00003325 }
Sean Huntbe631222011-05-17 20:44:43 +00003326
Sean Hunt2b188082011-05-14 05:23:28 +00003327 if (OperType->getTypeQuals()) {
3328 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3329 HadError = true;
3330 }
3331
3332 if (OperType->hasExceptionSpec()) {
3333 if (CheckEquivalentExceptionSpec(
3334 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003335 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00003336 PDiag(),
3337 ExceptionType, SourceLocation(),
3338 OperType, MD->getLocation())) {
3339 HadError = true;
3340 }
3341 } else if (First) {
3342 // We set the declaration to have the computed exception spec here.
3343 // We duplicate the one parameter type.
3344 EPI.RefQualifier = OperType->getRefQualifier();
3345 EPI.ExtInfo = OperType->getExtInfo();
3346 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3347 }
3348
3349 if (HadError) {
3350 MD->setInvalidDecl();
3351 return;
3352 }
3353
3354 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3355 if (First) {
3356 MD->setDeletedAsWritten();
3357 } else {
3358 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003359 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00003360 MD->setInvalidDecl();
3361 }
3362 }
3363}
3364
Sean Huntcb45a0f2011-05-12 22:46:25 +00003365void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3366 assert(DD->isExplicitlyDefaulted());
3367
3368 // Whether this was the first-declared instance of the destructor.
3369 bool First = DD == DD->getCanonicalDecl();
3370
3371 ImplicitExceptionSpecification Spec
3372 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3373 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3374 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3375 *ExceptionType = Context.getFunctionType(
3376 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3377
3378 if (DtorType->hasExceptionSpec()) {
3379 if (CheckEquivalentExceptionSpec(
3380 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003381 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00003382 PDiag(),
3383 ExceptionType, SourceLocation(),
3384 DtorType, DD->getLocation())) {
3385 DD->setInvalidDecl();
3386 return;
3387 }
3388 } else if (First) {
3389 // We set the declaration to have the computed exception spec here.
3390 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00003391 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00003392 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3393 }
3394
3395 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003396 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003397 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003398 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003399 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003400 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003401 DD->setInvalidDecl();
3402 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003403 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00003404}
3405
Sean Huntcdee3fe2011-05-11 22:34:38 +00003406bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3407 CXXRecordDecl *RD = CD->getParent();
3408 assert(!RD->isDependentType() && "do deletion after instantiation");
3409 if (!LangOpts.CPlusPlus0x)
3410 return false;
3411
Sean Hunt71a682f2011-05-18 03:41:58 +00003412 SourceLocation Loc = CD->getLocation();
3413
Sean Huntcdee3fe2011-05-11 22:34:38 +00003414 // Do access control from the constructor
3415 ContextRAII CtorContext(*this, CD);
3416
3417 bool Union = RD->isUnion();
3418 bool AllConst = true;
3419
Sean Huntcdee3fe2011-05-11 22:34:38 +00003420 // We do this because we should never actually use an anonymous
3421 // union's constructor.
3422 if (Union && RD->isAnonymousStructOrUnion())
3423 return false;
3424
3425 // FIXME: We should put some diagnostic logic right into this function.
3426
3427 // C++0x [class.ctor]/5
Sean Huntb320e0c2011-06-10 03:50:41 +00003428 // A defaulted default constructor for class X is defined as deleted if:
Sean Huntcdee3fe2011-05-11 22:34:38 +00003429
3430 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3431 BE = RD->bases_end();
3432 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003433 // We'll handle this one later
3434 if (BI->isVirtual())
3435 continue;
3436
Sean Huntcdee3fe2011-05-11 22:34:38 +00003437 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3438 assert(BaseDecl && "base isn't a CXXRecordDecl");
3439
3440 // -- any [direct base class] has a type with a destructor that is
Sean Huntb320e0c2011-06-10 03:50:41 +00003441 // deleted or inaccessible from the defaulted default constructor
Sean Huntcdee3fe2011-05-11 22:34:38 +00003442 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3443 if (BaseDtor->isDeleted())
3444 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003445 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003446 AR_accessible)
3447 return true;
3448
Sean Huntcdee3fe2011-05-11 22:34:38 +00003449 // -- any [direct base class either] has no default constructor or
3450 // overload resolution as applied to [its] default constructor
3451 // results in an ambiguity or in a function that is deleted or
3452 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003453 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3454 if (!BaseDefault || BaseDefault->isDeleted())
3455 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003456
Sean Huntb320e0c2011-06-10 03:50:41 +00003457 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3458 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003459 return true;
3460 }
3461
3462 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3463 BE = RD->vbases_end();
3464 BI != BE; ++BI) {
3465 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3466 assert(BaseDecl && "base isn't a CXXRecordDecl");
3467
3468 // -- any [virtual base class] has a type with a destructor that is
3469 // delete or inaccessible from the defaulted default constructor
3470 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3471 if (BaseDtor->isDeleted())
3472 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003473 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003474 AR_accessible)
3475 return true;
3476
3477 // -- any [virtual base class either] has no default constructor or
3478 // overload resolution as applied to [its] default constructor
3479 // results in an ambiguity or in a function that is deleted or
3480 // inaccessible from the defaulted default constructor
Sean Huntb320e0c2011-06-10 03:50:41 +00003481 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3482 if (!BaseDefault || BaseDefault->isDeleted())
3483 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003484
Sean Huntb320e0c2011-06-10 03:50:41 +00003485 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3486 PDiag()) != AR_accessible)
Sean Huntcdee3fe2011-05-11 22:34:38 +00003487 return true;
3488 }
3489
3490 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3491 FE = RD->field_end();
3492 FI != FE; ++FI) {
Richard Smith7a614d82011-06-11 17:19:42 +00003493 if (FI->isInvalidDecl())
3494 continue;
3495
Sean Huntcdee3fe2011-05-11 22:34:38 +00003496 QualType FieldType = Context.getBaseElementType(FI->getType());
3497 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00003498
Sean Huntcdee3fe2011-05-11 22:34:38 +00003499 // -- any non-static data member with no brace-or-equal-initializer is of
3500 // reference type
Richard Smith7a614d82011-06-11 17:19:42 +00003501 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Sean Huntcdee3fe2011-05-11 22:34:38 +00003502 return true;
3503
3504 // -- X is a union and all its variant members are of const-qualified type
3505 // (or array thereof)
3506 if (Union && !FieldType.isConstQualified())
3507 AllConst = false;
3508
3509 if (FieldRecord) {
3510 // -- X is a union-like class that has a variant member with a non-trivial
3511 // default constructor
3512 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3513 return true;
3514
3515 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3516 if (FieldDtor->isDeleted())
3517 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003518 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcdee3fe2011-05-11 22:34:38 +00003519 AR_accessible)
3520 return true;
3521
3522 // -- any non-variant non-static data member of const-qualified type (or
3523 // array thereof) with no brace-or-equal-initializer does not have a
3524 // user-provided default constructor
3525 if (FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00003526 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00003527 !FieldRecord->hasUserProvidedDefaultConstructor())
3528 return true;
3529
3530 if (!Union && FieldRecord->isUnion() &&
3531 FieldRecord->isAnonymousStructOrUnion()) {
3532 // We're okay to reuse AllConst here since we only care about the
3533 // value otherwise if we're in a union.
3534 AllConst = true;
3535
3536 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3537 UE = FieldRecord->field_end();
3538 UI != UE; ++UI) {
3539 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3540 CXXRecordDecl *UnionFieldRecord =
3541 UnionFieldType->getAsCXXRecordDecl();
3542
3543 if (!UnionFieldType.isConstQualified())
3544 AllConst = false;
3545
3546 if (UnionFieldRecord &&
3547 !UnionFieldRecord->hasTrivialDefaultConstructor())
3548 return true;
3549 }
Sean Hunt2be7e902011-05-12 22:46:29 +00003550
Sean Huntcdee3fe2011-05-11 22:34:38 +00003551 if (AllConst)
3552 return true;
3553
3554 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00003555 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00003556 continue;
3557 }
Sean Huntb320e0c2011-06-10 03:50:41 +00003558
Richard Smith7a614d82011-06-11 17:19:42 +00003559 // -- any non-static data member with no brace-or-equal-initializer has
3560 // class type M (or array thereof) and either M has no default
3561 // constructor or overload resolution as applied to M's default
3562 // constructor results in an ambiguity or in a function that is deleted
3563 // or inaccessible from the defaulted default constructor.
3564 if (!FI->hasInClassInitializer()) {
3565 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3566 if (!FieldDefault || FieldDefault->isDeleted())
3567 return true;
3568 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3569 PDiag()) != AR_accessible)
3570 return true;
3571 }
3572 } else if (!Union && FieldType.isConstQualified() &&
3573 !FI->hasInClassInitializer()) {
Sean Hunte3406822011-05-20 21:43:47 +00003574 // -- any non-variant non-static data member of const-qualified type (or
3575 // array thereof) with no brace-or-equal-initializer does not have a
3576 // user-provided default constructor
3577 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00003578 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003579 }
3580
3581 if (Union && AllConst)
3582 return true;
3583
3584 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003585}
3586
Sean Hunt49634cf2011-05-13 06:10:58 +00003587bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Sean Hunt493ff722011-05-18 20:57:13 +00003588 CXXRecordDecl *RD = CD->getParent();
Sean Hunt49634cf2011-05-13 06:10:58 +00003589 assert(!RD->isDependentType() && "do deletion after instantiation");
3590 if (!LangOpts.CPlusPlus0x)
3591 return false;
3592
Sean Hunt71a682f2011-05-18 03:41:58 +00003593 SourceLocation Loc = CD->getLocation();
3594
Sean Hunt49634cf2011-05-13 06:10:58 +00003595 // Do access control from the constructor
3596 ContextRAII CtorContext(*this, CD);
3597
Sean Huntc530d172011-06-10 04:44:37 +00003598 bool Union = RD->isUnion();
Sean Hunt49634cf2011-05-13 06:10:58 +00003599
Sean Hunt2b188082011-05-14 05:23:28 +00003600 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3601 "copy assignment arg has no pointee type");
Sean Huntc530d172011-06-10 04:44:37 +00003602 unsigned ArgQuals =
3603 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3604 Qualifiers::Const : 0;
Sean Hunt49634cf2011-05-13 06:10:58 +00003605
3606 // We do this because we should never actually use an anonymous
3607 // union's constructor.
3608 if (Union && RD->isAnonymousStructOrUnion())
3609 return false;
3610
3611 // FIXME: We should put some diagnostic logic right into this function.
3612
3613 // C++0x [class.copy]/11
3614 // A defaulted [copy] constructor for class X is defined as delete if X has:
3615
3616 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3617 BE = RD->bases_end();
3618 BI != BE; ++BI) {
3619 // We'll handle this one later
3620 if (BI->isVirtual())
3621 continue;
3622
3623 QualType BaseType = BI->getType();
3624 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3625 assert(BaseDecl && "base isn't a CXXRecordDecl");
3626
3627 // -- any [direct base class] of a type with a destructor that is deleted or
3628 // inaccessible from the defaulted constructor
3629 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3630 if (BaseDtor->isDeleted())
3631 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003632 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003633 AR_accessible)
3634 return true;
3635
3636 // -- a [direct base class] B that cannot be [copied] because overload
3637 // resolution, as applied to B's [copy] constructor, results in an
3638 // ambiguity or a function that is deleted or inaccessible from the
3639 // defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003640 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003641 if (!BaseCtor || BaseCtor->isDeleted())
3642 return true;
3643 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3644 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003645 return true;
3646 }
3647
3648 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3649 BE = RD->vbases_end();
3650 BI != BE; ++BI) {
3651 QualType BaseType = BI->getType();
3652 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3653 assert(BaseDecl && "base isn't a CXXRecordDecl");
3654
Sean Huntb320e0c2011-06-10 03:50:41 +00003655 // -- any [virtual base class] of a type with a destructor that is deleted or
Sean Hunt49634cf2011-05-13 06:10:58 +00003656 // inaccessible from the defaulted constructor
3657 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3658 if (BaseDtor->isDeleted())
3659 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003660 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003661 AR_accessible)
3662 return true;
3663
3664 // -- a [virtual base class] B that cannot be [copied] because overload
3665 // resolution, as applied to B's [copy] constructor, results in an
3666 // ambiguity or a function that is deleted or inaccessible from the
3667 // defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003668 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003669 if (!BaseCtor || BaseCtor->isDeleted())
3670 return true;
3671 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3672 AR_accessible)
Sean Hunt49634cf2011-05-13 06:10:58 +00003673 return true;
3674 }
3675
3676 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3677 FE = RD->field_end();
3678 FI != FE; ++FI) {
3679 QualType FieldType = Context.getBaseElementType(FI->getType());
3680
3681 // -- for a copy constructor, a non-static data member of rvalue reference
3682 // type
3683 if (FieldType->isRValueReferenceType())
3684 return true;
3685
3686 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3687
3688 if (FieldRecord) {
3689 // This is an anonymous union
3690 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3691 // Anonymous unions inside unions do not variant members create
3692 if (!Union) {
3693 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3694 UE = FieldRecord->field_end();
3695 UI != UE; ++UI) {
3696 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3697 CXXRecordDecl *UnionFieldRecord =
3698 UnionFieldType->getAsCXXRecordDecl();
3699
3700 // -- a variant member with a non-trivial [copy] constructor and X
3701 // is a union-like class
3702 if (UnionFieldRecord &&
3703 !UnionFieldRecord->hasTrivialCopyConstructor())
3704 return true;
3705 }
3706 }
3707
3708 // Don't try to initalize an anonymous union
3709 continue;
3710 } else {
3711 // -- a variant member with a non-trivial [copy] constructor and X is a
3712 // union-like class
3713 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3714 return true;
3715
3716 // -- any [non-static data member] of a type with a destructor that is
3717 // deleted or inaccessible from the defaulted constructor
3718 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3719 if (FieldDtor->isDeleted())
3720 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003721 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Hunt49634cf2011-05-13 06:10:58 +00003722 AR_accessible)
3723 return true;
3724 }
Sean Huntc530d172011-06-10 04:44:37 +00003725
3726 // -- a [non-static data member of class type (or array thereof)] B that
3727 // cannot be [copied] because overload resolution, as applied to B's
3728 // [copy] constructor, results in an ambiguity or a function that is
3729 // deleted or inaccessible from the defaulted constructor
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003730 CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3731 ArgQuals);
Sean Huntc530d172011-06-10 04:44:37 +00003732 if (!FieldCtor || FieldCtor->isDeleted())
3733 return true;
3734 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3735 PDiag()) != AR_accessible)
3736 return true;
Sean Hunt49634cf2011-05-13 06:10:58 +00003737 }
Sean Hunt49634cf2011-05-13 06:10:58 +00003738 }
3739
3740 return false;
3741}
3742
Sean Hunt7f410192011-05-14 05:23:24 +00003743bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3744 CXXRecordDecl *RD = MD->getParent();
3745 assert(!RD->isDependentType() && "do deletion after instantiation");
3746 if (!LangOpts.CPlusPlus0x)
3747 return false;
3748
Sean Hunt71a682f2011-05-18 03:41:58 +00003749 SourceLocation Loc = MD->getLocation();
3750
Sean Hunt7f410192011-05-14 05:23:24 +00003751 // Do access control from the constructor
3752 ContextRAII MethodContext(*this, MD);
3753
3754 bool Union = RD->isUnion();
3755
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003756 bool ConstArg =
3757 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Sean Hunt7f410192011-05-14 05:23:24 +00003758
3759 // We do this because we should never actually use an anonymous
3760 // union's constructor.
3761 if (Union && RD->isAnonymousStructOrUnion())
3762 return false;
3763
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003764 DeclarationName OperatorName =
3765 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3766 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3767 R.suppressDiagnostics();
3768
Sean Hunt7f410192011-05-14 05:23:24 +00003769 // FIXME: We should put some diagnostic logic right into this function.
3770
3771 // C++0x [class.copy]/11
3772 // A defaulted [copy] assignment operator for class X is defined as deleted
3773 // if X has:
3774
3775 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3776 BE = RD->bases_end();
3777 BI != BE; ++BI) {
3778 // We'll handle this one later
3779 if (BI->isVirtual())
3780 continue;
3781
3782 QualType BaseType = BI->getType();
3783 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3784 assert(BaseDecl && "base isn't a CXXRecordDecl");
3785
3786 // -- a [direct base class] B that cannot be [copied] because overload
3787 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00003788 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00003789 // assignment operator
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003790
3791 LookupQualifiedName(R, BaseDecl, false);
3792
3793 // Filter out any result that isn't a copy-assignment operator.
3794 LookupResult::Filter F = R.makeFilter();
3795 while (F.hasNext()) {
3796 NamedDecl *D = F.next();
3797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3798 if (Method->isCopyAssignmentOperator())
3799 continue;
3800
3801 F.erase();
3802 }
3803 F.done();
3804
3805 // Build a fake argument expression
3806 QualType ArgType = BaseType;
3807 QualType ThisType = BaseType;
3808 if (ConstArg)
3809 ArgType.addConst();
3810 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3811 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3812 };
3813
3814 OverloadCandidateSet OCS((Loc));
3815 OverloadCandidateSet::iterator Best;
3816
3817 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3818
3819 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3820 OR_Success)
Sean Hunt7f410192011-05-14 05:23:24 +00003821 return true;
3822 }
3823
3824 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3825 BE = RD->vbases_end();
3826 BI != BE; ++BI) {
3827 QualType BaseType = BI->getType();
3828 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3829 assert(BaseDecl && "base isn't a CXXRecordDecl");
3830
Sean Hunt7f410192011-05-14 05:23:24 +00003831 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00003832 // resolution, as applied to B's [copy] assignment operator, results in
3833 // an ambiguity or a function that is deleted or inaccessible from the
3834 // assignment operator
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003835
3836 LookupQualifiedName(R, BaseDecl, false);
3837
3838 // Filter out any result that isn't a copy-assignment operator.
3839 LookupResult::Filter F = R.makeFilter();
3840 while (F.hasNext()) {
3841 NamedDecl *D = F.next();
3842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3843 if (Method->isCopyAssignmentOperator())
3844 continue;
3845
3846 F.erase();
3847 }
3848 F.done();
3849
3850 // Build a fake argument expression
3851 QualType ArgType = BaseType;
3852 QualType ThisType = BaseType;
3853 if (ConstArg)
3854 ArgType.addConst();
3855 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3856 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3857 };
3858
3859 OverloadCandidateSet OCS((Loc));
3860 OverloadCandidateSet::iterator Best;
3861
3862 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3863
3864 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3865 OR_Success)
Sean Hunt7f410192011-05-14 05:23:24 +00003866 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00003867 }
3868
3869 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3870 FE = RD->field_end();
3871 FI != FE; ++FI) {
3872 QualType FieldType = Context.getBaseElementType(FI->getType());
3873
3874 // -- a non-static data member of reference type
3875 if (FieldType->isReferenceType())
3876 return true;
3877
3878 // -- a non-static data member of const non-class type (or array thereof)
3879 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3880 return true;
3881
3882 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3883
3884 if (FieldRecord) {
3885 // This is an anonymous union
3886 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3887 // Anonymous unions inside unions do not variant members create
3888 if (!Union) {
3889 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3890 UE = FieldRecord->field_end();
3891 UI != UE; ++UI) {
3892 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3893 CXXRecordDecl *UnionFieldRecord =
3894 UnionFieldType->getAsCXXRecordDecl();
3895
3896 // -- a variant member with a non-trivial [copy] assignment operator
3897 // and X is a union-like class
3898 if (UnionFieldRecord &&
3899 !UnionFieldRecord->hasTrivialCopyAssignment())
3900 return true;
3901 }
3902 }
3903
3904 // Don't try to initalize an anonymous union
3905 continue;
3906 // -- a variant member with a non-trivial [copy] assignment operator
3907 // and X is a union-like class
3908 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3909 return true;
3910 }
Sean Hunt7f410192011-05-14 05:23:24 +00003911
Sean Hunt3bde0ce2011-06-10 12:07:09 +00003912 LookupQualifiedName(R, FieldRecord, false);
3913
3914 // Filter out any result that isn't a copy-assignment operator.
3915 LookupResult::Filter F = R.makeFilter();
3916 while (F.hasNext()) {
3917 NamedDecl *D = F.next();
3918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3919 if (Method->isCopyAssignmentOperator())
3920 continue;
3921
3922 F.erase();
3923 }
3924 F.done();
3925
3926 // Build a fake argument expression
3927 QualType ArgType = FieldType;
3928 QualType ThisType = FieldType;
3929 if (ConstArg)
3930 ArgType.addConst();
3931 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3932 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3933 };
3934
3935 OverloadCandidateSet OCS((Loc));
3936 OverloadCandidateSet::iterator Best;
3937
3938 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3939
3940 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3941 OR_Success)
3942 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00003943 }
Sean Hunt7f410192011-05-14 05:23:24 +00003944 }
3945
3946 return false;
3947}
3948
Sean Huntcb45a0f2011-05-12 22:46:25 +00003949bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3950 CXXRecordDecl *RD = DD->getParent();
3951 assert(!RD->isDependentType() && "do deletion after instantiation");
3952 if (!LangOpts.CPlusPlus0x)
3953 return false;
3954
Sean Hunt71a682f2011-05-18 03:41:58 +00003955 SourceLocation Loc = DD->getLocation();
3956
Sean Huntcb45a0f2011-05-12 22:46:25 +00003957 // Do access control from the destructor
3958 ContextRAII CtorContext(*this, DD);
3959
3960 bool Union = RD->isUnion();
3961
Sean Hunt49634cf2011-05-13 06:10:58 +00003962 // We do this because we should never actually use an anonymous
3963 // union's destructor.
3964 if (Union && RD->isAnonymousStructOrUnion())
3965 return false;
3966
Sean Huntcb45a0f2011-05-12 22:46:25 +00003967 // C++0x [class.dtor]p5
3968 // A defaulted destructor for a class X is defined as deleted if:
3969 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3970 BE = RD->bases_end();
3971 BI != BE; ++BI) {
3972 // We'll handle this one later
3973 if (BI->isVirtual())
3974 continue;
3975
3976 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3977 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3978 assert(BaseDtor && "base has no destructor");
3979
3980 // -- any direct or virtual base class has a deleted destructor or
3981 // a destructor that is inaccessible from the defaulted destructor
3982 if (BaseDtor->isDeleted())
3983 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00003984 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00003985 AR_accessible)
3986 return true;
3987 }
3988
3989 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3990 BE = RD->vbases_end();
3991 BI != BE; ++BI) {
3992 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3993 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3994 assert(BaseDtor && "base has no destructor");
3995
3996 // -- any direct or virtual base class has a deleted destructor or
3997 // a destructor that is inaccessible from the defaulted destructor
3998 if (BaseDtor->isDeleted())
3999 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004000 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004001 AR_accessible)
4002 return true;
4003 }
4004
4005 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4006 FE = RD->field_end();
4007 FI != FE; ++FI) {
4008 QualType FieldType = Context.getBaseElementType(FI->getType());
4009 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4010 if (FieldRecord) {
4011 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4012 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4013 UE = FieldRecord->field_end();
4014 UI != UE; ++UI) {
4015 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4016 CXXRecordDecl *UnionFieldRecord =
4017 UnionFieldType->getAsCXXRecordDecl();
4018
4019 // -- X is a union-like class that has a variant member with a non-
4020 // trivial destructor.
4021 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4022 return true;
4023 }
4024 // Technically we are supposed to do this next check unconditionally.
4025 // But that makes absolutely no sense.
4026 } else {
4027 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4028
4029 // -- any of the non-static data members has class type M (or array
4030 // thereof) and M has a deleted destructor or a destructor that is
4031 // inaccessible from the defaulted destructor
4032 if (FieldDtor->isDeleted())
4033 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004034 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004035 AR_accessible)
4036 return true;
4037
4038 // -- X is a union-like class that has a variant member with a non-
4039 // trivial destructor.
4040 if (Union && !FieldDtor->isTrivial())
4041 return true;
4042 }
4043 }
4044 }
4045
4046 if (DD->isVirtual()) {
4047 FunctionDecl *OperatorDelete = 0;
4048 DeclarationName Name =
4049 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004050 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004051 false))
4052 return true;
4053 }
4054
4055
4056 return false;
4057}
4058
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004059/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004060namespace {
4061 struct FindHiddenVirtualMethodData {
4062 Sema *S;
4063 CXXMethodDecl *Method;
4064 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4065 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4066 };
4067}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004068
4069/// \brief Member lookup function that determines whether a given C++
4070/// method overloads virtual methods in a base class without overriding any,
4071/// to be used with CXXRecordDecl::lookupInBases().
4072static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4073 CXXBasePath &Path,
4074 void *UserData) {
4075 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4076
4077 FindHiddenVirtualMethodData &Data
4078 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4079
4080 DeclarationName Name = Data.Method->getDeclName();
4081 assert(Name.getNameKind() == DeclarationName::Identifier);
4082
4083 bool foundSameNameMethod = false;
4084 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4085 for (Path.Decls = BaseRecord->lookup(Name);
4086 Path.Decls.first != Path.Decls.second;
4087 ++Path.Decls.first) {
4088 NamedDecl *D = *Path.Decls.first;
4089 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004090 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004091 foundSameNameMethod = true;
4092 // Interested only in hidden virtual methods.
4093 if (!MD->isVirtual())
4094 continue;
4095 // If the method we are checking overrides a method from its base
4096 // don't warn about the other overloaded methods.
4097 if (!Data.S->IsOverload(Data.Method, MD, false))
4098 return true;
4099 // Collect the overload only if its hidden.
4100 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4101 overloadedMethods.push_back(MD);
4102 }
4103 }
4104
4105 if (foundSameNameMethod)
4106 Data.OverloadedMethods.append(overloadedMethods.begin(),
4107 overloadedMethods.end());
4108 return foundSameNameMethod;
4109}
4110
4111/// \brief See if a method overloads virtual methods in a base class without
4112/// overriding any.
4113void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4114 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4115 MD->getLocation()) == Diagnostic::Ignored)
4116 return;
4117 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4118 return;
4119
4120 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4121 /*bool RecordPaths=*/false,
4122 /*bool DetectVirtual=*/false);
4123 FindHiddenVirtualMethodData Data;
4124 Data.Method = MD;
4125 Data.S = this;
4126
4127 // Keep the base methods that were overriden or introduced in the subclass
4128 // by 'using' in a set. A base method not in this set is hidden.
4129 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4130 res.first != res.second; ++res.first) {
4131 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4132 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4133 E = MD->end_overridden_methods();
4134 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004135 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004136 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4137 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004138 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004139 }
4140
4141 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4142 !Data.OverloadedMethods.empty()) {
4143 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4144 << MD << (Data.OverloadedMethods.size() > 1);
4145
4146 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4147 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4148 Diag(overloadedMD->getLocation(),
4149 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4150 }
4151 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004152}
4153
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004154void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004155 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004156 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004157 SourceLocation RBrac,
4158 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004159 if (!TagDecl)
4160 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Douglas Gregor42af25f2009-05-11 19:58:34 +00004162 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004163
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004164 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00004165 // strict aliasing violation!
4166 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004167 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004168
Douglas Gregor23c94db2010-07-02 17:43:08 +00004169 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004170 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004171}
4172
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004173/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4174/// special functions, such as the default constructor, copy
4175/// constructor, or destructor, to the given C++ class (C++
4176/// [special]p1). This routine can only be executed just before the
4177/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004178void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004179 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004180 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004181
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004182 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004183 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004184
Douglas Gregora376d102010-07-02 21:50:04 +00004185 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4186 ++ASTContext::NumImplicitCopyAssignmentOperators;
4187
4188 // If we have a dynamic class, then the copy assignment operator may be
4189 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4190 // it shows up in the right place in the vtable and that we diagnose
4191 // problems with the implicit exception specification.
4192 if (ClassDecl->isDynamicClass())
4193 DeclareImplicitCopyAssignment(ClassDecl);
4194 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004195
Douglas Gregor4923aa22010-07-02 20:37:36 +00004196 if (!ClassDecl->hasUserDeclaredDestructor()) {
4197 ++ASTContext::NumImplicitDestructors;
4198
4199 // If we have a dynamic class, then the destructor may be virtual, so we
4200 // have to declare the destructor immediately. This ensures that, e.g., it
4201 // shows up in the right place in the vtable and that we diagnose problems
4202 // with the implicit exception specification.
4203 if (ClassDecl->isDynamicClass())
4204 DeclareImplicitDestructor(ClassDecl);
4205 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004206}
4207
Francois Pichet8387e2a2011-04-22 22:18:13 +00004208void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4209 if (!D)
4210 return;
4211
4212 int NumParamList = D->getNumTemplateParameterLists();
4213 for (int i = 0; i < NumParamList; i++) {
4214 TemplateParameterList* Params = D->getTemplateParameterList(i);
4215 for (TemplateParameterList::iterator Param = Params->begin(),
4216 ParamEnd = Params->end();
4217 Param != ParamEnd; ++Param) {
4218 NamedDecl *Named = cast<NamedDecl>(*Param);
4219 if (Named->getDeclName()) {
4220 S->AddDecl(Named);
4221 IdResolver.AddDecl(Named);
4222 }
4223 }
4224 }
4225}
4226
John McCalld226f652010-08-21 09:40:31 +00004227void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004228 if (!D)
4229 return;
4230
4231 TemplateParameterList *Params = 0;
4232 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4233 Params = Template->getTemplateParameters();
4234 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4235 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4236 Params = PartialSpec->getTemplateParameters();
4237 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004238 return;
4239
Douglas Gregor6569d682009-05-27 23:11:45 +00004240 for (TemplateParameterList::iterator Param = Params->begin(),
4241 ParamEnd = Params->end();
4242 Param != ParamEnd; ++Param) {
4243 NamedDecl *Named = cast<NamedDecl>(*Param);
4244 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004245 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004246 IdResolver.AddDecl(Named);
4247 }
4248 }
4249}
4250
John McCalld226f652010-08-21 09:40:31 +00004251void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004252 if (!RecordD) return;
4253 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004254 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004255 PushDeclContext(S, Record);
4256}
4257
John McCalld226f652010-08-21 09:40:31 +00004258void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004259 if (!RecordD) return;
4260 PopDeclContext();
4261}
4262
Douglas Gregor72b505b2008-12-16 21:30:33 +00004263/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4264/// parsing a top-level (non-nested) C++ class, and we are now
4265/// parsing those parts of the given Method declaration that could
4266/// not be parsed earlier (C++ [class.mem]p2), such as default
4267/// arguments. This action should enter the scope of the given
4268/// Method declaration as if we had just parsed the qualified method
4269/// name. However, it should not bring the parameters into scope;
4270/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004271void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004272}
4273
4274/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4275/// C++ method declaration. We're (re-)introducing the given
4276/// function parameter into scope for use in parsing later parts of
4277/// the method declaration. For example, we could see an
4278/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004279void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004280 if (!ParamD)
4281 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004282
John McCalld226f652010-08-21 09:40:31 +00004283 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004284
4285 // If this parameter has an unparsed default argument, clear it out
4286 // to make way for the parsed default argument.
4287 if (Param->hasUnparsedDefaultArg())
4288 Param->setDefaultArg(0);
4289
John McCalld226f652010-08-21 09:40:31 +00004290 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004291 if (Param->getDeclName())
4292 IdResolver.AddDecl(Param);
4293}
4294
4295/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4296/// processing the delayed method declaration for Method. The method
4297/// declaration is now considered finished. There may be a separate
4298/// ActOnStartOfFunctionDef action later (not necessarily
4299/// immediately!) for this method, if it was also defined inside the
4300/// class body.
John McCalld226f652010-08-21 09:40:31 +00004301void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004302 if (!MethodD)
4303 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004305 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004306
John McCalld226f652010-08-21 09:40:31 +00004307 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004308
4309 // Now that we have our default arguments, check the constructor
4310 // again. It could produce additional diagnostics or affect whether
4311 // the class has implicitly-declared destructors, among other
4312 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004313 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4314 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004315
4316 // Check the default arguments, which we may have added.
4317 if (!Method->isInvalidDecl())
4318 CheckCXXDefaultArguments(Method);
4319}
4320
Douglas Gregor42a552f2008-11-05 20:51:48 +00004321/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004322/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004323/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004324/// emit diagnostics and set the invalid bit to true. In any case, the type
4325/// will be updated to reflect a well-formed type for the constructor and
4326/// returned.
4327QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004328 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004329 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004330
4331 // C++ [class.ctor]p3:
4332 // A constructor shall not be virtual (10.3) or static (9.4). A
4333 // constructor can be invoked for a const, volatile or const
4334 // volatile object. A constructor shall not be declared const,
4335 // volatile, or const volatile (9.3.2).
4336 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004337 if (!D.isInvalidType())
4338 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4339 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4340 << SourceRange(D.getIdentifierLoc());
4341 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004342 }
John McCalld931b082010-08-26 03:08:43 +00004343 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004344 if (!D.isInvalidType())
4345 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4346 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4347 << SourceRange(D.getIdentifierLoc());
4348 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004349 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004350 }
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004352 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004353 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004354 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004355 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4356 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004357 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004358 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4359 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004360 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004361 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4362 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004363 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
Douglas Gregorc938c162011-01-26 05:01:58 +00004366 // C++0x [class.ctor]p4:
4367 // A constructor shall not be declared with a ref-qualifier.
4368 if (FTI.hasRefQualifier()) {
4369 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4370 << FTI.RefQualifierIsLValueRef
4371 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4372 D.setInvalidType();
4373 }
4374
Douglas Gregor42a552f2008-11-05 20:51:48 +00004375 // Rebuild the function type "R" without any type qualifiers (in
4376 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004377 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004378 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004379 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4380 return R;
4381
4382 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4383 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004384 EPI.RefQualifier = RQ_None;
4385
Chris Lattner65401802009-04-25 08:28:21 +00004386 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004387 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004388}
4389
Douglas Gregor72b505b2008-12-16 21:30:33 +00004390/// CheckConstructor - Checks a fully-formed constructor for
4391/// well-formedness, issuing any diagnostics required. Returns true if
4392/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004393void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004394 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004395 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4396 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004397 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004398
4399 // C++ [class.copy]p3:
4400 // A declaration of a constructor for a class X is ill-formed if
4401 // its first parameter is of type (optionally cv-qualified) X and
4402 // either there are no other parameters or else all other
4403 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00004404 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004405 ((Constructor->getNumParams() == 1) ||
4406 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00004407 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4408 Constructor->getTemplateSpecializationKind()
4409 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004410 QualType ParamType = Constructor->getParamDecl(0)->getType();
4411 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4412 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00004413 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004414 const char *ConstRef
4415 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4416 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00004417 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00004418 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00004419
4420 // FIXME: Rather that making the constructor invalid, we should endeavor
4421 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00004422 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004423 }
4424 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00004425}
4426
John McCall15442822010-08-04 01:04:25 +00004427/// CheckDestructor - Checks a fully-formed destructor definition for
4428/// well-formedness, issuing any diagnostics required. Returns true
4429/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004430bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00004431 CXXRecordDecl *RD = Destructor->getParent();
4432
4433 if (Destructor->isVirtual()) {
4434 SourceLocation Loc;
4435
4436 if (!Destructor->isImplicit())
4437 Loc = Destructor->getLocation();
4438 else
4439 Loc = RD->getLocation();
4440
4441 // If we have a virtual destructor, look up the deallocation function
4442 FunctionDecl *OperatorDelete = 0;
4443 DeclarationName Name =
4444 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00004445 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00004446 return true;
John McCall5efd91a2010-07-03 18:33:00 +00004447
4448 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00004449
4450 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00004451 }
Anders Carlsson37909802009-11-30 21:24:50 +00004452
4453 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00004454}
4455
Mike Stump1eb44332009-09-09 15:08:12 +00004456static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004457FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4458 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4459 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00004460 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004461}
4462
Douglas Gregor42a552f2008-11-05 20:51:48 +00004463/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4464/// the well-formednes of the destructor declarator @p D with type @p
4465/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004466/// emit diagnostics and set the declarator to invalid. Even if this happens,
4467/// will be updated to reflect a well-formed type for the destructor and
4468/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00004469QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004470 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004471 // C++ [class.dtor]p1:
4472 // [...] A typedef-name that names a class is a class-name
4473 // (7.1.3); however, a typedef-name that names a class shall not
4474 // be used as the identifier in the declarator for a destructor
4475 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004476 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00004477 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00004478 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00004479 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00004480 else if (const TemplateSpecializationType *TST =
4481 DeclaratorType->getAs<TemplateSpecializationType>())
4482 if (TST->isTypeAlias())
4483 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4484 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004485
4486 // C++ [class.dtor]p2:
4487 // A destructor is used to destroy objects of its class type. A
4488 // destructor takes no parameters, and no return type can be
4489 // specified for it (not even void). The address of a destructor
4490 // shall not be taken. A destructor shall not be static. A
4491 // destructor can be invoked for a const, volatile or const
4492 // volatile object. A destructor shall not be declared const,
4493 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00004494 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004495 if (!D.isInvalidType())
4496 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4497 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00004498 << SourceRange(D.getIdentifierLoc())
4499 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4500
John McCalld931b082010-08-26 03:08:43 +00004501 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004502 }
Chris Lattner65401802009-04-25 08:28:21 +00004503 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004504 // Destructors don't have return types, but the parser will
4505 // happily parse something like:
4506 //
4507 // class X {
4508 // float ~X();
4509 // };
4510 //
4511 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004512 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4513 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4514 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00004515 }
Mike Stump1eb44332009-09-09 15:08:12 +00004516
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004517 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004518 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00004519 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004520 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4521 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004522 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004523 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4524 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004525 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004526 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4527 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00004528 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004529 }
4530
Douglas Gregorc938c162011-01-26 05:01:58 +00004531 // C++0x [class.dtor]p2:
4532 // A destructor shall not be declared with a ref-qualifier.
4533 if (FTI.hasRefQualifier()) {
4534 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4535 << FTI.RefQualifierIsLValueRef
4536 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4537 D.setInvalidType();
4538 }
4539
Douglas Gregor42a552f2008-11-05 20:51:48 +00004540 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00004541 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004542 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4543
4544 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00004545 FTI.freeArgs();
4546 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004547 }
4548
Mike Stump1eb44332009-09-09 15:08:12 +00004549 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00004550 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004551 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00004552 D.setInvalidType();
4553 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00004554
4555 // Rebuild the function type "R" without any type qualifiers or
4556 // parameters (in case any of the errors above fired) and with
4557 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00004558 // types.
John McCalle23cf432010-12-14 08:05:40 +00004559 if (!D.isInvalidType())
4560 return R;
4561
Douglas Gregord92ec472010-07-01 05:10:53 +00004562 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004563 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4564 EPI.Variadic = false;
4565 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004566 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00004567 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004568}
4569
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004570/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4571/// well-formednes of the conversion function declarator @p D with
4572/// type @p R. If there are any errors in the declarator, this routine
4573/// will emit diagnostics and return true. Otherwise, it will return
4574/// false. Either way, the type @p R will be updated to reflect a
4575/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00004576void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00004577 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004578 // C++ [class.conv.fct]p1:
4579 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00004580 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00004581 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00004582 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00004583 if (!D.isInvalidType())
4584 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4585 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4586 << SourceRange(D.getIdentifierLoc());
4587 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004588 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004589 }
John McCalla3f81372010-04-13 00:04:31 +00004590
4591 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4592
Chris Lattner6e475012009-04-25 08:35:12 +00004593 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004594 // Conversion functions don't have return types, but the parser will
4595 // happily parse something like:
4596 //
4597 // class X {
4598 // float operator bool();
4599 // };
4600 //
4601 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004602 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4603 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4604 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00004605 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004606 }
4607
John McCalla3f81372010-04-13 00:04:31 +00004608 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4609
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004610 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00004611 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004612 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4613
4614 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004615 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00004616 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00004617 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004618 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00004619 D.setInvalidType();
4620 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004621
John McCalla3f81372010-04-13 00:04:31 +00004622 // Diagnose "&operator bool()" and other such nonsense. This
4623 // is actually a gcc extension which we don't support.
4624 if (Proto->getResultType() != ConvType) {
4625 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4626 << Proto->getResultType();
4627 D.setInvalidType();
4628 ConvType = Proto->getResultType();
4629 }
4630
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004631 // C++ [class.conv.fct]p4:
4632 // The conversion-type-id shall not represent a function type nor
4633 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004634 if (ConvType->isArrayType()) {
4635 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4636 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004637 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004638 } else if (ConvType->isFunctionType()) {
4639 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4640 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00004641 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004642 }
4643
4644 // Rebuild the function type "R" without any parameters (in case any
4645 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00004646 // return type.
John McCalle23cf432010-12-14 08:05:40 +00004647 if (D.isInvalidType())
4648 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004649
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004650 // C++0x explicit conversion operators.
4651 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00004652 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004653 diag::warn_explicit_conversion_functions)
4654 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004655}
4656
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004657/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4658/// the declaration of the given C++ conversion function. This routine
4659/// is responsible for recording the conversion function in the C++
4660/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00004661Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004662 assert(Conversion && "Expected to receive a conversion function declaration");
4663
Douglas Gregor9d350972008-12-12 08:25:50 +00004664 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004665
4666 // Make sure we aren't redeclaring the conversion function.
4667 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004668
4669 // C++ [class.conv.fct]p1:
4670 // [...] A conversion function is never used to convert a
4671 // (possibly cv-qualified) object to the (possibly cv-qualified)
4672 // same object type (or a reference to it), to a (possibly
4673 // cv-qualified) base class of that type (or a reference to it),
4674 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00004675 // FIXME: Suppress this warning if the conversion function ends up being a
4676 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00004677 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004678 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00004679 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004680 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004681 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4682 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00004683 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00004684 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004685 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4686 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00004687 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004688 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004689 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00004690 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004691 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004692 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00004693 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00004694 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004695 }
4696
Douglas Gregore80622f2010-09-29 04:25:11 +00004697 if (FunctionTemplateDecl *ConversionTemplate
4698 = Conversion->getDescribedFunctionTemplate())
4699 return ConversionTemplate;
4700
John McCalld226f652010-08-21 09:40:31 +00004701 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00004702}
4703
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004704//===----------------------------------------------------------------------===//
4705// Namespace Handling
4706//===----------------------------------------------------------------------===//
4707
John McCallea318642010-08-26 09:15:37 +00004708
4709
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004710/// ActOnStartNamespaceDef - This is called at the start of a namespace
4711/// definition.
John McCalld226f652010-08-21 09:40:31 +00004712Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00004713 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004714 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00004715 SourceLocation IdentLoc,
4716 IdentifierInfo *II,
4717 SourceLocation LBrace,
4718 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004719 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4720 // For anonymous namespace, take the location of the left brace.
4721 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor21e09b62010-08-19 20:55:47 +00004722 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004723 StartLoc, Loc, II);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004724 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004725
4726 Scope *DeclRegionScope = NamespcScope->getParent();
4727
Anders Carlsson2a3503d2010-02-07 01:09:23 +00004728 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4729
John McCall90f14502010-12-10 02:59:44 +00004730 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4731 PushNamespaceVisibilityAttr(Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004732
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004733 if (II) {
4734 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00004735 // The identifier in an original-namespace-definition shall not
4736 // have been previously defined in the declarative region in
4737 // which the original-namespace-definition appears. The
4738 // identifier in an original-namespace-definition is the name of
4739 // the namespace. Subsequently in that declarative region, it is
4740 // treated as an original-namespace-name.
4741 //
4742 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00004743 // look through using directives, just look for any ordinary names.
4744
4745 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4746 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4747 Decl::IDNS_Namespace;
4748 NamedDecl *PrevDecl = 0;
4749 for (DeclContext::lookup_result R
4750 = CurContext->getRedeclContext()->lookup(II);
4751 R.first != R.second; ++R.first) {
4752 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4753 PrevDecl = *R.first;
4754 break;
4755 }
4756 }
4757
Douglas Gregor44b43212008-12-11 16:49:14 +00004758 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4759 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004760 if (Namespc->isInline() != OrigNS->isInline()) {
4761 // inline-ness must match
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004762 if (OrigNS->isInline()) {
4763 // The user probably just forgot the 'inline', so suggest that it
4764 // be added back.
4765 Diag(Namespc->getLocation(),
4766 diag::warn_inline_namespace_reopened_noninline)
4767 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4768 } else {
4769 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4770 << Namespc->isInline();
4771 }
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004772 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregorb7ec9062011-05-20 15:48:31 +00004773
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004774 // Recover by ignoring the new namespace's inline status.
4775 Namespc->setInline(OrigNS->isInline());
4776 }
4777
Douglas Gregor44b43212008-12-11 16:49:14 +00004778 // Attach this namespace decl to the chain of extended namespace
4779 // definitions.
4780 OrigNS->setNextNamespace(Namespc);
4781 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004782
Mike Stump1eb44332009-09-09 15:08:12 +00004783 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00004784 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00004785 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00004786 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004787 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004788 } else if (PrevDecl) {
4789 // This is an invalid name redefinition.
4790 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4791 << Namespc->getDeclName();
4792 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4793 Namespc->setInvalidDecl();
4794 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004795 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004796 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004797 // This is the first "real" definition of the namespace "std", so update
4798 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004799 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004800 // We had already defined a dummy namespace "std". Link this new
4801 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004802 StdNS->setNextNamespace(Namespc);
4803 StdNS->setLocation(IdentLoc);
4804 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00004805 }
4806
4807 // Make our StdNamespace cache point at the first real definition of the
4808 // "std" namespace.
4809 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00004810 }
Douglas Gregor44b43212008-12-11 16:49:14 +00004811
4812 PushOnScopeChains(Namespc, DeclRegionScope);
4813 } else {
John McCall9aeed322009-10-01 00:25:31 +00004814 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00004815 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00004816
4817 // Link the anonymous namespace into its parent.
4818 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004819 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00004820 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4821 PrevDecl = TU->getAnonymousNamespace();
4822 TU->setAnonymousNamespace(Namespc);
4823 } else {
4824 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4825 PrevDecl = ND->getAnonymousNamespace();
4826 ND->setAnonymousNamespace(Namespc);
4827 }
4828
4829 // Link the anonymous namespace with its previous declaration.
4830 if (PrevDecl) {
4831 assert(PrevDecl->isAnonymousNamespace());
4832 assert(!PrevDecl->getNextNamespace());
4833 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4834 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00004835
4836 if (Namespc->isInline() != PrevDecl->isInline()) {
4837 // inline-ness must match
4838 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4839 << Namespc->isInline();
4840 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4841 Namespc->setInvalidDecl();
4842 // Recover by ignoring the new namespace's inline status.
4843 Namespc->setInline(PrevDecl->isInline());
4844 }
John McCall5fdd7642009-12-16 02:06:49 +00004845 }
John McCall9aeed322009-10-01 00:25:31 +00004846
Douglas Gregora4181472010-03-24 00:46:35 +00004847 CurContext->addDecl(Namespc);
4848
John McCall9aeed322009-10-01 00:25:31 +00004849 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4850 // behaves as if it were replaced by
4851 // namespace unique { /* empty body */ }
4852 // using namespace unique;
4853 // namespace unique { namespace-body }
4854 // where all occurrences of 'unique' in a translation unit are
4855 // replaced by the same identifier and this identifier differs
4856 // from all other identifiers in the entire program.
4857
4858 // We just create the namespace with an empty name and then add an
4859 // implicit using declaration, just like the standard suggests.
4860 //
4861 // CodeGen enforces the "universally unique" aspect by giving all
4862 // declarations semantically contained within an anonymous
4863 // namespace internal linkage.
4864
John McCall5fdd7642009-12-16 02:06:49 +00004865 if (!PrevDecl) {
4866 UsingDirectiveDecl* UD
4867 = UsingDirectiveDecl::Create(Context, CurContext,
4868 /* 'using' */ LBrace,
4869 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00004870 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00004871 /* identifier */ SourceLocation(),
4872 Namespc,
4873 /* Ancestor */ CurContext);
4874 UD->setImplicit();
4875 CurContext->addDecl(UD);
4876 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004877 }
4878
4879 // Although we could have an invalid decl (i.e. the namespace name is a
4880 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00004881 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4882 // for the namespace has the declarations that showed up in that particular
4883 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00004884 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00004885 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004886}
4887
Sebastian Redleb0d8c92009-11-23 15:34:23 +00004888/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4889/// is a namespace alias, returns the namespace it points to.
4890static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4891 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4892 return AD->getNamespace();
4893 return dyn_cast_or_null<NamespaceDecl>(D);
4894}
4895
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004896/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4897/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00004898void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004899 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4900 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004901 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004902 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004903 if (Namespc->hasAttr<VisibilityAttr>())
4904 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00004905}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004906
John McCall384aff82010-08-25 07:42:41 +00004907CXXRecordDecl *Sema::getStdBadAlloc() const {
4908 return cast_or_null<CXXRecordDecl>(
4909 StdBadAlloc.get(Context.getExternalSource()));
4910}
4911
4912NamespaceDecl *Sema::getStdNamespace() const {
4913 return cast_or_null<NamespaceDecl>(
4914 StdNamespace.get(Context.getExternalSource()));
4915}
4916
Douglas Gregor66992202010-06-29 17:53:46 +00004917/// \brief Retrieve the special "std" namespace, which may require us to
4918/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004919NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00004920 if (!StdNamespace) {
4921 // The "std" namespace has not yet been defined, so build one implicitly.
4922 StdNamespace = NamespaceDecl::Create(Context,
4923 Context.getTranslationUnitDecl(),
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00004924 SourceLocation(), SourceLocation(),
Douglas Gregor66992202010-06-29 17:53:46 +00004925 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004926 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00004927 }
4928
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00004929 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00004930}
4931
Douglas Gregor9172aa62011-03-26 22:25:30 +00004932/// \brief Determine whether a using statement is in a context where it will be
4933/// apply in all contexts.
4934static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4935 switch (CurContext->getDeclKind()) {
4936 case Decl::TranslationUnit:
4937 return true;
4938 case Decl::LinkageSpec:
4939 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4940 default:
4941 return false;
4942 }
4943}
4944
John McCalld226f652010-08-21 09:40:31 +00004945Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004946 SourceLocation UsingLoc,
4947 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004948 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004949 SourceLocation IdentLoc,
4950 IdentifierInfo *NamespcName,
4951 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00004952 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4953 assert(NamespcName && "Invalid NamespcName.");
4954 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00004955
4956 // This can only happen along a recovery path.
4957 while (S->getFlags() & Scope::TemplateParamScope)
4958 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004959 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00004960
Douglas Gregor2a3009a2009-02-03 19:21:40 +00004961 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00004962 NestedNameSpecifier *Qualifier = 0;
4963 if (SS.isSet())
4964 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4965
Douglas Gregoreb11cd02009-01-14 22:20:51 +00004966 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004967 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4968 LookupParsedName(R, S, &SS);
4969 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004970 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00004971
Douglas Gregor66992202010-06-29 17:53:46 +00004972 if (R.empty()) {
4973 // Allow "using namespace std;" or "using namespace ::std;" even if
4974 // "std" hasn't been defined yet, for GCC compatibility.
4975 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4976 NamespcName->isStr("std")) {
4977 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00004978 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00004979 R.resolveKind();
4980 }
4981 // Otherwise, attempt typo correction.
4982 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4983 CTC_NoKeywords, 0)) {
4984 if (R.getAsSingle<NamespaceDecl>() ||
4985 R.getAsSingle<NamespaceAliasDecl>()) {
4986 if (DeclContext *DC = computeDeclContext(SS, false))
4987 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4988 << NamespcName << DC << Corrected << SS.getRange()
4989 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4990 else
4991 Diag(IdentLoc, diag::err_using_directive_suggest)
4992 << NamespcName << Corrected
4993 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4994 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4995 << Corrected;
4996
4997 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004998 } else {
4999 R.clear();
5000 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005001 }
5002 }
5003 }
5004
John McCallf36e02d2009-10-09 21:13:30 +00005005 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005006 NamedDecl *Named = R.getFoundDecl();
5007 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5008 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005009 // C++ [namespace.udir]p1:
5010 // A using-directive specifies that the names in the nominated
5011 // namespace can be used in the scope in which the
5012 // using-directive appears after the using-directive. During
5013 // unqualified name lookup (3.4.1), the names appear as if they
5014 // were declared in the nearest enclosing namespace which
5015 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005016 // namespace. [Note: in this context, "contains" means "contains
5017 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005018
5019 // Find enclosing context containing both using-directive and
5020 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005021 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005022 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5023 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5024 CommonAncestor = CommonAncestor->getParent();
5025
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005026 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005027 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005028 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005029
Douglas Gregor9172aa62011-03-26 22:25:30 +00005030 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Weber21669482011-04-02 19:45:15 +00005031 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005032 Diag(IdentLoc, diag::warn_using_directive_in_header);
5033 }
5034
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005035 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005036 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005037 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005038 }
5039
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005040 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005041 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005042}
5043
5044void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5045 // If scope has associated entity, then using directive is at namespace
5046 // or translation unit scope. We add UsingDirectiveDecls, into
5047 // it's lookup structure.
5048 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005049 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005050 else
5051 // Otherwise it is block-sope. using-directives will affect lookup
5052 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00005053 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005054}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005055
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005056
John McCalld226f652010-08-21 09:40:31 +00005057Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005058 AccessSpecifier AS,
5059 bool HasUsingKeyword,
5060 SourceLocation UsingLoc,
5061 CXXScopeSpec &SS,
5062 UnqualifiedId &Name,
5063 AttributeList *AttrList,
5064 bool IsTypeName,
5065 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005066 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005067
Douglas Gregor12c118a2009-11-04 16:30:06 +00005068 switch (Name.getKind()) {
5069 case UnqualifiedId::IK_Identifier:
5070 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005071 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005072 case UnqualifiedId::IK_ConversionFunctionId:
5073 break;
5074
5075 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005076 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00005077 // C++0x inherited constructors.
5078 if (getLangOptions().CPlusPlus0x) break;
5079
Douglas Gregor12c118a2009-11-04 16:30:06 +00005080 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5081 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005082 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005083
5084 case UnqualifiedId::IK_DestructorName:
5085 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5086 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005087 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005088
5089 case UnqualifiedId::IK_TemplateId:
5090 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5091 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005092 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005093 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005094
5095 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5096 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005097 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005098 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005099
John McCall60fa3cf2009-12-11 02:10:03 +00005100 // Warn about using declarations.
5101 // TODO: store that the declaration was written without 'using' and
5102 // talk about access decls instead of using decls in the
5103 // diagnostics.
5104 if (!HasUsingKeyword) {
5105 UsingLoc = Name.getSourceRange().getBegin();
5106
5107 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005108 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005109 }
5110
Douglas Gregor56c04582010-12-16 00:46:58 +00005111 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5112 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5113 return 0;
5114
John McCall9488ea12009-11-17 05:59:44 +00005115 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005116 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005117 /* IsInstantiation */ false,
5118 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005119 if (UD)
5120 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005121
John McCalld226f652010-08-21 09:40:31 +00005122 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005123}
5124
Douglas Gregor09acc982010-07-07 23:08:52 +00005125/// \brief Determine whether a using declaration considers the given
5126/// declarations as "equivalent", e.g., if they are redeclarations of
5127/// the same entity or are both typedefs of the same type.
5128static bool
5129IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5130 bool &SuppressRedeclaration) {
5131 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5132 SuppressRedeclaration = false;
5133 return true;
5134 }
5135
Richard Smith162e1c12011-04-15 14:24:37 +00005136 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5137 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005138 SuppressRedeclaration = true;
5139 return Context.hasSameType(TD1->getUnderlyingType(),
5140 TD2->getUnderlyingType());
5141 }
5142
5143 return false;
5144}
5145
5146
John McCall9f54ad42009-12-10 09:41:52 +00005147/// Determines whether to create a using shadow decl for a particular
5148/// decl, given the set of decls existing prior to this using lookup.
5149bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5150 const LookupResult &Previous) {
5151 // Diagnose finding a decl which is not from a base class of the
5152 // current class. We do this now because there are cases where this
5153 // function will silently decide not to build a shadow decl, which
5154 // will pre-empt further diagnostics.
5155 //
5156 // We don't need to do this in C++0x because we do the check once on
5157 // the qualifier.
5158 //
5159 // FIXME: diagnose the following if we care enough:
5160 // struct A { int foo; };
5161 // struct B : A { using A::foo; };
5162 // template <class T> struct C : A {};
5163 // template <class T> struct D : C<T> { using B::foo; } // <---
5164 // This is invalid (during instantiation) in C++03 because B::foo
5165 // resolves to the using decl in B, which is not a base class of D<T>.
5166 // We can't diagnose it immediately because C<T> is an unknown
5167 // specialization. The UsingShadowDecl in D<T> then points directly
5168 // to A::foo, which will look well-formed when we instantiate.
5169 // The right solution is to not collapse the shadow-decl chain.
5170 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5171 DeclContext *OrigDC = Orig->getDeclContext();
5172
5173 // Handle enums and anonymous structs.
5174 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5175 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5176 while (OrigRec->isAnonymousStructOrUnion())
5177 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5178
5179 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5180 if (OrigDC == CurContext) {
5181 Diag(Using->getLocation(),
5182 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005183 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005184 Diag(Orig->getLocation(), diag::note_using_decl_target);
5185 return true;
5186 }
5187
Douglas Gregordc355712011-02-25 00:36:19 +00005188 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005189 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005190 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005191 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005192 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005193 Diag(Orig->getLocation(), diag::note_using_decl_target);
5194 return true;
5195 }
5196 }
5197
5198 if (Previous.empty()) return false;
5199
5200 NamedDecl *Target = Orig;
5201 if (isa<UsingShadowDecl>(Target))
5202 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5203
John McCalld7533ec2009-12-11 02:33:26 +00005204 // If the target happens to be one of the previous declarations, we
5205 // don't have a conflict.
5206 //
5207 // FIXME: but we might be increasing its access, in which case we
5208 // should redeclare it.
5209 NamedDecl *NonTag = 0, *Tag = 0;
5210 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5211 I != E; ++I) {
5212 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005213 bool Result;
5214 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5215 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005216
5217 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5218 }
5219
John McCall9f54ad42009-12-10 09:41:52 +00005220 if (Target->isFunctionOrFunctionTemplate()) {
5221 FunctionDecl *FD;
5222 if (isa<FunctionTemplateDecl>(Target))
5223 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5224 else
5225 FD = cast<FunctionDecl>(Target);
5226
5227 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005228 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005229 case Ovl_Overload:
5230 return false;
5231
5232 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005233 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005234 break;
5235
5236 // We found a decl with the exact signature.
5237 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005238 // If we're in a record, we want to hide the target, so we
5239 // return true (without a diagnostic) to tell the caller not to
5240 // build a shadow decl.
5241 if (CurContext->isRecord())
5242 return true;
5243
5244 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00005245 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005246 break;
5247 }
5248
5249 Diag(Target->getLocation(), diag::note_using_decl_target);
5250 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5251 return true;
5252 }
5253
5254 // Target is not a function.
5255
John McCall9f54ad42009-12-10 09:41:52 +00005256 if (isa<TagDecl>(Target)) {
5257 // No conflict between a tag and a non-tag.
5258 if (!Tag) return false;
5259
John McCall41ce66f2009-12-10 19:51:03 +00005260 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005261 Diag(Target->getLocation(), diag::note_using_decl_target);
5262 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5263 return true;
5264 }
5265
5266 // No conflict between a tag and a non-tag.
5267 if (!NonTag) return false;
5268
John McCall41ce66f2009-12-10 19:51:03 +00005269 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005270 Diag(Target->getLocation(), diag::note_using_decl_target);
5271 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5272 return true;
5273}
5274
John McCall9488ea12009-11-17 05:59:44 +00005275/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00005276UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00005277 UsingDecl *UD,
5278 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00005279
5280 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00005281 NamedDecl *Target = Orig;
5282 if (isa<UsingShadowDecl>(Target)) {
5283 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5284 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00005285 }
5286
5287 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00005288 = UsingShadowDecl::Create(Context, CurContext,
5289 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00005290 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00005291
5292 Shadow->setAccess(UD->getAccess());
5293 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5294 Shadow->setInvalidDecl();
5295
John McCall9488ea12009-11-17 05:59:44 +00005296 if (S)
John McCall604e7f12009-12-08 07:46:18 +00005297 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00005298 else
John McCall604e7f12009-12-08 07:46:18 +00005299 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00005300
John McCall604e7f12009-12-08 07:46:18 +00005301
John McCall9f54ad42009-12-10 09:41:52 +00005302 return Shadow;
5303}
John McCall604e7f12009-12-08 07:46:18 +00005304
John McCall9f54ad42009-12-10 09:41:52 +00005305/// Hides a using shadow declaration. This is required by the current
5306/// using-decl implementation when a resolvable using declaration in a
5307/// class is followed by a declaration which would hide or override
5308/// one or more of the using decl's targets; for example:
5309///
5310/// struct Base { void foo(int); };
5311/// struct Derived : Base {
5312/// using Base::foo;
5313/// void foo(int);
5314/// };
5315///
5316/// The governing language is C++03 [namespace.udecl]p12:
5317///
5318/// When a using-declaration brings names from a base class into a
5319/// derived class scope, member functions in the derived class
5320/// override and/or hide member functions with the same name and
5321/// parameter types in a base class (rather than conflicting).
5322///
5323/// There are two ways to implement this:
5324/// (1) optimistically create shadow decls when they're not hidden
5325/// by existing declarations, or
5326/// (2) don't create any shadow decls (or at least don't make them
5327/// visible) until we've fully parsed/instantiated the class.
5328/// The problem with (1) is that we might have to retroactively remove
5329/// a shadow decl, which requires several O(n) operations because the
5330/// decl structures are (very reasonably) not designed for removal.
5331/// (2) avoids this but is very fiddly and phase-dependent.
5332void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00005333 if (Shadow->getDeclName().getNameKind() ==
5334 DeclarationName::CXXConversionFunctionName)
5335 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5336
John McCall9f54ad42009-12-10 09:41:52 +00005337 // Remove it from the DeclContext...
5338 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005339
John McCall9f54ad42009-12-10 09:41:52 +00005340 // ...and the scope, if applicable...
5341 if (S) {
John McCalld226f652010-08-21 09:40:31 +00005342 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00005343 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00005344 }
5345
John McCall9f54ad42009-12-10 09:41:52 +00005346 // ...and the using decl.
5347 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5348
5349 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00005350 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00005351}
5352
John McCall7ba107a2009-11-18 02:36:19 +00005353/// Builds a using declaration.
5354///
5355/// \param IsInstantiation - Whether this call arises from an
5356/// instantiation of an unresolved using declaration. We treat
5357/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00005358NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5359 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005360 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005361 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00005362 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005363 bool IsInstantiation,
5364 bool IsTypeName,
5365 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00005366 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005367 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00005368 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00005369
Anders Carlsson550b14b2009-08-28 05:49:21 +00005370 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00005371
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005372 if (SS.isEmpty()) {
5373 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00005374 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005375 }
Mike Stump1eb44332009-09-09 15:08:12 +00005376
John McCall9f54ad42009-12-10 09:41:52 +00005377 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005378 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00005379 ForRedeclaration);
5380 Previous.setHideTags(false);
5381 if (S) {
5382 LookupName(Previous, S);
5383
5384 // It is really dumb that we have to do this.
5385 LookupResult::Filter F = Previous.makeFilter();
5386 while (F.hasNext()) {
5387 NamedDecl *D = F.next();
5388 if (!isDeclInScope(D, CurContext, S))
5389 F.erase();
5390 }
5391 F.done();
5392 } else {
5393 assert(IsInstantiation && "no scope in non-instantiation");
5394 assert(CurContext->isRecord() && "scope not record in instantiation");
5395 LookupQualifiedName(Previous, CurContext);
5396 }
5397
John McCall9f54ad42009-12-10 09:41:52 +00005398 // Check for invalid redeclarations.
5399 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5400 return 0;
5401
5402 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00005403 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5404 return 0;
5405
John McCallaf8e6ed2009-11-12 03:15:40 +00005406 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005407 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00005408 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00005409 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00005410 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00005411 // FIXME: not all declaration name kinds are legal here
5412 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5413 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00005414 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005415 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00005416 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005417 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5418 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00005419 }
John McCalled976492009-12-04 22:46:56 +00005420 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00005421 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5422 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00005423 }
John McCalled976492009-12-04 22:46:56 +00005424 D->setAccess(AS);
5425 CurContext->addDecl(D);
5426
5427 if (!LookupContext) return D;
5428 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00005429
John McCall77bb1aa2010-05-01 00:40:08 +00005430 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00005431 UD->setInvalidDecl();
5432 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005433 }
5434
Sebastian Redlf677ea32011-02-05 19:23:19 +00005435 // Constructor inheriting using decls get special treatment.
5436 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00005437 if (CheckInheritedConstructorUsingDecl(UD))
5438 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005439 return UD;
5440 }
5441
5442 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00005443
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005444 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetb2ee8302011-05-23 03:43:44 +00005445 R.setUsingDeclaration(true);
John McCall7ba107a2009-11-18 02:36:19 +00005446
John McCall604e7f12009-12-08 07:46:18 +00005447 // Unlike most lookups, we don't always want to hide tag
5448 // declarations: tag names are visible through the using declaration
5449 // even if hidden by ordinary names, *except* in a dependent context
5450 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00005451 if (!IsInstantiation)
5452 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00005453
John McCalla24dc2e2009-11-17 02:14:36 +00005454 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00005455
John McCallf36e02d2009-10-09 21:13:30 +00005456 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00005457 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005458 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005459 UD->setInvalidDecl();
5460 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005461 }
5462
John McCalled976492009-12-04 22:46:56 +00005463 if (R.isAmbiguous()) {
5464 UD->setInvalidDecl();
5465 return UD;
5466 }
Mike Stump1eb44332009-09-09 15:08:12 +00005467
John McCall7ba107a2009-11-18 02:36:19 +00005468 if (IsTypeName) {
5469 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00005470 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005471 Diag(IdentLoc, diag::err_using_typename_non_type);
5472 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5473 Diag((*I)->getUnderlyingDecl()->getLocation(),
5474 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005475 UD->setInvalidDecl();
5476 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005477 }
5478 } else {
5479 // If we asked for a non-typename and we got a type, error out,
5480 // but only if this is an instantiation of an unresolved using
5481 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00005482 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00005483 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5484 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00005485 UD->setInvalidDecl();
5486 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00005487 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00005488 }
5489
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005490 // C++0x N2914 [namespace.udecl]p6:
5491 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00005492 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005493 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5494 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00005495 UD->setInvalidDecl();
5496 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00005497 }
Mike Stump1eb44332009-09-09 15:08:12 +00005498
John McCall9f54ad42009-12-10 09:41:52 +00005499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5500 if (!CheckUsingShadowDecl(UD, *I, Previous))
5501 BuildUsingShadowDecl(S, UD, *I);
5502 }
John McCall9488ea12009-11-17 05:59:44 +00005503
5504 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005505}
5506
Sebastian Redlf677ea32011-02-05 19:23:19 +00005507/// Additional checks for a using declaration referring to a constructor name.
5508bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5509 if (UD->isTypeName()) {
5510 // FIXME: Cannot specify typename when specifying constructor
5511 return true;
5512 }
5513
Douglas Gregordc355712011-02-25 00:36:19 +00005514 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00005515 assert(SourceType &&
5516 "Using decl naming constructor doesn't have type in scope spec.");
5517 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5518
5519 // Check whether the named type is a direct base class.
5520 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5521 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5522 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5523 BaseIt != BaseE; ++BaseIt) {
5524 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5525 if (CanonicalSourceType == BaseType)
5526 break;
5527 }
5528
5529 if (BaseIt == BaseE) {
5530 // Did not find SourceType in the bases.
5531 Diag(UD->getUsingLocation(),
5532 diag::err_using_decl_constructor_not_in_direct_base)
5533 << UD->getNameInfo().getSourceRange()
5534 << QualType(SourceType, 0) << TargetClass;
5535 return true;
5536 }
5537
5538 BaseIt->setInheritConstructors();
5539
5540 return false;
5541}
5542
John McCall9f54ad42009-12-10 09:41:52 +00005543/// Checks that the given using declaration is not an invalid
5544/// redeclaration. Note that this is checking only for the using decl
5545/// itself, not for any ill-formedness among the UsingShadowDecls.
5546bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5547 bool isTypeName,
5548 const CXXScopeSpec &SS,
5549 SourceLocation NameLoc,
5550 const LookupResult &Prev) {
5551 // C++03 [namespace.udecl]p8:
5552 // C++0x [namespace.udecl]p10:
5553 // A using-declaration is a declaration and can therefore be used
5554 // repeatedly where (and only where) multiple declarations are
5555 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00005556 //
John McCall8a726212010-11-29 18:01:58 +00005557 // That's in non-member contexts.
5558 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00005559 return false;
5560
5561 NestedNameSpecifier *Qual
5562 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5563
5564 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5565 NamedDecl *D = *I;
5566
5567 bool DTypename;
5568 NestedNameSpecifier *DQual;
5569 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5570 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00005571 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005572 } else if (UnresolvedUsingValueDecl *UD
5573 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5574 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00005575 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005576 } else if (UnresolvedUsingTypenameDecl *UD
5577 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5578 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00005579 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00005580 } else continue;
5581
5582 // using decls differ if one says 'typename' and the other doesn't.
5583 // FIXME: non-dependent using decls?
5584 if (isTypeName != DTypename) continue;
5585
5586 // using decls differ if they name different scopes (but note that
5587 // template instantiation can cause this check to trigger when it
5588 // didn't before instantiation).
5589 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5590 Context.getCanonicalNestedNameSpecifier(DQual))
5591 continue;
5592
5593 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00005594 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00005595 return true;
5596 }
5597
5598 return false;
5599}
5600
John McCall604e7f12009-12-08 07:46:18 +00005601
John McCalled976492009-12-04 22:46:56 +00005602/// Checks that the given nested-name qualifier used in a using decl
5603/// in the current context is appropriately related to the current
5604/// scope. If an error is found, diagnoses it and returns true.
5605bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5606 const CXXScopeSpec &SS,
5607 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00005608 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00005609
John McCall604e7f12009-12-08 07:46:18 +00005610 if (!CurContext->isRecord()) {
5611 // C++03 [namespace.udecl]p3:
5612 // C++0x [namespace.udecl]p8:
5613 // A using-declaration for a class member shall be a member-declaration.
5614
5615 // If we weren't able to compute a valid scope, it must be a
5616 // dependent class scope.
5617 if (!NamedContext || NamedContext->isRecord()) {
5618 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5619 << SS.getRange();
5620 return true;
5621 }
5622
5623 // Otherwise, everything is known to be fine.
5624 return false;
5625 }
5626
5627 // The current scope is a record.
5628
5629 // If the named context is dependent, we can't decide much.
5630 if (!NamedContext) {
5631 // FIXME: in C++0x, we can diagnose if we can prove that the
5632 // nested-name-specifier does not refer to a base class, which is
5633 // still possible in some cases.
5634
5635 // Otherwise we have to conservatively report that things might be
5636 // okay.
5637 return false;
5638 }
5639
5640 if (!NamedContext->isRecord()) {
5641 // Ideally this would point at the last name in the specifier,
5642 // but we don't have that level of source info.
5643 Diag(SS.getRange().getBegin(),
5644 diag::err_using_decl_nested_name_specifier_is_not_class)
5645 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5646 return true;
5647 }
5648
Douglas Gregor6fb07292010-12-21 07:41:49 +00005649 if (!NamedContext->isDependentContext() &&
5650 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5651 return true;
5652
John McCall604e7f12009-12-08 07:46:18 +00005653 if (getLangOptions().CPlusPlus0x) {
5654 // C++0x [namespace.udecl]p3:
5655 // In a using-declaration used as a member-declaration, the
5656 // nested-name-specifier shall name a base class of the class
5657 // being defined.
5658
5659 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5660 cast<CXXRecordDecl>(NamedContext))) {
5661 if (CurContext == NamedContext) {
5662 Diag(NameLoc,
5663 diag::err_using_decl_nested_name_specifier_is_current_class)
5664 << SS.getRange();
5665 return true;
5666 }
5667
5668 Diag(SS.getRange().getBegin(),
5669 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5670 << (NestedNameSpecifier*) SS.getScopeRep()
5671 << cast<CXXRecordDecl>(CurContext)
5672 << SS.getRange();
5673 return true;
5674 }
5675
5676 return false;
5677 }
5678
5679 // C++03 [namespace.udecl]p4:
5680 // A using-declaration used as a member-declaration shall refer
5681 // to a member of a base class of the class being defined [etc.].
5682
5683 // Salient point: SS doesn't have to name a base class as long as
5684 // lookup only finds members from base classes. Therefore we can
5685 // diagnose here only if we can prove that that can't happen,
5686 // i.e. if the class hierarchies provably don't intersect.
5687
5688 // TODO: it would be nice if "definitely valid" results were cached
5689 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5690 // need to be repeated.
5691
5692 struct UserData {
5693 llvm::DenseSet<const CXXRecordDecl*> Bases;
5694
5695 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5696 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5697 Data->Bases.insert(Base);
5698 return true;
5699 }
5700
5701 bool hasDependentBases(const CXXRecordDecl *Class) {
5702 return !Class->forallBases(collect, this);
5703 }
5704
5705 /// Returns true if the base is dependent or is one of the
5706 /// accumulated base classes.
5707 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5708 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5709 return !Data->Bases.count(Base);
5710 }
5711
5712 bool mightShareBases(const CXXRecordDecl *Class) {
5713 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5714 }
5715 };
5716
5717 UserData Data;
5718
5719 // Returns false if we find a dependent base.
5720 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5721 return false;
5722
5723 // Returns false if the class has a dependent base or if it or one
5724 // of its bases is present in the base set of the current context.
5725 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5726 return false;
5727
5728 Diag(SS.getRange().getBegin(),
5729 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5730 << (NestedNameSpecifier*) SS.getScopeRep()
5731 << cast<CXXRecordDecl>(CurContext)
5732 << SS.getRange();
5733
5734 return true;
John McCalled976492009-12-04 22:46:56 +00005735}
5736
Richard Smith162e1c12011-04-15 14:24:37 +00005737Decl *Sema::ActOnAliasDeclaration(Scope *S,
5738 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005739 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00005740 SourceLocation UsingLoc,
5741 UnqualifiedId &Name,
5742 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00005743 // Skip up to the relevant declaration scope.
5744 while (S->getFlags() & Scope::TemplateParamScope)
5745 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00005746 assert((S->getFlags() & Scope::DeclScope) &&
5747 "got alias-declaration outside of declaration scope");
5748
5749 if (Type.isInvalid())
5750 return 0;
5751
5752 bool Invalid = false;
5753 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5754 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00005755 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00005756
5757 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5758 return 0;
5759
5760 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00005761 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00005762 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005763 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5764 TInfo->getTypeLoc().getBeginLoc());
5765 }
Richard Smith162e1c12011-04-15 14:24:37 +00005766
5767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5768 LookupName(Previous, S);
5769
5770 // Warn about shadowing the name of a template parameter.
5771 if (Previous.isSingleResult() &&
5772 Previous.getFoundDecl()->isTemplateParameter()) {
5773 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5774 Previous.getFoundDecl()))
5775 Invalid = true;
5776 Previous.clear();
5777 }
5778
5779 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5780 "name in alias declaration must be an identifier");
5781 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5782 Name.StartLocation,
5783 Name.Identifier, TInfo);
5784
5785 NewTD->setAccess(AS);
5786
5787 if (Invalid)
5788 NewTD->setInvalidDecl();
5789
Richard Smith3e4c6c42011-05-05 21:57:07 +00005790 CheckTypedefForVariablyModifiedType(S, NewTD);
5791 Invalid |= NewTD->isInvalidDecl();
5792
Richard Smith162e1c12011-04-15 14:24:37 +00005793 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00005794
5795 NamedDecl *NewND;
5796 if (TemplateParamLists.size()) {
5797 TypeAliasTemplateDecl *OldDecl = 0;
5798 TemplateParameterList *OldTemplateParams = 0;
5799
5800 if (TemplateParamLists.size() != 1) {
5801 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5802 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5803 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5804 }
5805 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5806
5807 // Only consider previous declarations in the same scope.
5808 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5809 /*ExplicitInstantiationOrSpecialization*/false);
5810 if (!Previous.empty()) {
5811 Redeclaration = true;
5812
5813 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5814 if (!OldDecl && !Invalid) {
5815 Diag(UsingLoc, diag::err_redefinition_different_kind)
5816 << Name.Identifier;
5817
5818 NamedDecl *OldD = Previous.getRepresentativeDecl();
5819 if (OldD->getLocation().isValid())
5820 Diag(OldD->getLocation(), diag::note_previous_definition);
5821
5822 Invalid = true;
5823 }
5824
5825 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5826 if (TemplateParameterListsAreEqual(TemplateParams,
5827 OldDecl->getTemplateParameters(),
5828 /*Complain=*/true,
5829 TPL_TemplateMatch))
5830 OldTemplateParams = OldDecl->getTemplateParameters();
5831 else
5832 Invalid = true;
5833
5834 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5835 if (!Invalid &&
5836 !Context.hasSameType(OldTD->getUnderlyingType(),
5837 NewTD->getUnderlyingType())) {
5838 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5839 // but we can't reasonably accept it.
5840 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5841 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5842 if (OldTD->getLocation().isValid())
5843 Diag(OldTD->getLocation(), diag::note_previous_definition);
5844 Invalid = true;
5845 }
5846 }
5847 }
5848
5849 // Merge any previous default template arguments into our parameters,
5850 // and check the parameter list.
5851 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5852 TPC_TypeAliasTemplate))
5853 return 0;
5854
5855 TypeAliasTemplateDecl *NewDecl =
5856 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5857 Name.Identifier, TemplateParams,
5858 NewTD);
5859
5860 NewDecl->setAccess(AS);
5861
5862 if (Invalid)
5863 NewDecl->setInvalidDecl();
5864 else if (OldDecl)
5865 NewDecl->setPreviousDeclaration(OldDecl);
5866
5867 NewND = NewDecl;
5868 } else {
5869 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5870 NewND = NewTD;
5871 }
Richard Smith162e1c12011-04-15 14:24:37 +00005872
5873 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00005874 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00005875
Richard Smith3e4c6c42011-05-05 21:57:07 +00005876 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00005877}
5878
John McCalld226f652010-08-21 09:40:31 +00005879Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005880 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005881 SourceLocation AliasLoc,
5882 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005883 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00005884 SourceLocation IdentLoc,
5885 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00005886
Anders Carlsson81c85c42009-03-28 23:53:49 +00005887 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005888 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5889 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00005890
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005891 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00005892 NamedDecl *PrevDecl
5893 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5894 ForRedeclaration);
5895 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5896 PrevDecl = 0;
5897
5898 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00005899 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005900 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00005901 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00005902 // FIXME: At some point, we'll want to create the (redundant)
5903 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00005904 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00005905 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00005906 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00005907 }
Mike Stump1eb44332009-09-09 15:08:12 +00005908
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005909 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5910 diag::err_redefinition_different_kind;
5911 Diag(AliasLoc, DiagID) << Alias;
5912 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00005913 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00005914 }
5915
John McCalla24dc2e2009-11-17 02:14:36 +00005916 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005917 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005918
John McCallf36e02d2009-10-09 21:13:30 +00005919 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005920 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5921 CTC_NoKeywords, 0)) {
5922 if (R.getAsSingle<NamespaceDecl>() ||
5923 R.getAsSingle<NamespaceAliasDecl>()) {
5924 if (DeclContext *DC = computeDeclContext(SS, false))
5925 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5926 << Ident << DC << Corrected << SS.getRange()
5927 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5928 else
5929 Diag(IdentLoc, diag::err_using_directive_suggest)
5930 << Ident << Corrected
5931 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5932
5933 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5934 << Corrected;
5935
5936 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00005937 } else {
5938 R.clear();
5939 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005940 }
5941 }
5942
5943 if (R.empty()) {
5944 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005945 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00005946 }
Anders Carlsson5721c682009-03-28 06:42:02 +00005947 }
Mike Stump1eb44332009-09-09 15:08:12 +00005948
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00005949 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00005950 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00005951 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00005952 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00005953
John McCall3dbd3d52010-02-16 06:53:13 +00005954 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00005955 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00005956}
5957
Douglas Gregor39957dc2010-05-01 15:04:51 +00005958namespace {
5959 /// \brief Scoped object used to handle the state changes required in Sema
5960 /// to implicitly define the body of a C++ member function;
5961 class ImplicitlyDefinedFunctionScope {
5962 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00005963 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00005964
5965 public:
5966 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00005967 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00005968 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00005969 S.PushFunctionScope();
5970 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5971 }
5972
5973 ~ImplicitlyDefinedFunctionScope() {
5974 S.PopExpressionEvaluationContext();
5975 S.PopFunctionOrBlockScope();
Douglas Gregor39957dc2010-05-01 15:04:51 +00005976 }
5977 };
5978}
5979
Sean Hunt001cad92011-05-10 00:49:42 +00005980Sema::ImplicitExceptionSpecification
5981Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005982 // C++ [except.spec]p14:
5983 // An implicitly declared special member function (Clause 12) shall have an
5984 // exception-specification. [...]
5985 ImplicitExceptionSpecification ExceptSpec(Context);
5986
Sebastian Redl60618fa2011-03-12 11:50:43 +00005987 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00005988 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5989 BEnd = ClassDecl->bases_end();
5990 B != BEnd; ++B) {
5991 if (B->isVirtual()) // Handled below.
5992 continue;
5993
Douglas Gregor18274032010-07-03 00:47:00 +00005994 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5995 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00005996 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5997 // If this is a deleted function, add it anyway. This might be conformant
5998 // with the standard. This might not. I'm not sure. It might not matter.
5999 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006000 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006001 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006002 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006003
6004 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006005 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6006 BEnd = ClassDecl->vbases_end();
6007 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006008 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6009 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006010 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6011 // If this is a deleted function, add it anyway. This might be conformant
6012 // with the standard. This might not. I'm not sure. It might not matter.
6013 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006014 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006015 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006016 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006017
6018 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006019 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6020 FEnd = ClassDecl->field_end();
6021 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006022 if (F->hasInClassInitializer()) {
6023 if (Expr *E = F->getInClassInitializer())
6024 ExceptSpec.CalledExpr(E);
6025 else if (!F->isInvalidDecl())
6026 ExceptSpec.SetDelayed();
6027 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006028 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006029 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6030 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6031 // If this is a deleted function, add it anyway. This might be conformant
6032 // with the standard. This might not. I'm not sure. It might not matter.
6033 // In particular, the problem is that this function never gets called. It
6034 // might just be ill-formed because this function attempts to refer to
6035 // a deleted function here.
6036 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006037 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006038 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006039 }
John McCalle23cf432010-12-14 08:05:40 +00006040
Sean Hunt001cad92011-05-10 00:49:42 +00006041 return ExceptSpec;
6042}
6043
6044CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6045 CXXRecordDecl *ClassDecl) {
6046 // C++ [class.ctor]p5:
6047 // A default constructor for a class X is a constructor of class X
6048 // that can be called without an argument. If there is no
6049 // user-declared constructor for class X, a default constructor is
6050 // implicitly declared. An implicitly-declared default constructor
6051 // is an inline public member of its class.
6052 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6053 "Should not build implicit default constructor!");
6054
6055 ImplicitExceptionSpecification Spec =
6056 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6057 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00006058
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006059 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006060 CanQualType ClassType
6061 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006062 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006063 DeclarationName Name
6064 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006065 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006066 CXXConstructorDecl *DefaultCon
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006067 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00006068 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00006069 0, 0, EPI),
Douglas Gregor32df23e2010-07-01 22:02:46 +00006070 /*TInfo=*/0,
6071 /*isExplicit=*/false,
6072 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006073 /*isImplicitlyDeclared=*/true);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006074 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006075 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006076 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006077 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00006078
6079 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006080 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6081
Douglas Gregor23c94db2010-07-02 17:43:08 +00006082 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006083 PushOnScopeChains(DefaultCon, S, false);
6084 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006085
6086 if (ShouldDeleteDefaultConstructor(DefaultCon))
6087 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006088
Douglas Gregor32df23e2010-07-01 22:02:46 +00006089 return DefaultCon;
6090}
6091
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006092void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6093 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006094 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006095 !Constructor->doesThisDeclarationHaveABody() &&
6096 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006097 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006098
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006099 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006100 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006101
Douglas Gregor39957dc2010-05-01 15:04:51 +00006102 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006103 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006104 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006105 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006106 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006107 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006108 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006109 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006110 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006111
6112 SourceLocation Loc = Constructor->getLocation();
6113 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6114
6115 Constructor->setUsed();
6116 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006117
6118 if (ASTMutationListener *L = getASTMutationListener()) {
6119 L->CompletedImplicitDefinition(Constructor);
6120 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006121}
6122
Richard Smith7a614d82011-06-11 17:19:42 +00006123/// Get any existing defaulted default constructor for the given class. Do not
6124/// implicitly define one if it does not exist.
6125static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6126 CXXRecordDecl *D) {
6127 ASTContext &Context = Self.Context;
6128 QualType ClassType = Context.getTypeDeclType(D);
6129 DeclarationName ConstructorName
6130 = Context.DeclarationNames.getCXXConstructorName(
6131 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6132
6133 DeclContext::lookup_const_iterator Con, ConEnd;
6134 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6135 Con != ConEnd; ++Con) {
6136 // A function template cannot be defaulted.
6137 if (isa<FunctionTemplateDecl>(*Con))
6138 continue;
6139
6140 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6141 if (Constructor->isDefaultConstructor())
6142 return Constructor->isDefaulted() ? Constructor : 0;
6143 }
6144 return 0;
6145}
6146
6147void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6148 if (!D) return;
6149 AdjustDeclIfTemplate(D);
6150
6151 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6152 CXXConstructorDecl *CtorDecl
6153 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6154
6155 if (!CtorDecl) return;
6156
6157 // Compute the exception specification for the default constructor.
6158 const FunctionProtoType *CtorTy =
6159 CtorDecl->getType()->castAs<FunctionProtoType>();
6160 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6161 ImplicitExceptionSpecification Spec =
6162 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6163 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6164 assert(EPI.ExceptionSpecType != EST_Delayed);
6165
6166 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6167 }
6168
6169 // If the default constructor is explicitly defaulted, checking the exception
6170 // specification is deferred until now.
6171 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6172 !ClassDecl->isDependentType())
6173 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6174}
6175
Sebastian Redlf677ea32011-02-05 19:23:19 +00006176void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6177 // We start with an initial pass over the base classes to collect those that
6178 // inherit constructors from. If there are none, we can forgo all further
6179 // processing.
6180 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6181 BasesVector BasesToInheritFrom;
6182 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6183 BaseE = ClassDecl->bases_end();
6184 BaseIt != BaseE; ++BaseIt) {
6185 if (BaseIt->getInheritConstructors()) {
6186 QualType Base = BaseIt->getType();
6187 if (Base->isDependentType()) {
6188 // If we inherit constructors from anything that is dependent, just
6189 // abort processing altogether. We'll get another chance for the
6190 // instantiations.
6191 return;
6192 }
6193 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6194 }
6195 }
6196 if (BasesToInheritFrom.empty())
6197 return;
6198
6199 // Now collect the constructors that we already have in the current class.
6200 // Those take precedence over inherited constructors.
6201 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6202 // unless there is a user-declared constructor with the same signature in
6203 // the class where the using-declaration appears.
6204 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6205 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6206 CtorE = ClassDecl->ctor_end();
6207 CtorIt != CtorE; ++CtorIt) {
6208 ExistingConstructors.insert(
6209 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6210 }
6211
6212 Scope *S = getScopeForContext(ClassDecl);
6213 DeclarationName CreatedCtorName =
6214 Context.DeclarationNames.getCXXConstructorName(
6215 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6216
6217 // Now comes the true work.
6218 // First, we keep a map from constructor types to the base that introduced
6219 // them. Needed for finding conflicting constructors. We also keep the
6220 // actually inserted declarations in there, for pretty diagnostics.
6221 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6222 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6223 ConstructorToSourceMap InheritedConstructors;
6224 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6225 BaseE = BasesToInheritFrom.end();
6226 BaseIt != BaseE; ++BaseIt) {
6227 const RecordType *Base = *BaseIt;
6228 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6229 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6230 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6231 CtorE = BaseDecl->ctor_end();
6232 CtorIt != CtorE; ++CtorIt) {
6233 // Find the using declaration for inheriting this base's constructors.
6234 DeclarationName Name =
6235 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6236 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6237 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6238 SourceLocation UsingLoc = UD ? UD->getLocation() :
6239 ClassDecl->getLocation();
6240
6241 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6242 // from the class X named in the using-declaration consists of actual
6243 // constructors and notional constructors that result from the
6244 // transformation of defaulted parameters as follows:
6245 // - all non-template default constructors of X, and
6246 // - for each non-template constructor of X that has at least one
6247 // parameter with a default argument, the set of constructors that
6248 // results from omitting any ellipsis parameter specification and
6249 // successively omitting parameters with a default argument from the
6250 // end of the parameter-type-list.
6251 CXXConstructorDecl *BaseCtor = *CtorIt;
6252 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6253 const FunctionProtoType *BaseCtorType =
6254 BaseCtor->getType()->getAs<FunctionProtoType>();
6255
6256 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6257 maxParams = BaseCtor->getNumParams();
6258 params <= maxParams; ++params) {
6259 // Skip default constructors. They're never inherited.
6260 if (params == 0)
6261 continue;
6262 // Skip copy and move constructors for the same reason.
6263 if (CanBeCopyOrMove && params == 1)
6264 continue;
6265
6266 // Build up a function type for this particular constructor.
6267 // FIXME: The working paper does not consider that the exception spec
6268 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006269 // source. This code doesn't yet, either. When it does, this code will
6270 // need to be delayed until after exception specifications and in-class
6271 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006272 const Type *NewCtorType;
6273 if (params == maxParams)
6274 NewCtorType = BaseCtorType;
6275 else {
6276 llvm::SmallVector<QualType, 16> Args;
6277 for (unsigned i = 0; i < params; ++i) {
6278 Args.push_back(BaseCtorType->getArgType(i));
6279 }
6280 FunctionProtoType::ExtProtoInfo ExtInfo =
6281 BaseCtorType->getExtProtoInfo();
6282 ExtInfo.Variadic = false;
6283 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6284 Args.data(), params, ExtInfo)
6285 .getTypePtr();
6286 }
6287 const Type *CanonicalNewCtorType =
6288 Context.getCanonicalType(NewCtorType);
6289
6290 // Now that we have the type, first check if the class already has a
6291 // constructor with this signature.
6292 if (ExistingConstructors.count(CanonicalNewCtorType))
6293 continue;
6294
6295 // Then we check if we have already declared an inherited constructor
6296 // with this signature.
6297 std::pair<ConstructorToSourceMap::iterator, bool> result =
6298 InheritedConstructors.insert(std::make_pair(
6299 CanonicalNewCtorType,
6300 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6301 if (!result.second) {
6302 // Already in the map. If it came from a different class, that's an
6303 // error. Not if it's from the same.
6304 CanQualType PreviousBase = result.first->second.first;
6305 if (CanonicalBase != PreviousBase) {
6306 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6307 const CXXConstructorDecl *PrevBaseCtor =
6308 PrevCtor->getInheritedConstructor();
6309 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6310
6311 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6312 Diag(BaseCtor->getLocation(),
6313 diag::note_using_decl_constructor_conflict_current_ctor);
6314 Diag(PrevBaseCtor->getLocation(),
6315 diag::note_using_decl_constructor_conflict_previous_ctor);
6316 Diag(PrevCtor->getLocation(),
6317 diag::note_using_decl_constructor_conflict_previous_using);
6318 }
6319 continue;
6320 }
6321
6322 // OK, we're there, now add the constructor.
6323 // C++0x [class.inhctor]p8: [...] that would be performed by a
6324 // user-writtern inline constructor [...]
6325 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6326 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006327 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6328 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00006329 /*ImplicitlyDeclared=*/true);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006330 NewCtor->setAccess(BaseCtor->getAccess());
6331
6332 // Build up the parameter decls and add them.
6333 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6334 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006335 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6336 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006337 /*IdentifierInfo=*/0,
6338 BaseCtorType->getArgType(i),
6339 /*TInfo=*/0, SC_None,
6340 SC_None, /*DefaultArg=*/0));
6341 }
6342 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6343 NewCtor->setInheritedConstructor(BaseCtor);
6344
6345 PushOnScopeChains(NewCtor, S, false);
6346 ClassDecl->addDecl(NewCtor);
6347 result.first->second.second = NewCtor;
6348 }
6349 }
6350 }
6351}
6352
Sean Huntcb45a0f2011-05-12 22:46:25 +00006353Sema::ImplicitExceptionSpecification
6354Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006355 // C++ [except.spec]p14:
6356 // An implicitly declared special member function (Clause 12) shall have
6357 // an exception-specification.
6358 ImplicitExceptionSpecification ExceptSpec(Context);
6359
6360 // Direct base-class destructors.
6361 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6362 BEnd = ClassDecl->bases_end();
6363 B != BEnd; ++B) {
6364 if (B->isVirtual()) // Handled below.
6365 continue;
6366
6367 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6368 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006369 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006370 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006371
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006372 // Virtual base-class destructors.
6373 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6374 BEnd = ClassDecl->vbases_end();
6375 B != BEnd; ++B) {
6376 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6377 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006378 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006379 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00006380
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006381 // Field destructors.
6382 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6383 FEnd = ClassDecl->field_end();
6384 F != FEnd; ++F) {
6385 if (const RecordType *RecordTy
6386 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6387 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00006388 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006389 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006390
Sean Huntcb45a0f2011-05-12 22:46:25 +00006391 return ExceptSpec;
6392}
6393
6394CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6395 // C++ [class.dtor]p2:
6396 // If a class has no user-declared destructor, a destructor is
6397 // declared implicitly. An implicitly-declared destructor is an
6398 // inline public member of its class.
6399
6400 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00006401 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006402 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6403
Douglas Gregor4923aa22010-07-02 20:37:36 +00006404 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00006405 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00006406
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006407 CanQualType ClassType
6408 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006409 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006410 DeclarationName Name
6411 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006412 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006413 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00006414 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6415 /*isInline=*/true,
6416 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006417 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00006418 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006419 Destructor->setImplicit();
6420 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00006421
6422 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00006423 ++ASTContext::NumImplicitDestructorsDeclared;
6424
6425 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006426 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00006427 PushOnScopeChains(Destructor, S, false);
6428 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006429
6430 // This could be uniqued if it ever proves significant.
6431 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00006432
6433 if (ShouldDeleteDestructor(Destructor))
6434 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006435
6436 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00006437
Douglas Gregorfabd43a2010-07-01 19:09:28 +00006438 return Destructor;
6439}
6440
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006441void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00006442 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00006443 assert((Destructor->isDefaulted() &&
6444 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006445 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00006446 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006447 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006448
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006449 if (Destructor->isInvalidDecl())
6450 return;
6451
Douglas Gregor39957dc2010-05-01 15:04:51 +00006452 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00006453
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006454 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00006455 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6456 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00006457
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006458 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006459 Diag(CurrentLocation, diag::note_member_synthesized_at)
6460 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6461
6462 Destructor->setInvalidDecl();
6463 return;
6464 }
6465
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006466 SourceLocation Loc = Destructor->getLocation();
6467 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6468
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006469 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006470 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006471
6472 if (ASTMutationListener *L = getASTMutationListener()) {
6473 L->CompletedImplicitDefinition(Destructor);
6474 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006475}
6476
Sebastian Redl0ee33912011-05-19 05:13:44 +00006477void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6478 CXXDestructorDecl *destructor) {
6479 // C++11 [class.dtor]p3:
6480 // A declaration of a destructor that does not have an exception-
6481 // specification is implicitly considered to have the same exception-
6482 // specification as an implicit declaration.
6483 const FunctionProtoType *dtorType = destructor->getType()->
6484 getAs<FunctionProtoType>();
6485 if (dtorType->hasExceptionSpec())
6486 return;
6487
6488 ImplicitExceptionSpecification exceptSpec =
6489 ComputeDefaultedDtorExceptionSpec(classDecl);
6490
6491 // Replace the destructor's type.
6492 FunctionProtoType::ExtProtoInfo epi;
6493 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6494 epi.NumExceptions = exceptSpec.size();
6495 epi.Exceptions = exceptSpec.data();
6496 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6497
6498 destructor->setType(ty);
6499
6500 // FIXME: If the destructor has a body that could throw, and the newly created
6501 // spec doesn't allow exceptions, we should emit a warning, because this
6502 // change in behavior can break conforming C++03 programs at runtime.
6503 // However, we don't have a body yet, so it needs to be done somewhere else.
6504}
6505
Douglas Gregor06a9f362010-05-01 20:49:11 +00006506/// \brief Builds a statement that copies the given entity from \p From to
6507/// \c To.
6508///
6509/// This routine is used to copy the members of a class with an
6510/// implicitly-declared copy assignment operator. When the entities being
6511/// copied are arrays, this routine builds for loops to copy them.
6512///
6513/// \param S The Sema object used for type-checking.
6514///
6515/// \param Loc The location where the implicit copy is being generated.
6516///
6517/// \param T The type of the expressions being copied. Both expressions must
6518/// have this type.
6519///
6520/// \param To The expression we are copying to.
6521///
6522/// \param From The expression we are copying from.
6523///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006524/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6525/// Otherwise, it's a non-static member subobject.
6526///
Douglas Gregor06a9f362010-05-01 20:49:11 +00006527/// \param Depth Internal parameter recording the depth of the recursion.
6528///
6529/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00006530static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00006531BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00006532 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006533 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006534 // C++0x [class.copy]p30:
6535 // Each subobject is assigned in the manner appropriate to its type:
6536 //
6537 // - if the subobject is of class type, the copy assignment operator
6538 // for the class is used (as if by explicit qualification; that is,
6539 // ignoring any possible virtual overriding functions in more derived
6540 // classes);
6541 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6542 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6543
6544 // Look for operator=.
6545 DeclarationName Name
6546 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6547 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6548 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6549
6550 // Filter out any result that isn't a copy-assignment operator.
6551 LookupResult::Filter F = OpLookup.makeFilter();
6552 while (F.hasNext()) {
6553 NamedDecl *D = F.next();
6554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6555 if (Method->isCopyAssignmentOperator())
6556 continue;
6557
6558 F.erase();
John McCallb0207482010-03-16 06:11:48 +00006559 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006560 F.done();
6561
Douglas Gregor6cdc1612010-05-04 15:20:55 +00006562 // Suppress the protected check (C++ [class.protected]) for each of the
6563 // assignment operators we found. This strange dance is required when
6564 // we're assigning via a base classes's copy-assignment operator. To
6565 // ensure that we're getting the right base class subobject (without
6566 // ambiguities), we need to cast "this" to that subobject type; to
6567 // ensure that we don't go through the virtual call mechanism, we need
6568 // to qualify the operator= name with the base class (see below). However,
6569 // this means that if the base class has a protected copy assignment
6570 // operator, the protected member access check will fail. So, we
6571 // rewrite "protected" access to "public" access in this case, since we
6572 // know by construction that we're calling from a derived class.
6573 if (CopyingBaseSubobject) {
6574 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6575 L != LEnd; ++L) {
6576 if (L.getAccess() == AS_protected)
6577 L.setAccess(AS_public);
6578 }
6579 }
6580
Douglas Gregor06a9f362010-05-01 20:49:11 +00006581 // Create the nested-name-specifier that will be used to qualify the
6582 // reference to operator=; this is required to suppress the virtual
6583 // call mechanism.
6584 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00006585 SS.MakeTrivial(S.Context,
6586 NestedNameSpecifier::Create(S.Context, 0, false,
6587 T.getTypePtr()),
6588 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006589
6590 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00006591 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00006592 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006593 /*FirstQualifierInScope=*/0, OpLookup,
6594 /*TemplateArgs=*/0,
6595 /*SuppressQualifierCheck=*/true);
6596 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006597 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006598
6599 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00006600
John McCall60d7b3a2010-08-24 06:29:42 +00006601 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00006602 OpEqualRef.takeAs<Expr>(),
6603 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006604 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006605 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006606
6607 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006608 }
John McCallb0207482010-03-16 06:11:48 +00006609
Douglas Gregor06a9f362010-05-01 20:49:11 +00006610 // - if the subobject is of scalar type, the built-in assignment
6611 // operator is used.
6612 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6613 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00006614 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006615 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006616 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006617
6618 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006619 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00006620
6621 // - if the subobject is an array, each element is assigned, in the
6622 // manner appropriate to the element type;
6623
6624 // Construct a loop over the array bounds, e.g.,
6625 //
6626 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6627 //
6628 // that will copy each of the array elements.
6629 QualType SizeType = S.Context.getSizeType();
6630
6631 // Create the iteration variable.
6632 IdentifierInfo *IterationVarName = 0;
6633 {
6634 llvm::SmallString<8> Str;
6635 llvm::raw_svector_ostream OS(Str);
6636 OS << "__i" << Depth;
6637 IterationVarName = &S.Context.Idents.get(OS.str());
6638 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006639 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006640 IterationVarName, SizeType,
6641 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00006642 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006643
6644 // Initialize the iteration variable to zero.
6645 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006646 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006647
6648 // Create a reference to the iteration variable; we'll use this several
6649 // times throughout.
6650 Expr *IterationVarRef
John McCallf89e55a2010-11-18 06:31:45 +00006651 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006652 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6653
6654 // Create the DeclStmt that holds the iteration variable.
6655 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6656
6657 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00006658 llvm::APInt Upper
6659 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00006660 Expr *Comparison
John McCall3fa5cae2010-10-26 07:05:15 +00006661 = new (S.Context) BinaryOperator(IterationVarRef,
John McCallf89e55a2010-11-18 06:31:45 +00006662 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6663 BO_NE, S.Context.BoolTy,
6664 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006665
6666 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006667 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00006668 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6669 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006670
6671 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00006672 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6673 IterationVarRef, Loc));
6674 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6675 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00006676
6677 // Build the copy for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00006678 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6679 To, From, CopyingBaseSubobject,
6680 Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00006681 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006682 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006683
6684 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00006685 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00006686 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00006687 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00006688 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006689}
6690
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006691/// \brief Determine whether the given class has a copy assignment operator
6692/// that accepts a const-qualified argument.
6693static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6694 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6695
6696 if (!Class->hasDeclaredCopyAssignment())
6697 S.DeclareImplicitCopyAssignment(Class);
6698
6699 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6700 DeclarationName OpName
6701 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6702
6703 DeclContext::lookup_const_iterator Op, OpEnd;
6704 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6705 // C++ [class.copy]p9:
6706 // A user-declared copy assignment operator is a non-static non-template
6707 // member function of class X with exactly one parameter of type X, X&,
6708 // const X&, volatile X& or const volatile X&.
6709 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6710 if (!Method)
6711 continue;
6712
6713 if (Method->isStatic())
6714 continue;
6715 if (Method->getPrimaryTemplate())
6716 continue;
6717 const FunctionProtoType *FnType =
6718 Method->getType()->getAs<FunctionProtoType>();
6719 assert(FnType && "Overloaded operator has no prototype.");
6720 // Don't assert on this; an invalid decl might have been left in the AST.
6721 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6722 continue;
6723 bool AcceptsConst = true;
6724 QualType ArgType = FnType->getArgType(0);
6725 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6726 ArgType = Ref->getPointeeType();
6727 // Is it a non-const lvalue reference?
6728 if (!ArgType.isConstQualified())
6729 AcceptsConst = false;
6730 }
6731 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6732 continue;
6733
6734 // We have a single argument of type cv X or cv X&, i.e. we've found the
6735 // copy assignment operator. Return whether it accepts const arguments.
6736 return AcceptsConst;
6737 }
6738 assert(Class->isInvalidDecl() &&
6739 "No copy assignment operator declared in valid code.");
6740 return false;
6741}
6742
Sean Hunt30de05c2011-05-14 05:23:20 +00006743std::pair<Sema::ImplicitExceptionSpecification, bool>
6744Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6745 CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00006746 // C++ [class.copy]p10:
6747 // If the class definition does not explicitly declare a copy
6748 // assignment operator, one is declared implicitly.
6749 // The implicitly-defined copy assignment operator for a class X
6750 // will have the form
6751 //
6752 // X& X::operator=(const X&)
6753 //
6754 // if
6755 bool HasConstCopyAssignment = true;
6756
6757 // -- each direct base class B of X has a copy assignment operator
6758 // whose parameter is of type const B&, const volatile B& or B,
6759 // and
6760 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6761 BaseEnd = ClassDecl->bases_end();
6762 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6763 assert(!Base->getType()->isDependentType() &&
6764 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006765 const CXXRecordDecl *BaseClassDecl
6766 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6767 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006768 }
6769
6770 // -- for all the nonstatic data members of X that are of a class
6771 // type M (or array thereof), each such class type has a copy
6772 // assignment operator whose parameter is of type const M&,
6773 // const volatile M& or M.
6774 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6775 FieldEnd = ClassDecl->field_end();
6776 HasConstCopyAssignment && Field != FieldEnd;
6777 ++Field) {
6778 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006779 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6780 const CXXRecordDecl *FieldClassDecl
6781 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6782 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00006783 }
6784 }
6785
6786 // Otherwise, the implicitly declared copy assignment operator will
6787 // have the form
6788 //
6789 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00006790
Douglas Gregorb87786f2010-07-01 17:48:08 +00006791 // C++ [except.spec]p14:
6792 // An implicitly declared special member function (Clause 12) shall have an
6793 // exception-specification. [...]
6794 ImplicitExceptionSpecification ExceptSpec(Context);
6795 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6796 BaseEnd = ClassDecl->bases_end();
6797 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00006798 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00006799 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006800
6801 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6802 DeclareImplicitCopyAssignment(BaseClassDecl);
6803
6804 if (CXXMethodDecl *CopyAssign
6805 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
Douglas Gregorb87786f2010-07-01 17:48:08 +00006806 ExceptSpec.CalledDecl(CopyAssign);
6807 }
6808 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6809 FieldEnd = ClassDecl->field_end();
6810 Field != FieldEnd;
6811 ++Field) {
6812 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00006813 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6814 CXXRecordDecl *FieldClassDecl
6815 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6816
6817 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6818 DeclareImplicitCopyAssignment(FieldClassDecl);
6819
6820 if (CXXMethodDecl *CopyAssign
6821 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6822 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00006823 }
6824 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006825
Sean Hunt30de05c2011-05-14 05:23:20 +00006826 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6827}
6828
6829CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6830 // Note: The following rules are largely analoguous to the copy
6831 // constructor rules. Note that virtual bases are not taken into account
6832 // for determining the argument type of the operator. Note also that
6833 // operators taking an object instead of a reference are allowed.
6834
6835 ImplicitExceptionSpecification Spec(Context);
6836 bool Const;
6837 llvm::tie(Spec, Const) =
6838 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6839
6840 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6841 QualType RetType = Context.getLValueReferenceType(ArgType);
6842 if (Const)
6843 ArgType = ArgType.withConst();
6844 ArgType = Context.getLValueReferenceType(ArgType);
6845
Douglas Gregord3c35902010-07-01 16:36:15 +00006846 // An implicitly-declared copy assignment operator is an inline public
6847 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00006848 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00006849 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006850 SourceLocation ClassLoc = ClassDecl->getLocation();
6851 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00006852 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006853 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00006854 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00006855 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00006856 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf5251602011-03-08 17:10:18 +00006857 /*isInline=*/true,
6858 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00006859 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00006860 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00006861 CopyAssignment->setImplicit();
6862 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00006863
6864 // Add the parameter to the operator.
6865 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006866 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00006867 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00006868 SC_None,
6869 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00006870 CopyAssignment->setParams(&FromParam, 1);
6871
Douglas Gregora376d102010-07-02 21:50:04 +00006872 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00006873 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00006874
Douglas Gregor23c94db2010-07-02 17:43:08 +00006875 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00006876 PushOnScopeChains(CopyAssignment, S, false);
6877 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00006878
Sean Hunt71a682f2011-05-18 03:41:58 +00006879 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6880 CopyAssignment->setDeletedAsWritten();
6881
Douglas Gregord3c35902010-07-01 16:36:15 +00006882 AddOverriddenMethods(ClassDecl, CopyAssignment);
6883 return CopyAssignment;
6884}
6885
Douglas Gregor06a9f362010-05-01 20:49:11 +00006886void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6887 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00006888 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006889 CopyAssignOperator->isOverloadedOperator() &&
6890 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006891 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00006892 "DefineImplicitCopyAssignment called for wrong function");
6893
6894 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6895
6896 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6897 CopyAssignOperator->setInvalidDecl();
6898 return;
6899 }
6900
6901 CopyAssignOperator->setUsed();
6902
6903 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006904 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006905
6906 // C++0x [class.copy]p30:
6907 // The implicitly-defined or explicitly-defaulted copy assignment operator
6908 // for a non-union class X performs memberwise copy assignment of its
6909 // subobjects. The direct base classes of X are assigned first, in the
6910 // order of their declaration in the base-specifier-list, and then the
6911 // immediate non-static data members of X are assigned, in the order in
6912 // which they were declared in the class definition.
6913
6914 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00006915 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006916
6917 // The parameter for the "other" object, which we are copying from.
6918 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6919 Qualifiers OtherQuals = Other->getType().getQualifiers();
6920 QualType OtherRefType = Other->getType();
6921 if (const LValueReferenceType *OtherRef
6922 = OtherRefType->getAs<LValueReferenceType>()) {
6923 OtherRefType = OtherRef->getPointeeType();
6924 OtherQuals = OtherRefType.getQualifiers();
6925 }
6926
6927 // Our location for everything implicitly-generated.
6928 SourceLocation Loc = CopyAssignOperator->getLocation();
6929
6930 // Construct a reference to the "other" object. We'll be using this
6931 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00006932 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006933 assert(OtherRef && "Reference to parameter cannot fail!");
6934
6935 // Construct the "this" pointer. We'll be using this throughout the generated
6936 // ASTs.
6937 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6938 assert(This && "Reference to this cannot fail!");
6939
6940 // Assign base classes.
6941 bool Invalid = false;
6942 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6943 E = ClassDecl->bases_end(); Base != E; ++Base) {
6944 // Form the assignment:
6945 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6946 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00006947 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00006948 Invalid = true;
6949 continue;
6950 }
6951
John McCallf871d0c2010-08-07 06:22:56 +00006952 CXXCastPath BasePath;
6953 BasePath.push_back(Base);
6954
Douglas Gregor06a9f362010-05-01 20:49:11 +00006955 // Construct the "from" expression, which is an implicit cast to the
6956 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00006957 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00006958 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6959 CK_UncheckedDerivedToBase,
6960 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00006961
6962 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00006963 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006964
6965 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00006966 To = ImpCastExprToType(To.take(),
6967 Context.getCVRQualifiedType(BaseType,
6968 CopyAssignOperator->getTypeQualifiers()),
6969 CK_UncheckedDerivedToBase,
6970 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006971
6972 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00006973 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00006974 To.get(), From,
6975 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00006976 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00006977 Diag(CurrentLocation, diag::note_member_synthesized_at)
6978 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6979 CopyAssignOperator->setInvalidDecl();
6980 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006981 }
6982
6983 // Success! Record the copy.
6984 Statements.push_back(Copy.takeAs<Expr>());
6985 }
6986
6987 // \brief Reference to the __builtin_memcpy function.
6988 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00006989 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006990 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00006991
6992 // Assign non-static members.
6993 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6994 FieldEnd = ClassDecl->field_end();
6995 Field != FieldEnd; ++Field) {
6996 // Check for members of reference type; we can't copy those.
6997 if (Field->getType()->isReferenceType()) {
6998 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6999 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7000 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007001 Diag(CurrentLocation, diag::note_member_synthesized_at)
7002 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007003 Invalid = true;
7004 continue;
7005 }
7006
7007 // Check for members of const-qualified, non-class type.
7008 QualType BaseType = Context.getBaseElementType(Field->getType());
7009 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7010 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7011 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7012 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007013 Diag(CurrentLocation, diag::note_member_synthesized_at)
7014 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007015 Invalid = true;
7016 continue;
7017 }
John McCallb77115d2011-06-17 00:18:42 +00007018
7019 // Suppress assigning zero-width bitfields.
7020 if (const Expr *Width = Field->getBitWidth())
7021 if (Width->EvaluateAsInt(Context) == 0)
7022 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007023
7024 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007025 if (FieldType->isIncompleteArrayType()) {
7026 assert(ClassDecl->hasFlexibleArrayMember() &&
7027 "Incomplete array type is not valid");
7028 continue;
7029 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007030
7031 // Build references to the field in the object we're copying from and to.
7032 CXXScopeSpec SS; // Intentionally empty
7033 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7034 LookupMemberName);
7035 MemberLookup.addDecl(*Field);
7036 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007037 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007038 Loc, /*IsArrow=*/false,
7039 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007040 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007041 Loc, /*IsArrow=*/true,
7042 SS, 0, MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007043 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7044 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7045
7046 // If the field should be copied with __builtin_memcpy rather than via
7047 // explicit assignments, do so. This optimization only applies for arrays
7048 // of scalars and arrays of class type with trivial copy-assignment
7049 // operators.
John McCallf85e1932011-06-15 23:02:42 +00007050 if (FieldType->isArrayType() &&
7051 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007052 // Compute the size of the memory buffer to be copied.
7053 QualType SizeType = Context.getSizeType();
7054 llvm::APInt Size(Context.getTypeSize(SizeType),
7055 Context.getTypeSizeInChars(BaseType).getQuantity());
7056 for (const ConstantArrayType *Array
7057 = Context.getAsConstantArrayType(FieldType);
7058 Array;
7059 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007060 llvm::APInt ArraySize
7061 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007062 Size *= ArraySize;
7063 }
7064
7065 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007066 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7067 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007068
7069 bool NeedsCollectableMemCpy =
7070 (BaseType->isRecordType() &&
7071 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7072
7073 if (NeedsCollectableMemCpy) {
7074 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007075 // Create a reference to the __builtin_objc_memmove_collectable function.
7076 LookupResult R(*this,
7077 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007078 Loc, LookupOrdinaryName);
7079 LookupName(R, TUScope, true);
7080
7081 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7082 if (!CollectableMemCpy) {
7083 // Something went horribly wrong earlier, and we will have
7084 // complained about it.
7085 Invalid = true;
7086 continue;
7087 }
7088
7089 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7090 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007091 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007092 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7093 }
7094 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007095 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007096 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007097 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7098 LookupOrdinaryName);
7099 LookupName(R, TUScope, true);
7100
7101 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7102 if (!BuiltinMemCpy) {
7103 // Something went horribly wrong earlier, and we will have complained
7104 // about it.
7105 Invalid = true;
7106 continue;
7107 }
7108
7109 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7110 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007111 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007112 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7113 }
7114
John McCallca0408f2010-08-23 06:44:23 +00007115 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007116 CallArgs.push_back(To.takeAs<Expr>());
7117 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007118 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007119 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007120 if (NeedsCollectableMemCpy)
7121 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007122 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007123 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007124 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007125 else
7126 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007127 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007128 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007129 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007130
Douglas Gregor06a9f362010-05-01 20:49:11 +00007131 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7132 Statements.push_back(Call.takeAs<Expr>());
7133 continue;
7134 }
7135
7136 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007137 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00007138 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007139 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007140 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007141 Diag(CurrentLocation, diag::note_member_synthesized_at)
7142 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7143 CopyAssignOperator->setInvalidDecl();
7144 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007145 }
7146
7147 // Success! Record the copy.
7148 Statements.push_back(Copy.takeAs<Stmt>());
7149 }
7150
7151 if (!Invalid) {
7152 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007153 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007154
John McCall60d7b3a2010-08-24 06:29:42 +00007155 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007156 if (Return.isInvalid())
7157 Invalid = true;
7158 else {
7159 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007160
7161 if (Trap.hasErrorOccurred()) {
7162 Diag(CurrentLocation, diag::note_member_synthesized_at)
7163 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7164 Invalid = true;
7165 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007166 }
7167 }
7168
7169 if (Invalid) {
7170 CopyAssignOperator->setInvalidDecl();
7171 return;
7172 }
7173
John McCall60d7b3a2010-08-24 06:29:42 +00007174 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00007175 /*isStmtExpr=*/false);
7176 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7177 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007178
7179 if (ASTMutationListener *L = getASTMutationListener()) {
7180 L->CompletedImplicitDefinition(CopyAssignOperator);
7181 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007182}
7183
Sean Hunt49634cf2011-05-13 06:10:58 +00007184std::pair<Sema::ImplicitExceptionSpecification, bool>
7185Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007186 // C++ [class.copy]p5:
7187 // The implicitly-declared copy constructor for a class X will
7188 // have the form
7189 //
7190 // X::X(const X&)
7191 //
7192 // if
Sean Huntc530d172011-06-10 04:44:37 +00007193 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007194 bool HasConstCopyConstructor = true;
7195
7196 // -- each direct or virtual base class B of X has a copy
7197 // constructor whose first parameter is of type const B& or
7198 // const volatile B&, and
7199 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7200 BaseEnd = ClassDecl->bases_end();
7201 HasConstCopyConstructor && Base != BaseEnd;
7202 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007203 // Virtual bases are handled below.
7204 if (Base->isVirtual())
7205 continue;
7206
Douglas Gregor22584312010-07-02 23:41:54 +00007207 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00007208 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007209 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7210 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00007211 }
7212
7213 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7214 BaseEnd = ClassDecl->vbases_end();
7215 HasConstCopyConstructor && Base != BaseEnd;
7216 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007217 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007218 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007219 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7220 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007221 }
7222
7223 // -- for all the nonstatic data members of X that are of a
7224 // class type M (or array thereof), each such class type
7225 // has a copy constructor whose first parameter is of type
7226 // const M& or const volatile M&.
7227 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7228 FieldEnd = ClassDecl->field_end();
7229 HasConstCopyConstructor && Field != FieldEnd;
7230 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00007231 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007232 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007233 LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7234 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007235 }
7236 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007237 // Otherwise, the implicitly declared copy constructor will have
7238 // the form
7239 //
7240 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00007241
Douglas Gregor0d405db2010-07-01 20:59:04 +00007242 // C++ [except.spec]p14:
7243 // An implicitly declared special member function (Clause 12) shall have an
7244 // exception-specification. [...]
7245 ImplicitExceptionSpecification ExceptSpec(Context);
7246 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7247 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7248 BaseEnd = ClassDecl->bases_end();
7249 Base != BaseEnd;
7250 ++Base) {
7251 // Virtual bases are handled below.
7252 if (Base->isVirtual())
7253 continue;
7254
Douglas Gregor22584312010-07-02 23:41:54 +00007255 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007256 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007257 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007258 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007259 ExceptSpec.CalledDecl(CopyConstructor);
7260 }
7261 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7262 BaseEnd = ClassDecl->vbases_end();
7263 Base != BaseEnd;
7264 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00007265 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00007266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00007267 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007268 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00007269 ExceptSpec.CalledDecl(CopyConstructor);
7270 }
7271 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7272 FieldEnd = ClassDecl->field_end();
7273 Field != FieldEnd;
7274 ++Field) {
7275 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00007276 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7277 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt3bde0ce2011-06-10 12:07:09 +00007278 LookupCopyConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00007279 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00007280 }
7281 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007282
Sean Hunt49634cf2011-05-13 06:10:58 +00007283 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7284}
7285
7286CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7287 CXXRecordDecl *ClassDecl) {
7288 // C++ [class.copy]p4:
7289 // If the class definition does not explicitly declare a copy
7290 // constructor, one is declared implicitly.
7291
7292 ImplicitExceptionSpecification Spec(Context);
7293 bool Const;
7294 llvm::tie(Spec, Const) =
7295 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7296
7297 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7298 QualType ArgType = ClassType;
7299 if (Const)
7300 ArgType = ArgType.withConst();
7301 ArgType = Context.getLValueReferenceType(ArgType);
7302
7303 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7304
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007305 DeclarationName Name
7306 = Context.DeclarationNames.getCXXConstructorName(
7307 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007308 SourceLocation ClassLoc = ClassDecl->getLocation();
7309 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00007310
7311 // An implicitly-declared copy constructor is an inline public
7312 // member of its class.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007313 CXXConstructorDecl *CopyConstructor
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007314 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007315 Context.getFunctionType(Context.VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00007316 &ArgType, 1, EPI),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007317 /*TInfo=*/0,
7318 /*isExplicit=*/false,
7319 /*isInline=*/true,
Sean Hunt5f802e52011-05-06 00:11:07 +00007320 /*isImplicitlyDeclared=*/true);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007321 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00007322 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007323 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7324
Douglas Gregor22584312010-07-02 23:41:54 +00007325 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00007326 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7327
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007328 // Add the parameter to the constructor.
7329 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007330 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007331 /*IdentifierInfo=*/0,
7332 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007333 SC_None,
7334 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007335 CopyConstructor->setParams(&FromParam, 1);
Sean Hunt49634cf2011-05-13 06:10:58 +00007336
Douglas Gregor23c94db2010-07-02 17:43:08 +00007337 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00007338 PushOnScopeChains(CopyConstructor, S, false);
7339 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00007340
7341 if (ShouldDeleteCopyConstructor(CopyConstructor))
7342 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00007343
7344 return CopyConstructor;
7345}
7346
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007347void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00007348 CXXConstructorDecl *CopyConstructor) {
7349 assert((CopyConstructor->isDefaulted() &&
7350 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007351 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007352 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007353
Anders Carlsson63010a72010-04-23 16:24:12 +00007354 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007355 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007356
Douglas Gregor39957dc2010-05-01 15:04:51 +00007357 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007358 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007359
Sean Huntcbb67482011-01-08 20:30:50 +00007360 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007361 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00007362 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007363 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00007364 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007365 } else {
7366 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7367 CopyConstructor->getLocation(),
7368 MultiStmtArg(*this, 0, 0),
7369 /*isStmtExpr=*/false)
7370 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00007371 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00007372
7373 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007374
7375 if (ASTMutationListener *L = getASTMutationListener()) {
7376 L->CompletedImplicitDefinition(CopyConstructor);
7377 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007378}
7379
John McCall60d7b3a2010-08-24 06:29:42 +00007380ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007381Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00007382 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00007383 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007384 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007385 unsigned ConstructKind,
7386 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007387 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00007388
Douglas Gregor2f599792010-04-02 18:24:57 +00007389 // C++0x [class.copy]p34:
7390 // When certain criteria are met, an implementation is allowed to
7391 // omit the copy/move construction of a class object, even if the
7392 // copy/move constructor and/or destructor for the object have
7393 // side effects. [...]
7394 // - when a temporary class object that has not been bound to a
7395 // reference (12.2) would be copied/moved to a class object
7396 // with the same cv-unqualified type, the copy/move operation
7397 // can be omitted by constructing the temporary object
7398 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00007399 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00007400 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00007401 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00007402 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007403 }
Mike Stump1eb44332009-09-09 15:08:12 +00007404
7405 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007406 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007407 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00007408}
7409
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007410/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7411/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007412ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00007413Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7414 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00007415 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007416 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007417 unsigned ConstructKind,
7418 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00007419 unsigned NumExprs = ExprArgs.size();
7420 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00007421
Nick Lewycky909a70d2011-03-25 01:44:32 +00007422 for (specific_attr_iterator<NonNullAttr>
7423 i = Constructor->specific_attr_begin<NonNullAttr>(),
7424 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7425 const NonNullAttr *NonNull = *i;
7426 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7427 }
7428
Douglas Gregor7edfb692009-11-23 12:27:39 +00007429 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00007430 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00007431 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00007432 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007433 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7434 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007435}
7436
Mike Stump1eb44332009-09-09 15:08:12 +00007437bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00007438 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00007439 MultiExprArg Exprs) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00007440 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00007441 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00007442 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth428edaf2010-10-25 08:47:36 +00007443 move(Exprs), false, CXXConstructExpr::CK_Complete,
7444 SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00007445 if (TempResult.isInvalid())
7446 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007447
Anders Carlssonda3f4e22009-08-25 05:12:04 +00007448 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00007449 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007450 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00007451 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00007452 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00007453
Anders Carlssonfe2de492009-08-25 05:18:00 +00007454 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00007455}
7456
John McCall68c6c9a2010-02-02 09:10:11 +00007457void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007458 if (VD->isInvalidDecl()) return;
7459
John McCall68c6c9a2010-02-02 09:10:11 +00007460 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007461 if (ClassDecl->isInvalidDecl()) return;
7462 if (ClassDecl->hasTrivialDestructor()) return;
7463 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00007464
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007465 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7466 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7467 CheckDestructorAccess(VD->getLocation(), Destructor,
7468 PDiag(diag::err_access_dtor_var)
7469 << VD->getDeclName()
7470 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00007471
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00007472 if (!VD->hasGlobalStorage()) return;
7473
7474 // Emit warning for non-trivial dtor in global scope (a real global,
7475 // class-static, function-static).
7476 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7477
7478 // TODO: this should be re-enabled for static locals by !CXAAtExit
7479 if (!VD->isStaticLocal())
7480 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007481}
7482
Mike Stump1eb44332009-09-09 15:08:12 +00007483/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007484/// ActOnDeclarator, when a C++ direct initializer is present.
7485/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00007486void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007487 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00007488 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00007489 SourceLocation RParenLoc,
7490 bool TypeMayContainAuto) {
Daniel Dunbar51846262009-12-24 19:19:26 +00007491 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007492
7493 // If there is no declaration, there was an error parsing it. Just ignore
7494 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00007495 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007496 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007497
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007498 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7499 if (!VDecl) {
7500 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7501 RealDecl->setInvalidDecl();
7502 return;
7503 }
7504
Richard Smith34b41d92011-02-20 03:19:35 +00007505 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7506 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith34b41d92011-02-20 03:19:35 +00007507 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7508 if (Exprs.size() > 1) {
7509 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7510 diag::err_auto_var_init_multiple_expressions)
7511 << VDecl->getDeclName() << VDecl->getType()
7512 << VDecl->getSourceRange();
7513 RealDecl->setInvalidDecl();
7514 return;
7515 }
7516
7517 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00007518 TypeSourceInfo *DeducedType = 0;
7519 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith34b41d92011-02-20 03:19:35 +00007520 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7521 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7522 << Init->getSourceRange();
Richard Smitha085da82011-03-17 16:11:59 +00007523 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00007524 RealDecl->setInvalidDecl();
7525 return;
7526 }
Richard Smitha085da82011-03-17 16:11:59 +00007527 VDecl->setTypeSourceInfo(DeducedType);
7528 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00007529
John McCallf85e1932011-06-15 23:02:42 +00007530 // In ARC, infer lifetime.
7531 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7532 VDecl->setInvalidDecl();
7533
Richard Smith34b41d92011-02-20 03:19:35 +00007534 // If this is a redeclaration, check that the type we just deduced matches
7535 // the previously declared type.
7536 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7537 MergeVarDeclTypes(VDecl, Old);
7538 }
7539
Douglas Gregor83ddad32009-08-26 21:14:46 +00007540 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007541 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007542 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7543 //
7544 // Clients that want to distinguish between the two forms, can check for
7545 // direct initializer using VarDecl::hasCXXDirectInitializer().
7546 // A major benefit is that clients that don't particularly care about which
7547 // exactly form was it (like the CodeGen) can handle both cases without
7548 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007549
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007550 // C++ 8.5p11:
7551 // The form of initialization (using parentheses or '=') is generally
7552 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007553 // class type.
7554
Douglas Gregor4dffad62010-02-11 22:55:30 +00007555 if (!VDecl->getType()->isDependentType() &&
7556 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00007557 diag::err_typecheck_decl_incomplete_type)) {
7558 VDecl->setInvalidDecl();
7559 return;
7560 }
7561
Douglas Gregor90f93822009-12-22 22:17:25 +00007562 // The variable can not have an abstract class type.
7563 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7564 diag::err_abstract_type_in_decl,
7565 AbstractVariableType))
7566 VDecl->setInvalidDecl();
7567
Sebastian Redl31310a22010-02-01 20:16:42 +00007568 const VarDecl *Def;
7569 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00007570 Diag(VDecl->getLocation(), diag::err_redefinition)
7571 << VDecl->getDeclName();
7572 Diag(Def->getLocation(), diag::note_previous_definition);
7573 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00007574 return;
7575 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00007576
Douglas Gregor3a91abf2010-08-24 05:27:49 +00007577 // C++ [class.static.data]p4
7578 // If a static data member is of const integral or const
7579 // enumeration type, its declaration in the class definition can
7580 // specify a constant-initializer which shall be an integral
7581 // constant expression (5.19). In that case, the member can appear
7582 // in integral constant expressions. The member shall still be
7583 // defined in a namespace scope if it is used in the program and the
7584 // namespace scope definition shall not contain an initializer.
7585 //
7586 // We already performed a redefinition check above, but for static
7587 // data members we also need to check whether there was an in-class
7588 // declaration with an initializer.
7589 const VarDecl* PrevInit = 0;
7590 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7591 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7592 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7593 return;
7594 }
7595
Douglas Gregora31040f2010-12-16 01:31:22 +00007596 bool IsDependent = false;
7597 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7598 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7599 VDecl->setInvalidDecl();
7600 return;
7601 }
7602
7603 if (Exprs.get()[I]->isTypeDependent())
7604 IsDependent = true;
7605 }
7606
Douglas Gregor4dffad62010-02-11 22:55:30 +00007607 // If either the declaration has a dependent type or if any of the
7608 // expressions is type-dependent, we represent the initialization
7609 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00007610 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00007611 // Let clients know that initialization was done with a direct initializer.
7612 VDecl->setCXXDirectInitializer(true);
7613
7614 // Store the initialization expressions as a ParenListExpr.
7615 unsigned NumExprs = Exprs.size();
7616 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7617 (Expr **)Exprs.release(),
7618 NumExprs, RParenLoc));
7619 return;
7620 }
Douglas Gregor90f93822009-12-22 22:17:25 +00007621
7622 // Capture the variable that is being initialized and the style of
7623 // initialization.
7624 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7625
7626 // FIXME: Poor source location information.
7627 InitializationKind Kind
7628 = InitializationKind::CreateDirect(VDecl->getLocation(),
7629 LParenLoc, RParenLoc);
7630
7631 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00007632 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00007633 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00007634 if (Result.isInvalid()) {
7635 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007636 return;
7637 }
John McCallb4eb64d2010-10-08 02:01:28 +00007638
7639 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregor90f93822009-12-22 22:17:25 +00007640
Douglas Gregor53c374f2010-12-07 00:41:46 +00007641 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregor838db382010-02-11 01:19:42 +00007642 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007643 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00007644
John McCall2998d6b2011-01-19 11:48:09 +00007645 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007646}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00007647
Douglas Gregor39da0b82009-09-09 23:08:42 +00007648/// \brief Given a constructor and the set of arguments provided for the
7649/// constructor, convert the arguments and add any required default arguments
7650/// to form a proper call to this constructor.
7651///
7652/// \returns true if an error occurred, false otherwise.
7653bool
7654Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7655 MultiExprArg ArgsPtr,
7656 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00007657 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00007658 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7659 unsigned NumArgs = ArgsPtr.size();
7660 Expr **Args = (Expr **)ArgsPtr.get();
7661
7662 const FunctionProtoType *Proto
7663 = Constructor->getType()->getAs<FunctionProtoType>();
7664 assert(Proto && "Constructor without a prototype?");
7665 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00007666
7667 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007668 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00007669 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007670 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00007671 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00007672
7673 VariadicCallType CallType =
7674 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7675 llvm::SmallVector<Expr *, 8> AllArgs;
7676 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7677 Proto, 0, Args, NumArgs, AllArgs,
7678 CallType);
7679 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7680 ConvertedArgs.push_back(AllArgs[i]);
7681 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00007682}
7683
Anders Carlsson20d45d22009-12-12 00:32:00 +00007684static inline bool
7685CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7686 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00007687 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00007688 if (isa<NamespaceDecl>(DC)) {
7689 return SemaRef.Diag(FnDecl->getLocation(),
7690 diag::err_operator_new_delete_declared_in_namespace)
7691 << FnDecl->getDeclName();
7692 }
7693
7694 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00007695 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007696 return SemaRef.Diag(FnDecl->getLocation(),
7697 diag::err_operator_new_delete_declared_static)
7698 << FnDecl->getDeclName();
7699 }
7700
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00007701 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00007702}
7703
Anders Carlsson156c78e2009-12-13 17:53:43 +00007704static inline bool
7705CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7706 CanQualType ExpectedResultType,
7707 CanQualType ExpectedFirstParamType,
7708 unsigned DependentParamTypeDiag,
7709 unsigned InvalidParamTypeDiag) {
7710 QualType ResultType =
7711 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7712
7713 // Check that the result type is not dependent.
7714 if (ResultType->isDependentType())
7715 return SemaRef.Diag(FnDecl->getLocation(),
7716 diag::err_operator_new_delete_dependent_result_type)
7717 << FnDecl->getDeclName() << ExpectedResultType;
7718
7719 // Check that the result type is what we expect.
7720 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7721 return SemaRef.Diag(FnDecl->getLocation(),
7722 diag::err_operator_new_delete_invalid_result_type)
7723 << FnDecl->getDeclName() << ExpectedResultType;
7724
7725 // A function template must have at least 2 parameters.
7726 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7727 return SemaRef.Diag(FnDecl->getLocation(),
7728 diag::err_operator_new_delete_template_too_few_parameters)
7729 << FnDecl->getDeclName();
7730
7731 // The function decl must have at least 1 parameter.
7732 if (FnDecl->getNumParams() == 0)
7733 return SemaRef.Diag(FnDecl->getLocation(),
7734 diag::err_operator_new_delete_too_few_parameters)
7735 << FnDecl->getDeclName();
7736
7737 // Check the the first parameter type is not dependent.
7738 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7739 if (FirstParamType->isDependentType())
7740 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7741 << FnDecl->getDeclName() << ExpectedFirstParamType;
7742
7743 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00007744 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00007745 ExpectedFirstParamType)
7746 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7747 << FnDecl->getDeclName() << ExpectedFirstParamType;
7748
7749 return false;
7750}
7751
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007752static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00007753CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00007754 // C++ [basic.stc.dynamic.allocation]p1:
7755 // A program is ill-formed if an allocation function is declared in a
7756 // namespace scope other than global scope or declared static in global
7757 // scope.
7758 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7759 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00007760
7761 CanQualType SizeTy =
7762 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7763
7764 // C++ [basic.stc.dynamic.allocation]p1:
7765 // The return type shall be void*. The first parameter shall have type
7766 // std::size_t.
7767 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7768 SizeTy,
7769 diag::err_operator_new_dependent_param_type,
7770 diag::err_operator_new_param_type))
7771 return true;
7772
7773 // C++ [basic.stc.dynamic.allocation]p1:
7774 // The first parameter shall not have an associated default argument.
7775 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00007776 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00007777 diag::err_operator_new_default_arg)
7778 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7779
7780 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00007781}
7782
7783static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007784CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7785 // C++ [basic.stc.dynamic.deallocation]p1:
7786 // A program is ill-formed if deallocation functions are declared in a
7787 // namespace scope other than global scope or declared static in global
7788 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00007789 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7790 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007791
7792 // C++ [basic.stc.dynamic.deallocation]p2:
7793 // Each deallocation function shall return void and its first parameter
7794 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00007795 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7796 SemaRef.Context.VoidPtrTy,
7797 diag::err_operator_delete_dependent_param_type,
7798 diag::err_operator_delete_param_type))
7799 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007800
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007801 return false;
7802}
7803
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007804/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7805/// of this overloaded operator is well-formed. If so, returns false;
7806/// otherwise, emits appropriate diagnostics and returns true.
7807bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007808 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007809 "Expected an overloaded operator declaration");
7810
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007811 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7812
Mike Stump1eb44332009-09-09 15:08:12 +00007813 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007814 // The allocation and deallocation functions, operator new,
7815 // operator new[], operator delete and operator delete[], are
7816 // described completely in 3.7.3. The attributes and restrictions
7817 // found in the rest of this subclause do not apply to them unless
7818 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00007819 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00007820 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00007821
Anders Carlssona3ccda52009-12-12 00:26:23 +00007822 if (Op == OO_New || Op == OO_Array_New)
7823 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007824
7825 // C++ [over.oper]p6:
7826 // An operator function shall either be a non-static member
7827 // function or be a non-member function and have at least one
7828 // parameter whose type is a class, a reference to a class, an
7829 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007830 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7831 if (MethodDecl->isStatic())
7832 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007833 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007834 } else {
7835 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007836 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7837 ParamEnd = FnDecl->param_end();
7838 Param != ParamEnd; ++Param) {
7839 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00007840 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7841 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007842 ClassOrEnumParam = true;
7843 break;
7844 }
7845 }
7846
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007847 if (!ClassOrEnumParam)
7848 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007849 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007850 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007851 }
7852
7853 // C++ [over.oper]p8:
7854 // An operator function cannot have default arguments (8.3.6),
7855 // except where explicitly stated below.
7856 //
Mike Stump1eb44332009-09-09 15:08:12 +00007857 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007858 // (C++ [over.call]p1).
7859 if (Op != OO_Call) {
7860 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7861 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00007862 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00007863 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00007864 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00007865 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007866 }
7867 }
7868
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007869 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7870 { false, false, false }
7871#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7872 , { Unary, Binary, MemberOnly }
7873#include "clang/Basic/OperatorKinds.def"
7874 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007875
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007876 bool CanBeUnaryOperator = OperatorUses[Op][0];
7877 bool CanBeBinaryOperator = OperatorUses[Op][1];
7878 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007879
7880 // C++ [over.oper]p8:
7881 // [...] Operator functions cannot have more or fewer parameters
7882 // than the number required for the corresponding operator, as
7883 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00007884 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007885 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007886 if (Op != OO_Call &&
7887 ((NumParams == 1 && !CanBeUnaryOperator) ||
7888 (NumParams == 2 && !CanBeBinaryOperator) ||
7889 (NumParams < 1) || (NumParams > 2))) {
7890 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00007891 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007892 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007893 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007894 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00007895 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007896 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007897 assert(CanBeBinaryOperator &&
7898 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00007899 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00007900 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007901
Chris Lattner416e46f2008-11-21 07:57:12 +00007902 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007903 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007904 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007905
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007906 // Overloaded operators other than operator() cannot be variadic.
7907 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00007908 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007909 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007910 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007911 }
7912
7913 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007914 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7915 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007916 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007917 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007918 }
7919
7920 // C++ [over.inc]p1:
7921 // The user-defined function called operator++ implements the
7922 // prefix and postfix ++ operator. If this function is a member
7923 // function with no parameters, or a non-member function with one
7924 // parameter of class or enumeration type, it defines the prefix
7925 // increment operator ++ for objects of that type. If the function
7926 // is a member function with one parameter (which shall be of type
7927 // int) or a non-member function with two parameters (the second
7928 // of which shall be of type int), it defines the postfix
7929 // increment operator ++ for objects of that type.
7930 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7931 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7932 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00007933 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007934 ParamIsInt = BT->getKind() == BuiltinType::Int;
7935
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00007936 if (!ParamIsInt)
7937 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00007938 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00007939 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007940 }
7941
Douglas Gregor43c7bad2008-11-17 16:14:12 +00007942 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00007943}
Chris Lattner5a003a42008-12-17 07:09:26 +00007944
Sean Hunta6c058d2010-01-13 09:01:02 +00007945/// CheckLiteralOperatorDeclaration - Check whether the declaration
7946/// of this literal operator function is well-formed. If so, returns
7947/// false; otherwise, emits appropriate diagnostics and returns true.
7948bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7949 DeclContext *DC = FnDecl->getDeclContext();
7950 Decl::Kind Kind = DC->getDeclKind();
7951 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7952 Kind != Decl::LinkageSpec) {
7953 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7954 << FnDecl->getDeclName();
7955 return true;
7956 }
7957
7958 bool Valid = false;
7959
Sean Hunt216c2782010-04-07 23:11:06 +00007960 // template <char...> type operator "" name() is the only valid template
7961 // signature, and the only valid signature with no parameters.
7962 if (FnDecl->param_size() == 0) {
7963 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7964 // Must have only one template parameter
7965 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7966 if (Params->size() == 1) {
7967 NonTypeTemplateParmDecl *PmDecl =
7968 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00007969
Sean Hunt216c2782010-04-07 23:11:06 +00007970 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00007971 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7972 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7973 Valid = true;
7974 }
7975 }
7976 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00007977 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00007978 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7979
Sean Hunta6c058d2010-01-13 09:01:02 +00007980 QualType T = (*Param)->getType();
7981
Sean Hunt30019c02010-04-07 22:57:35 +00007982 // unsigned long long int, long double, and any character type are allowed
7983 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00007984 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7985 Context.hasSameType(T, Context.LongDoubleTy) ||
7986 Context.hasSameType(T, Context.CharTy) ||
7987 Context.hasSameType(T, Context.WCharTy) ||
7988 Context.hasSameType(T, Context.Char16Ty) ||
7989 Context.hasSameType(T, Context.Char32Ty)) {
7990 if (++Param == FnDecl->param_end())
7991 Valid = true;
7992 goto FinishedParams;
7993 }
7994
Sean Hunt30019c02010-04-07 22:57:35 +00007995 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00007996 const PointerType *PT = T->getAs<PointerType>();
7997 if (!PT)
7998 goto FinishedParams;
7999 T = PT->getPointeeType();
8000 if (!T.isConstQualified())
8001 goto FinishedParams;
8002 T = T.getUnqualifiedType();
8003
8004 // Move on to the second parameter;
8005 ++Param;
8006
8007 // If there is no second parameter, the first must be a const char *
8008 if (Param == FnDecl->param_end()) {
8009 if (Context.hasSameType(T, Context.CharTy))
8010 Valid = true;
8011 goto FinishedParams;
8012 }
8013
8014 // const char *, const wchar_t*, const char16_t*, and const char32_t*
8015 // are allowed as the first parameter to a two-parameter function
8016 if (!(Context.hasSameType(T, Context.CharTy) ||
8017 Context.hasSameType(T, Context.WCharTy) ||
8018 Context.hasSameType(T, Context.Char16Ty) ||
8019 Context.hasSameType(T, Context.Char32Ty)))
8020 goto FinishedParams;
8021
8022 // The second and final parameter must be an std::size_t
8023 T = (*Param)->getType().getUnqualifiedType();
8024 if (Context.hasSameType(T, Context.getSizeType()) &&
8025 ++Param == FnDecl->param_end())
8026 Valid = true;
8027 }
8028
8029 // FIXME: This diagnostic is absolutely terrible.
8030FinishedParams:
8031 if (!Valid) {
8032 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8033 << FnDecl->getDeclName();
8034 return true;
8035 }
8036
8037 return false;
8038}
8039
Douglas Gregor074149e2009-01-05 19:45:36 +00008040/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8041/// linkage specification, including the language and (if present)
8042/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8043/// the location of the language string literal, which is provided
8044/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8045/// the '{' brace. Otherwise, this linkage specification does not
8046/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00008047Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8048 SourceLocation LangLoc,
8049 llvm::StringRef Lang,
8050 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00008051 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00008052 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00008053 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00008054 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00008055 Language = LinkageSpecDecl::lang_cxx;
8056 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00008057 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00008058 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00008059 }
Mike Stump1eb44332009-09-09 15:08:12 +00008060
Chris Lattnercc98eac2008-12-17 07:13:27 +00008061 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00008062
Douglas Gregor074149e2009-01-05 19:45:36 +00008063 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008064 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008065 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00008066 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00008067 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00008068}
8069
Abramo Bagnara35f9a192010-07-30 16:47:02 +00008070/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00008071/// the C++ linkage specification LinkageSpec. If RBraceLoc is
8072/// valid, it's the position of the closing '}' brace in a linkage
8073/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00008074Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008075 Decl *LinkageSpec,
8076 SourceLocation RBraceLoc) {
8077 if (LinkageSpec) {
8078 if (RBraceLoc.isValid()) {
8079 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8080 LSDecl->setRBraceLoc(RBraceLoc);
8081 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008082 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00008083 }
Douglas Gregor074149e2009-01-05 19:45:36 +00008084 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00008085}
8086
Douglas Gregord308e622009-05-18 20:51:54 +00008087/// \brief Perform semantic analysis for the variable declaration that
8088/// occurs within a C++ catch clause, returning the newly-created
8089/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008090VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00008091 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008092 SourceLocation StartLoc,
8093 SourceLocation Loc,
8094 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00008095 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00008096 QualType ExDeclType = TInfo->getType();
8097
Sebastian Redl4b07b292008-12-22 19:15:10 +00008098 // Arrays and functions decay.
8099 if (ExDeclType->isArrayType())
8100 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8101 else if (ExDeclType->isFunctionType())
8102 ExDeclType = Context.getPointerType(ExDeclType);
8103
8104 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8105 // The exception-declaration shall not denote a pointer or reference to an
8106 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008107 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00008108 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00008109 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008110 Invalid = true;
8111 }
Douglas Gregord308e622009-05-18 20:51:54 +00008112
Douglas Gregora2762912010-03-08 01:47:36 +00008113 // GCC allows catching pointers and references to incomplete types
8114 // as an extension; so do we, but we warn by default.
8115
Sebastian Redl4b07b292008-12-22 19:15:10 +00008116 QualType BaseType = ExDeclType;
8117 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00008118 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00008119 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00008120 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008121 BaseType = Ptr->getPointeeType();
8122 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00008123 DK = diag::ext_catch_incomplete_ptr;
8124 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00008125 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008126 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008127 BaseType = Ref->getPointeeType();
8128 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00008129 DK = diag::ext_catch_incomplete_ref;
8130 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008131 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00008132 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00008133 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8134 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00008135 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008136
Mike Stump1eb44332009-09-09 15:08:12 +00008137 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00008138 RequireNonAbstractType(Loc, ExDeclType,
8139 diag::err_abstract_type_in_decl,
8140 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00008141 Invalid = true;
8142
John McCall5a180392010-07-24 00:37:23 +00008143 // Only the non-fragile NeXT runtime currently supports C++ catches
8144 // of ObjC types, and no runtime supports catching ObjC types by value.
8145 if (!Invalid && getLangOptions().ObjC1) {
8146 QualType T = ExDeclType;
8147 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8148 T = RT->getPointeeType();
8149
8150 if (T->isObjCObjectType()) {
8151 Diag(Loc, diag::err_objc_object_catch);
8152 Invalid = true;
8153 } else if (T->isObjCObjectPointerType()) {
David Chisnall80558d22011-03-20 21:35:39 +00008154 if (!getLangOptions().ObjCNonFragileABI) {
John McCall5a180392010-07-24 00:37:23 +00008155 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8156 Invalid = true;
8157 }
8158 }
8159 }
8160
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008161 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8162 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00008163 ExDecl->setExceptionVariable(true);
8164
Douglas Gregor6d182892010-03-05 23:38:39 +00008165 if (!Invalid) {
John McCalle996ffd2011-02-16 08:02:54 +00008166 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00008167 // C++ [except.handle]p16:
8168 // The object declared in an exception-declaration or, if the
8169 // exception-declaration does not specify a name, a temporary (12.2) is
8170 // copy-initialized (8.5) from the exception object. [...]
8171 // The object is destroyed when the handler exits, after the destruction
8172 // of any automatic objects initialized within the handler.
8173 //
8174 // We just pretend to initialize the object with itself, then make sure
8175 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00008176 QualType initType = ExDeclType;
8177
8178 InitializedEntity entity =
8179 InitializedEntity::InitializeVariable(ExDecl);
8180 InitializationKind initKind =
8181 InitializationKind::CreateCopy(Loc, SourceLocation());
8182
8183 Expr *opaqueValue =
8184 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8185 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8186 ExprResult result = sequence.Perform(*this, entity, initKind,
8187 MultiExprArg(&opaqueValue, 1));
8188 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00008189 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00008190 else {
8191 // If the constructor used was non-trivial, set this as the
8192 // "initializer".
8193 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8194 if (!construct->getConstructor()->isTrivial()) {
8195 Expr *init = MaybeCreateExprWithCleanups(construct);
8196 ExDecl->setInit(init);
8197 }
8198
8199 // And make sure it's destructable.
8200 FinalizeVarWithDestructor(ExDecl, recordType);
8201 }
Douglas Gregor6d182892010-03-05 23:38:39 +00008202 }
8203 }
8204
Douglas Gregord308e622009-05-18 20:51:54 +00008205 if (Invalid)
8206 ExDecl->setInvalidDecl();
8207
8208 return ExDecl;
8209}
8210
8211/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8212/// handler.
John McCalld226f652010-08-21 09:40:31 +00008213Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00008214 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00008215 bool Invalid = D.isInvalidType();
8216
8217 // Check for unexpanded parameter packs.
8218 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8219 UPPC_ExceptionType)) {
8220 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8221 D.getIdentifierLoc());
8222 Invalid = true;
8223 }
8224
Sebastian Redl4b07b292008-12-22 19:15:10 +00008225 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00008226 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00008227 LookupOrdinaryName,
8228 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008229 // The scope should be freshly made just for us. There is just no way
8230 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00008231 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00008232 if (PrevDecl->isTemplateParameter()) {
8233 // Maybe we will complain about the shadowed template parameter.
8234 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008235 }
8236 }
8237
Chris Lattnereaaebc72009-04-25 08:06:05 +00008238 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00008239 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8240 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00008241 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008242 }
8243
Douglas Gregor83cb9422010-09-09 17:09:21 +00008244 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008245 D.getSourceRange().getBegin(),
8246 D.getIdentifierLoc(),
8247 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00008248 if (Invalid)
8249 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00008250
Sebastian Redl4b07b292008-12-22 19:15:10 +00008251 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00008252 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00008253 PushOnScopeChains(ExDecl, S);
8254 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008255 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00008256
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00008257 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00008258 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00008259}
Anders Carlssonfb311762009-03-14 00:25:26 +00008260
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008261Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00008262 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008263 Expr *AssertMessageExpr_,
8264 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00008265 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00008266
Anders Carlssonc3082412009-03-14 00:33:21 +00008267 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8268 llvm::APSInt Value(32);
8269 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008270 Diag(StaticAssertLoc,
8271 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlssonc3082412009-03-14 00:33:21 +00008272 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008273 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00008274 }
Anders Carlssonfb311762009-03-14 00:25:26 +00008275
Anders Carlssonc3082412009-03-14 00:33:21 +00008276 if (Value == 0) {
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008277 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00008278 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00008279 }
8280 }
Mike Stump1eb44332009-09-09 15:08:12 +00008281
Douglas Gregor399ad972010-12-15 23:55:21 +00008282 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8283 return 0;
8284
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00008285 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8286 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008287
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00008288 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00008289 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00008290}
Sebastian Redl50de12f2009-03-24 22:27:57 +00008291
Douglas Gregor1d869352010-04-07 16:53:43 +00008292/// \brief Perform semantic analysis of the given friend type declaration.
8293///
8294/// \returns A friend declaration that.
8295FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8296 TypeSourceInfo *TSInfo) {
8297 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8298
8299 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00008300 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00008301
Douglas Gregor06245bf2010-04-07 17:57:12 +00008302 if (!getLangOptions().CPlusPlus0x) {
8303 // C++03 [class.friend]p2:
8304 // An elaborated-type-specifier shall be used in a friend declaration
8305 // for a class.*
8306 //
8307 // * The class-key of the elaborated-type-specifier is required.
8308 if (!ActiveTemplateInstantiations.empty()) {
8309 // Do not complain about the form of friend template types during
8310 // template instantiation; we will already have complained when the
8311 // template was declared.
8312 } else if (!T->isElaboratedTypeSpecifier()) {
8313 // If we evaluated the type to a record type, suggest putting
8314 // a tag in front.
8315 if (const RecordType *RT = T->getAs<RecordType>()) {
8316 RecordDecl *RD = RT->getDecl();
8317
8318 std::string InsertionText = std::string(" ") + RD->getKindName();
8319
8320 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8321 << (unsigned) RD->getTagKind()
8322 << T
8323 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8324 InsertionText);
8325 } else {
8326 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8327 << T
8328 << SourceRange(FriendLoc, TypeRange.getEnd());
8329 }
8330 } else if (T->getAs<EnumType>()) {
8331 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00008332 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00008333 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00008334 }
8335 }
8336
Douglas Gregor06245bf2010-04-07 17:57:12 +00008337 // C++0x [class.friend]p3:
8338 // If the type specifier in a friend declaration designates a (possibly
8339 // cv-qualified) class type, that class is declared as a friend; otherwise,
8340 // the friend declaration is ignored.
8341
8342 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8343 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00008344
8345 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8346}
8347
John McCall9a34edb2010-10-19 01:40:49 +00008348/// Handle a friend tag declaration where the scope specifier was
8349/// templated.
8350Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8351 unsigned TagSpec, SourceLocation TagLoc,
8352 CXXScopeSpec &SS,
8353 IdentifierInfo *Name, SourceLocation NameLoc,
8354 AttributeList *Attr,
8355 MultiTemplateParamsArg TempParamLists) {
8356 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8357
8358 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00008359 bool Invalid = false;
8360
8361 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00008362 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +00008363 TempParamLists.get(),
8364 TempParamLists.size(),
8365 /*friend*/ true,
8366 isExplicitSpecialization,
8367 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00008368 if (TemplateParams->size() > 0) {
8369 // This is a declaration of a class template.
8370 if (Invalid)
8371 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008372
John McCall9a34edb2010-10-19 01:40:49 +00008373 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8374 SS, Name, NameLoc, Attr,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008375 TemplateParams, AS_public,
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008376 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00008377 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +00008378 } else {
8379 // The "template<>" header is extraneous.
8380 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8381 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8382 isExplicitSpecialization = true;
8383 }
8384 }
8385
8386 if (Invalid) return 0;
8387
8388 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8389
8390 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00008391 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +00008392 if (TempParamLists.get()[I]->size()) {
8393 isAllExplicitSpecializations = false;
8394 break;
8395 }
8396 }
8397
8398 // FIXME: don't ignore attributes.
8399
8400 // If it's explicit specializations all the way down, just forget
8401 // about the template header and build an appropriate non-templated
8402 // friend. TODO: for source fidelity, remember the headers.
8403 if (isAllExplicitSpecializations) {
Douglas Gregor2494dd02011-03-01 01:34:45 +00008404 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00008405 ElaboratedTypeKeyword Keyword
8406 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008407 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00008408 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008409 if (T.isNull())
8410 return 0;
8411
8412 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8413 if (isa<DependentNameType>(T)) {
8414 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8415 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008416 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008417 TL.setNameLoc(NameLoc);
8418 } else {
8419 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8420 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00008421 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00008422 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8423 }
8424
8425 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8426 TSI, FriendLoc);
8427 Friend->setAccess(AS_public);
8428 CurContext->addDecl(Friend);
8429 return Friend;
8430 }
8431
8432 // Handle the case of a templated-scope friend class. e.g.
8433 // template <class T> class A<T>::B;
8434 // FIXME: we don't support these right now.
8435 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8436 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8437 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8438 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8439 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00008440 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00008441 TL.setNameLoc(NameLoc);
8442
8443 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8444 TSI, FriendLoc);
8445 Friend->setAccess(AS_public);
8446 Friend->setUnsupportedFriend(true);
8447 CurContext->addDecl(Friend);
8448 return Friend;
8449}
8450
8451
John McCalldd4a3b02009-09-16 22:47:08 +00008452/// Handle a friend type declaration. This works in tandem with
8453/// ActOnTag.
8454///
8455/// Notes on friend class templates:
8456///
8457/// We generally treat friend class declarations as if they were
8458/// declaring a class. So, for example, the elaborated type specifier
8459/// in a friend declaration is required to obey the restrictions of a
8460/// class-head (i.e. no typedefs in the scope chain), template
8461/// parameters are required to match up with simple template-ids, &c.
8462/// However, unlike when declaring a template specialization, it's
8463/// okay to refer to a template specialization without an empty
8464/// template parameter declaration, e.g.
8465/// friend class A<T>::B<unsigned>;
8466/// We permit this as a special case; if there are any template
8467/// parameters present at all, require proper matching, i.e.
8468/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00008469Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +00008470 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00008471 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00008472
8473 assert(DS.isFriendSpecified());
8474 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8475
John McCalldd4a3b02009-09-16 22:47:08 +00008476 // Try to convert the decl specifier to a type. This works for
8477 // friend templates because ActOnTag never produces a ClassTemplateDecl
8478 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00008479 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00008480 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8481 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00008482 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00008483 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008484
Douglas Gregor6ccab972010-12-16 01:14:37 +00008485 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8486 return 0;
8487
John McCalldd4a3b02009-09-16 22:47:08 +00008488 // This is definitely an error in C++98. It's probably meant to
8489 // be forbidden in C++0x, too, but the specification is just
8490 // poorly written.
8491 //
8492 // The problem is with declarations like the following:
8493 // template <T> friend A<T>::foo;
8494 // where deciding whether a class C is a friend or not now hinges
8495 // on whether there exists an instantiation of A that causes
8496 // 'foo' to equal C. There are restrictions on class-heads
8497 // (which we declare (by fiat) elaborated friend declarations to
8498 // be) that makes this tractable.
8499 //
8500 // FIXME: handle "template <> friend class A<T>;", which
8501 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00008502 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00008503 Diag(Loc, diag::err_tagless_friend_type_template)
8504 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00008505 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00008506 }
Douglas Gregor1d869352010-04-07 16:53:43 +00008507
John McCall02cace72009-08-28 07:59:38 +00008508 // C++98 [class.friend]p1: A friend of a class is a function
8509 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00008510 // This is fixed in DR77, which just barely didn't make the C++03
8511 // deadline. It's also a very silly restriction that seriously
8512 // affects inner classes and which nobody else seems to implement;
8513 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00008514 //
8515 // But note that we could warn about it: it's always useless to
8516 // friend one of your own members (it's not, however, worthless to
8517 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00008518
John McCalldd4a3b02009-09-16 22:47:08 +00008519 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00008520 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00008521 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00008522 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +00008523 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00008524 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00008525 DS.getFriendSpecLoc());
8526 else
Douglas Gregor1d869352010-04-07 16:53:43 +00008527 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8528
8529 if (!D)
John McCalld226f652010-08-21 09:40:31 +00008530 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00008531
John McCalldd4a3b02009-09-16 22:47:08 +00008532 D->setAccess(AS_public);
8533 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00008534
John McCalld226f652010-08-21 09:40:31 +00008535 return D;
John McCall02cace72009-08-28 07:59:38 +00008536}
8537
John McCall337ec3d2010-10-12 23:13:28 +00008538Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8539 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00008540 const DeclSpec &DS = D.getDeclSpec();
8541
8542 assert(DS.isFriendSpecified());
8543 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8544
8545 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00008546 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8547 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00008548
8549 // C++ [class.friend]p1
8550 // A friend of a class is a function or class....
8551 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00008552 // It *doesn't* see through dependent types, which is correct
8553 // according to [temp.arg.type]p3:
8554 // If a declaration acquires a function type through a
8555 // type dependent on a template-parameter and this causes
8556 // a declaration that does not use the syntactic form of a
8557 // function declarator to have a function type, the program
8558 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00008559 if (!T->isFunctionType()) {
8560 Diag(Loc, diag::err_unexpected_friend);
8561
8562 // It might be worthwhile to try to recover by creating an
8563 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00008564 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008565 }
8566
8567 // C++ [namespace.memdef]p3
8568 // - If a friend declaration in a non-local class first declares a
8569 // class or function, the friend class or function is a member
8570 // of the innermost enclosing namespace.
8571 // - The name of the friend is not found by simple name lookup
8572 // until a matching declaration is provided in that namespace
8573 // scope (either before or after the class declaration granting
8574 // friendship).
8575 // - If a friend function is called, its name may be found by the
8576 // name lookup that considers functions from namespaces and
8577 // classes associated with the types of the function arguments.
8578 // - When looking for a prior declaration of a class or a function
8579 // declared as a friend, scopes outside the innermost enclosing
8580 // namespace scope are not considered.
8581
John McCall337ec3d2010-10-12 23:13:28 +00008582 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00008583 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8584 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00008585 assert(Name);
8586
Douglas Gregor6ccab972010-12-16 01:14:37 +00008587 // Check for unexpanded parameter packs.
8588 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8589 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8590 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8591 return 0;
8592
John McCall67d1a672009-08-06 02:15:43 +00008593 // The context we found the declaration in, or in which we should
8594 // create the declaration.
8595 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +00008596 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +00008597 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00008598 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00008599
John McCall337ec3d2010-10-12 23:13:28 +00008600 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +00008601
John McCall337ec3d2010-10-12 23:13:28 +00008602 // There are four cases here.
8603 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +00008604 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +00008605 // there as appropriate.
8606 // Recover from invalid scope qualifiers as if they just weren't there.
8607 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +00008608 // C++0x [namespace.memdef]p3:
8609 // If the name in a friend declaration is neither qualified nor
8610 // a template-id and the declaration is a function or an
8611 // elaborated-type-specifier, the lookup to determine whether
8612 // the entity has been previously declared shall not consider
8613 // any scopes outside the innermost enclosing namespace.
8614 // C++0x [class.friend]p11:
8615 // If a friend declaration appears in a local class and the name
8616 // specified is an unqualified name, a prior declaration is
8617 // looked up without considering scopes that are outside the
8618 // innermost enclosing non-class scope. For a friend function
8619 // declaration, if there is no prior declaration, the program is
8620 // ill-formed.
8621 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +00008622 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +00008623
John McCall29ae6e52010-10-13 05:45:15 +00008624 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +00008625 DC = CurContext;
8626 while (true) {
8627 // Skip class contexts. If someone can cite chapter and verse
8628 // for this behavior, that would be nice --- it's what GCC and
8629 // EDG do, and it seems like a reasonable intent, but the spec
8630 // really only says that checks for unqualified existing
8631 // declarations should stop at the nearest enclosing namespace,
8632 // not that they should only consider the nearest enclosing
8633 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00008634 while (DC->isRecord())
8635 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00008636
John McCall68263142009-11-18 22:49:29 +00008637 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00008638
8639 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +00008640 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00008641 break;
John McCall29ae6e52010-10-13 05:45:15 +00008642
John McCall8a407372010-10-14 22:22:28 +00008643 if (isTemplateId) {
8644 if (isa<TranslationUnitDecl>(DC)) break;
8645 } else {
8646 if (DC->isFileContext()) break;
8647 }
John McCall67d1a672009-08-06 02:15:43 +00008648 DC = DC->getParent();
8649 }
8650
8651 // C++ [class.friend]p1: A friend of a class is a function or
8652 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00008653 // C++0x changes this for both friend types and functions.
8654 // Most C++ 98 compilers do seem to give an error here, so
8655 // we do, too.
John McCall68263142009-11-18 22:49:29 +00008656 if (!Previous.empty() && DC->Equals(CurContext)
8657 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00008658 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +00008659
John McCall380aaa42010-10-13 06:22:15 +00008660 DCScope = getScopeForDeclContext(S, DC);
John McCall29ae6e52010-10-13 05:45:15 +00008661
John McCall337ec3d2010-10-12 23:13:28 +00008662 // - There's a non-dependent scope specifier, in which case we
8663 // compute it and do a previous lookup there for a function
8664 // or function template.
8665 } else if (!SS.getScopeRep()->isDependent()) {
8666 DC = computeDeclContext(SS);
8667 if (!DC) return 0;
8668
8669 if (RequireCompleteDeclContext(SS, DC)) return 0;
8670
8671 LookupQualifiedName(Previous, DC);
8672
8673 // Ignore things found implicitly in the wrong scope.
8674 // TODO: better diagnostics for this case. Suggesting the right
8675 // qualified scope would be nice...
8676 LookupResult::Filter F = Previous.makeFilter();
8677 while (F.hasNext()) {
8678 NamedDecl *D = F.next();
8679 if (!DC->InEnclosingNamespaceSetOf(
8680 D->getDeclContext()->getRedeclContext()))
8681 F.erase();
8682 }
8683 F.done();
8684
8685 if (Previous.empty()) {
8686 D.setInvalidType();
8687 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8688 return 0;
8689 }
8690
8691 // C++ [class.friend]p1: A friend of a class is a function or
8692 // class that is not a member of the class . . .
8693 if (DC->Equals(CurContext))
8694 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8695
8696 // - There's a scope specifier that does not match any template
8697 // parameter lists, in which case we use some arbitrary context,
8698 // create a method or method template, and wait for instantiation.
8699 // - There's a scope specifier that does match some template
8700 // parameter lists, which we don't handle right now.
8701 } else {
8702 DC = CurContext;
8703 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +00008704 }
8705
John McCall29ae6e52010-10-13 05:45:15 +00008706 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +00008707 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008708 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8709 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8710 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00008711 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00008712 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8713 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00008714 return 0;
John McCall67d1a672009-08-06 02:15:43 +00008715 }
John McCall67d1a672009-08-06 02:15:43 +00008716 }
8717
Douglas Gregor182ddf02009-09-28 00:08:27 +00008718 bool Redeclaration = false;
John McCall380aaa42010-10-13 06:22:15 +00008719 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00008720 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00008721 IsDefinition,
8722 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00008723 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00008724
Douglas Gregor182ddf02009-09-28 00:08:27 +00008725 assert(ND->getDeclContext() == DC);
8726 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00008727
John McCallab88d972009-08-31 22:39:49 +00008728 // Add the function declaration to the appropriate lookup tables,
8729 // adjusting the redeclarations list as necessary. We don't
8730 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00008731 //
John McCallab88d972009-08-31 22:39:49 +00008732 // Also update the scope-based lookup if the target context's
8733 // lookup context is in lexical scope.
8734 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00008735 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00008736 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008737 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00008738 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00008739 }
John McCall02cace72009-08-28 07:59:38 +00008740
8741 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00008742 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00008743 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00008744 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00008745 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00008746
John McCall337ec3d2010-10-12 23:13:28 +00008747 if (ND->isInvalidDecl())
8748 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +00008749 else {
8750 FunctionDecl *FD;
8751 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8752 FD = FTD->getTemplatedDecl();
8753 else
8754 FD = cast<FunctionDecl>(ND);
8755
8756 // Mark templated-scope function declarations as unsupported.
8757 if (FD->getNumTemplateParameterLists())
8758 FrD->setUnsupportedFriend(true);
8759 }
John McCall337ec3d2010-10-12 23:13:28 +00008760
John McCalld226f652010-08-21 09:40:31 +00008761 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00008762}
8763
John McCalld226f652010-08-21 09:40:31 +00008764void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8765 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00008766
Sebastian Redl50de12f2009-03-24 22:27:57 +00008767 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8768 if (!Fn) {
8769 Diag(DelLoc, diag::err_deleted_non_function);
8770 return;
8771 }
8772 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8773 Diag(DelLoc, diag::err_deleted_decl_not_first);
8774 Diag(Prev->getLocation(), diag::note_previous_declaration);
8775 // If the declaration wasn't the first, we delete the function anyway for
8776 // recovery.
8777 }
Sean Hunt10620eb2011-05-06 20:44:56 +00008778 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +00008779}
Sebastian Redl13e88542009-04-27 21:33:24 +00008780
Sean Hunte4246a62011-05-12 06:15:49 +00008781void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8782 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8783
8784 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +00008785 if (MD->getParent()->isDependentType()) {
8786 MD->setDefaulted();
8787 MD->setExplicitlyDefaulted();
8788 return;
8789 }
8790
Sean Hunte4246a62011-05-12 06:15:49 +00008791 CXXSpecialMember Member = getSpecialMember(MD);
8792 if (Member == CXXInvalid) {
8793 Diag(DefaultLoc, diag::err_default_special_members);
8794 return;
8795 }
8796
8797 MD->setDefaulted();
8798 MD->setExplicitlyDefaulted();
8799
Sean Huntcd10dec2011-05-23 23:14:04 +00008800 // If this definition appears within the record, do the checking when
8801 // the record is complete.
8802 const FunctionDecl *Primary = MD;
8803 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8804 // Find the uninstantiated declaration that actually had the '= default'
8805 // on it.
8806 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8807
8808 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +00008809 return;
8810
8811 switch (Member) {
8812 case CXXDefaultConstructor: {
8813 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8814 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008815 if (!CD->isInvalidDecl())
8816 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8817 break;
8818 }
8819
8820 case CXXCopyConstructor: {
8821 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8822 CheckExplicitlyDefaultedCopyConstructor(CD);
8823 if (!CD->isInvalidDecl())
8824 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +00008825 break;
8826 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00008827
Sean Hunt2b188082011-05-14 05:23:28 +00008828 case CXXCopyAssignment: {
8829 CheckExplicitlyDefaultedCopyAssignment(MD);
8830 if (!MD->isInvalidDecl())
8831 DefineImplicitCopyAssignment(DefaultLoc, MD);
8832 break;
8833 }
8834
Sean Huntcb45a0f2011-05-12 22:46:25 +00008835 case CXXDestructor: {
8836 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8837 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +00008838 if (!DD->isInvalidDecl())
8839 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008840 break;
8841 }
8842
Sean Hunt82713172011-05-25 23:16:36 +00008843 case CXXMoveConstructor:
8844 case CXXMoveAssignment:
8845 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8846 break;
8847
Sean Hunte4246a62011-05-12 06:15:49 +00008848 default:
Sean Hunt2b188082011-05-14 05:23:28 +00008849 // FIXME: Do the rest once we have move functions
Sean Hunte4246a62011-05-12 06:15:49 +00008850 break;
8851 }
8852 } else {
8853 Diag(DefaultLoc, diag::err_default_special_members);
8854 }
8855}
8856
Sebastian Redl13e88542009-04-27 21:33:24 +00008857static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00008858 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +00008859 Stmt *SubStmt = *CI;
8860 if (!SubStmt)
8861 continue;
8862 if (isa<ReturnStmt>(SubStmt))
8863 Self.Diag(SubStmt->getSourceRange().getBegin(),
8864 diag::err_return_in_constructor_handler);
8865 if (!isa<Expr>(SubStmt))
8866 SearchForReturnInStmt(Self, SubStmt);
8867 }
8868}
8869
8870void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8871 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8872 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8873 SearchForReturnInStmt(*this, Handler);
8874 }
8875}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008876
Mike Stump1eb44332009-09-09 15:08:12 +00008877bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008878 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00008879 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8880 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008881
Chandler Carruth73857792010-02-15 11:53:20 +00008882 if (Context.hasSameType(NewTy, OldTy) ||
8883 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008884 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00008885
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008886 // Check if the return types are covariant
8887 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00008888
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008889 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008890 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8891 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008892 NewClassTy = NewPT->getPointeeType();
8893 OldClassTy = OldPT->getPointeeType();
8894 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008895 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8896 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8897 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8898 NewClassTy = NewRT->getPointeeType();
8899 OldClassTy = OldRT->getPointeeType();
8900 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008901 }
8902 }
Mike Stump1eb44332009-09-09 15:08:12 +00008903
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008904 // The return types aren't either both pointers or references to a class type.
8905 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00008906 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008907 diag::err_different_return_type_for_overriding_virtual_function)
8908 << New->getDeclName() << NewTy << OldTy;
8909 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00008910
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008911 return true;
8912 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008913
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008914 // C++ [class.virtual]p6:
8915 // If the return type of D::f differs from the return type of B::f, the
8916 // class type in the return type of D::f shall be complete at the point of
8917 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00008918 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8919 if (!RT->isBeingDefined() &&
8920 RequireCompleteType(New->getLocation(), NewClassTy,
8921 PDiag(diag::err_covariant_return_incomplete)
8922 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008923 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00008924 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00008925
Douglas Gregora4923eb2009-11-16 21:35:15 +00008926 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008927 // Check if the new class derives from the old class.
8928 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8929 Diag(New->getLocation(),
8930 diag::err_covariant_return_not_derived)
8931 << New->getDeclName() << NewTy << OldTy;
8932 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8933 return true;
8934 }
Mike Stump1eb44332009-09-09 15:08:12 +00008935
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008936 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00008937 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00008938 diag::err_covariant_return_inaccessible_base,
8939 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8940 // FIXME: Should this point to the return type?
8941 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +00008942 // FIXME: this note won't trigger for delayed access control
8943 // diagnostics, and it's impossible to get an undelayed error
8944 // here from access control during the original parse because
8945 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008946 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8947 return true;
8948 }
8949 }
Mike Stump1eb44332009-09-09 15:08:12 +00008950
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008951 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00008952 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008953 Diag(New->getLocation(),
8954 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008955 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008956 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8957 return true;
8958 };
Mike Stump1eb44332009-09-09 15:08:12 +00008959
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008960
8961 // The new class type must have the same or less qualifiers as the old type.
8962 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8963 Diag(New->getLocation(),
8964 diag::err_covariant_return_type_class_type_more_qualified)
8965 << New->getDeclName() << NewTy << OldTy;
8966 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8967 return true;
8968 };
Mike Stump1eb44332009-09-09 15:08:12 +00008969
Anders Carlssonc3a68b22009-05-14 19:52:19 +00008970 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00008971}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008972
Douglas Gregor4ba31362009-12-01 17:24:26 +00008973/// \brief Mark the given method pure.
8974///
8975/// \param Method the method to be marked pure.
8976///
8977/// \param InitRange the source range that covers the "0" initializer.
8978bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00008979 SourceLocation EndLoc = InitRange.getEnd();
8980 if (EndLoc.isValid())
8981 Method->setRangeEnd(EndLoc);
8982
Douglas Gregor4ba31362009-12-01 17:24:26 +00008983 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8984 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +00008985 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +00008986 }
Douglas Gregor4ba31362009-12-01 17:24:26 +00008987
8988 if (!Method->isInvalidDecl())
8989 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8990 << Method->getDeclName() << InitRange;
8991 return true;
8992}
8993
John McCall731ad842009-12-19 09:28:58 +00008994/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8995/// an initializer for the out-of-line declaration 'Dcl'. The scope
8996/// is a fresh scope pushed for just this purpose.
8997///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00008998/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8999/// static data member of class X, names should be looked up in the scope of
9000/// class X.
John McCalld226f652010-08-21 09:40:31 +00009001void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009002 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00009003 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009004
John McCall731ad842009-12-19 09:28:58 +00009005 // We should only get called for declarations with scope specifiers, like:
9006 // int foo::bar;
9007 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00009008 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009009}
9010
9011/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00009012/// initializer for the out-of-line declaration 'D'.
9013void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009014 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +00009015 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009016
John McCall731ad842009-12-19 09:28:58 +00009017 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00009018 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00009019}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009020
9021/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9022/// C++ if/switch/while/for statement.
9023/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00009024DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009025 // C++ 6.4p2:
9026 // The declarator shall not specify a function or an array.
9027 // The type-specifier-seq shall not contain typedef and shall not declare a
9028 // new class or enumeration.
9029 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9030 "Parser allowed 'typedef' as storage class of condition decl.");
9031
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009032 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00009033 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9034 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009035
9036 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9037 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9038 // would be created and CXXConditionDeclExpr wants a VarDecl.
9039 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9040 << D.getSourceRange();
9041 return DeclResult();
9042 } else if (OwnedTag && OwnedTag->isDefinition()) {
9043 // The type-specifier-seq shall not declare a new class or enumeration.
9044 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9045 }
9046
John McCalld226f652010-08-21 09:40:31 +00009047 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009048 if (!Dcl)
9049 return DeclResult();
9050
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00009051 return Dcl;
9052}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009053
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009054void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9055 bool DefinitionRequired) {
9056 // Ignore any vtable uses in unevaluated operands or for classes that do
9057 // not have a vtable.
9058 if (!Class->isDynamicClass() || Class->isDependentContext() ||
9059 CurContext->isDependentContext() ||
9060 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00009061 return;
9062
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009063 // Try to insert this class into the map.
9064 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9065 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9066 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9067 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00009068 // If we already had an entry, check to see if we are promoting this vtable
9069 // to required a definition. If so, we need to reappend to the VTableUses
9070 // list, since we may have already processed the first entry.
9071 if (DefinitionRequired && !Pos.first->second) {
9072 Pos.first->second = true;
9073 } else {
9074 // Otherwise, we can early exit.
9075 return;
9076 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009077 }
9078
9079 // Local classes need to have their virtual members marked
9080 // immediately. For all other classes, we mark their virtual members
9081 // at the end of the translation unit.
9082 if (Class->isLocalClass())
9083 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00009084 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009085 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00009086}
9087
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009088bool Sema::DefineUsedVTables() {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009089 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00009090 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +00009091
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009092 // Note: The VTableUses vector could grow as a result of marking
9093 // the members of a class as "used", so we check the size each
9094 // time through the loop and prefer indices (with are stable) to
9095 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +00009096 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009097 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00009098 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009099 if (!Class)
9100 continue;
9101
9102 SourceLocation Loc = VTableUses[I].second;
9103
9104 // If this class has a key function, but that key function is
9105 // defined in another translation unit, we don't need to emit the
9106 // vtable even though we're using it.
9107 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009108 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009109 switch (KeyFunction->getTemplateSpecializationKind()) {
9110 case TSK_Undeclared:
9111 case TSK_ExplicitSpecialization:
9112 case TSK_ExplicitInstantiationDeclaration:
9113 // The key function is in another translation unit.
9114 continue;
9115
9116 case TSK_ExplicitInstantiationDefinition:
9117 case TSK_ImplicitInstantiation:
9118 // We will be instantiating the key function.
9119 break;
9120 }
9121 } else if (!KeyFunction) {
9122 // If we have a class with no key function that is the subject
9123 // of an explicit instantiation declaration, suppress the
9124 // vtable; it will live with the explicit instantiation
9125 // definition.
9126 bool IsExplicitInstantiationDeclaration
9127 = Class->getTemplateSpecializationKind()
9128 == TSK_ExplicitInstantiationDeclaration;
9129 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9130 REnd = Class->redecls_end();
9131 R != REnd; ++R) {
9132 TemplateSpecializationKind TSK
9133 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9134 if (TSK == TSK_ExplicitInstantiationDeclaration)
9135 IsExplicitInstantiationDeclaration = true;
9136 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9137 IsExplicitInstantiationDeclaration = false;
9138 break;
9139 }
9140 }
9141
9142 if (IsExplicitInstantiationDeclaration)
9143 continue;
9144 }
9145
9146 // Mark all of the virtual members of this class as referenced, so
9147 // that we can build a vtable. Then, tell the AST consumer that a
9148 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +00009149 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009150 MarkVirtualMembersReferenced(Loc, Class);
9151 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9152 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9153
9154 // Optionally warn if we're emitting a weak vtable.
9155 if (Class->getLinkage() == ExternalLinkage &&
9156 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00009157 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009158 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9159 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009160 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009161 VTableUses.clear();
9162
Douglas Gregor78844032011-04-22 22:25:37 +00009163 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00009164}
Anders Carlssond6a637f2009-12-07 08:24:59 +00009165
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009166void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9167 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00009168 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9169 e = RD->method_end(); i != e; ++i) {
9170 CXXMethodDecl *MD = *i;
9171
9172 // C++ [basic.def.odr]p2:
9173 // [...] A virtual member function is used if it is not pure. [...]
9174 if (MD->isVirtual() && !MD->isPure())
9175 MarkDeclarationReferenced(Loc, MD);
9176 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009177
9178 // Only classes that have virtual bases need a VTT.
9179 if (RD->getNumVBases() == 0)
9180 return;
9181
9182 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9183 e = RD->bases_end(); i != e; ++i) {
9184 const CXXRecordDecl *Base =
9185 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00009186 if (Base->getNumVBases() == 0)
9187 continue;
9188 MarkVirtualMembersReferenced(Loc, Base);
9189 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00009190}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009191
9192/// SetIvarInitializers - This routine builds initialization ASTs for the
9193/// Objective-C implementation whose ivars need be initialized.
9194void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9195 if (!getLangOptions().CPlusPlus)
9196 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00009197 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009198 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9199 CollectIvarsToConstructOrDestruct(OID, ivars);
9200 if (ivars.empty())
9201 return;
Sean Huntcbb67482011-01-08 20:30:50 +00009202 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009203 for (unsigned i = 0; i < ivars.size(); i++) {
9204 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009205 if (Field->isInvalidDecl())
9206 continue;
9207
Sean Huntcbb67482011-01-08 20:30:50 +00009208 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009209 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9210 InitializationKind InitKind =
9211 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9212
9213 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009214 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00009215 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +00009216 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009217 // Note, MemberInit could actually come back empty if no initialization
9218 // is required (e.g., because it would call a trivial default constructor)
9219 if (!MemberInit.get() || MemberInit.isInvalid())
9220 continue;
John McCallb4eb64d2010-10-08 02:01:28 +00009221
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009222 Member =
Sean Huntcbb67482011-01-08 20:30:50 +00009223 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9224 SourceLocation(),
9225 MemberInit.takeAs<Expr>(),
9226 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009227 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009228
9229 // Be sure that the destructor is accessible and is marked as referenced.
9230 if (const RecordType *RecordTy
9231 = Context.getBaseElementType(Field->getType())
9232 ->getAs<RecordType>()) {
9233 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00009234 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00009235 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9236 CheckDestructorAccess(Field->getLocation(), Destructor,
9237 PDiag(diag::err_access_dtor_ivar)
9238 << Context.getBaseElementType(Field->getType()));
9239 }
9240 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00009241 }
9242 ObjCImplementation->setIvarInitializers(Context,
9243 AllToInit.data(), AllToInit.size());
9244 }
9245}
Sean Huntfe57eef2011-05-04 05:57:24 +00009246
Sean Huntebcbe1d2011-05-04 23:29:54 +00009247static
9248void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9249 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9250 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9251 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9252 Sema &S) {
9253 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9254 CE = Current.end();
9255 if (Ctor->isInvalidDecl())
9256 return;
9257
9258 const FunctionDecl *FNTarget = 0;
9259 CXXConstructorDecl *Target;
9260
9261 // We ignore the result here since if we don't have a body, Target will be
9262 // null below.
9263 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9264 Target
9265= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9266
9267 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9268 // Avoid dereferencing a null pointer here.
9269 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9270
9271 if (!Current.insert(Canonical))
9272 return;
9273
9274 // We know that beyond here, we aren't chaining into a cycle.
9275 if (!Target || !Target->isDelegatingConstructor() ||
9276 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9277 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9278 Valid.insert(*CI);
9279 Current.clear();
9280 // We've hit a cycle.
9281 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9282 Current.count(TCanonical)) {
9283 // If we haven't diagnosed this cycle yet, do so now.
9284 if (!Invalid.count(TCanonical)) {
9285 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +00009286 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +00009287 << Ctor;
9288
9289 // Don't add a note for a function delegating directo to itself.
9290 if (TCanonical != Canonical)
9291 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9292
9293 CXXConstructorDecl *C = Target;
9294 while (C->getCanonicalDecl() != Canonical) {
9295 (void)C->getTargetConstructor()->hasBody(FNTarget);
9296 assert(FNTarget && "Ctor cycle through bodiless function");
9297
9298 C
9299 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9300 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9301 }
9302 }
9303
9304 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9305 Invalid.insert(*CI);
9306 Current.clear();
9307 } else {
9308 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9309 }
9310}
9311
9312
Sean Huntfe57eef2011-05-04 05:57:24 +00009313void Sema::CheckDelegatingCtorCycles() {
9314 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9315
Sean Huntebcbe1d2011-05-04 23:29:54 +00009316 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9317 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +00009318
9319 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Sean Huntebcbe1d2011-05-04 23:29:54 +00009320 I = DelegatingCtorDecls.begin(),
9321 E = DelegatingCtorDecls.end();
9322 I != E; ++I) {
9323 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +00009324 }
Sean Huntebcbe1d2011-05-04 23:29:54 +00009325
9326 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9327 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +00009328}