blob: ce99efbd0bd2020f702da71fc87a80d0b86759a8 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000035#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000036#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000037#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000038
39using namespace clang;
40
Chris Lattner58258242008-04-10 02:22:51 +000041//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000051 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000052 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 Expr *DefaultArg;
54 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 public:
Mike Stump11289f42009-09-09 15:08:12 +000057 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000062 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 };
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-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 McCall8322c3a2011-02-13 04:07:26 +000068 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000069 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000071 }
72
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000077 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000090 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
93 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000094 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000095 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 }
Chris Lattner58258242008-04-10 02:22:51 +000099
Douglas Gregor8e12c382008-11-04 13:41:56 +0000100 return false;
101 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000102
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111 }
Chris Lattner58258242008-04-10 02:22:51 +0000112}
113
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-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)
Alexis Hunt6d5b96c2011-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 Smith938f40b2011-06-11 17:19:42 +0000126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000127 ClearExceptions();
128 ComputedEST = EST;
129 return;
130 }
131
Richard Smith938f40b2011-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
Alexis Hunt6d5b96c2011-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) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-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)
Alexis Hunt913820d2011-05-13 06:10:58 +0000177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000178 Exceptions.push_back(*E);
179}
180
Richard Smith938f40b2011-06-11 17:19:42 +0000181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183 return;
184
185 // FIXME:
186 //
187 // C++0x [except.spec]p14:
188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f’s implicit definition; f shall allow all exceptions if any
191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders Carlssonc80a1272009-08-25 02:29:20 +0000210bool
John McCallb268a282010-08-23 23:25:46 +0000211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000212 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-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 Jahanian8fb87ae2010-09-24 17:30:16 +0000225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000231 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000232 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000233 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000234 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000235
John McCallacf0ee52010-10-08 02:01:28 +0000236 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000237 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000238
Anders Carlssonc80a1272009-08-25 02:29:20 +0000239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregor758cb672010-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 Carlsson4562f1f2009-08-25 03:18:48 +0000254 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000255}
256
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000260void
John McCall48871652010-08-21 09:40:31 +0000261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000262 Expr *DefaultArg) {
263 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000264 return;
Mike Stump11289f42009-09-09 15:08:12 +0000265
John McCall48871652010-08-21 09:40:31 +0000266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000267 UnparsedDefaultArgLocs.erase(Param);
268
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000273 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000274 return;
275 }
276
Douglas Gregor6ff1fbf2010-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 Carlssonf1c26952009-08-25 01:02:06 +0000283 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000286 Param->setInvalidDecl();
287 return;
288 }
Mike Stump11289f42009-09-09 15:08:12 +0000289
John McCallb268a282010-08-23 23:25:46 +0000290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000291}
292
Douglas Gregor58354032008-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 McCall48871652010-08-21 09:40:31 +0000297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 if (!param)
301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000304 if (Param)
305 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000306
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000308}
309
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000313 if (!param)
314 return;
Mike Stump11289f42009-09-09 15:08:12 +0000315
John McCall48871652010-08-21 09:40:31 +0000316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000317
Anders Carlsson84613c42009-06-12 16:51:40 +0000318 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Anders Carlsson84613c42009-06-12 16:51:40 +0000320 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000321}
322
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000352 }
353 }
354 }
355 }
356}
357
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000365 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000388
Francois Pichet53fe2bb2011-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 Pichet8cb243a2011-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 Pichet93921652011-04-22 08:25:24 +0000405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000406 Invalid = false;
407 }
408 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000409
Francois Pichet8cb243a2011-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 Gregor08dc5842010-01-13 00:12:48 +0000415 // int f(int);
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000418 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000419 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor4f15f4d2009-09-17 19:51:30 +0000433 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-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 McCall5d413782010-12-06 08:20:24 +0000436 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000437 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
441 else
John McCalle61b02b2010-05-04 01:53:42 +0000442 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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();
Alexis Huntd051b872011-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 Gregorc732aba2009-09-11 18:44:32 +0000501 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000502 }
503 }
504
Douglas Gregorf40863c2010-02-12 07:32:17 +0000505 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000506 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000507
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000508 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000509}
510
Sebastian Redlfa453cf2011-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 Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000563 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000574 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000575 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000576 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000580 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000581 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000582 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000583 else
Mike Stump11289f42009-09-09 15:08:12 +0000584 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000585 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000586
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000598 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000599 Param->setDefaultArg(0);
600 }
601 }
602 }
603}
Douglas Gregor556877c2008-04-13 21:30:24 +0000604
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000611 assert(getLangOptions().CPlusPlus && "No class names in C!");
612
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000613 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000614 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000615 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000620 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000621 return &II == CurDecl->getIdentifier();
622 else
623 return false;
624}
625
Mike Stump11289f42009-09-09 15:08:12 +0000626/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Gregor752a5952011-01-03 22:36:02 +0000634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000636 QualType BaseType = TInfo->getType();
637
Douglas Gregor463421d2009-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 Gregor752a5952011-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 Gregor463421d2009-03-03 04:44:36 +0000653 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000655 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000656 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000657
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000676 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000677 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000678 << SpecifierRange)) {
679 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000680 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000681 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000682
Eli Friedmanc96d4962009-08-15 21:55:26 +0000683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000685 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000686 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000690
Anders Carlsson65c76d32011-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 Carlsson1eb95962011-01-24 16:26:15 +0000694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-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 McCall3696dcb2010-08-17 07:23:57 +0000702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000704
705 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000707 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000708 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000709}
710
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000713/// example:
714/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000715/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000716BaseResult
John McCall48871652010-08-21 09:40:31 +0000717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000718 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000721 if (!classdecl)
722 return true;
723
Douglas Gregorc40290e2009-03-09 23:48:35 +0000724 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000726 if (!Class)
727 return true;
728
Nick Lewycky19b9f952010-07-26 16:56:01 +0000729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000731
Douglas Gregor752a5952011-01-03 22:36:02 +0000732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000734 UPPC_BaseType))
735 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000736
Douglas Gregor463421d2009-03-03 04:44:36 +0000737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000738 Virtual, Access, TInfo,
739 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000740 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Douglas Gregor463421d2009-03-03 04:44:36 +0000742 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000743}
Douglas Gregor556877c2008-04-13 21:30:24 +0000744
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000754 // that the key is always the unqualified canonical type of the base
755 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000759 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000760 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000761 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000762 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000763 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000765 if (!Class->hasObjectMember()) {
766 if (const RecordType *FDTTy =
767 NewBaseType.getTypePtr()->getAs<RecordType>())
768 if (FDTTy->getDecl()->hasObjectMember())
769 Class->setHasObjectMember(true);
770 }
771
Douglas Gregor29a92472008-10-22 17:49:05 +0000772 if (KnownBaseTypes[NewBaseType]) {
773 // C++ [class.mi]p3:
774 // A class shall not be specified as a direct base class of a
775 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000776 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000777 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000778 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000779 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000780
781 // Delete the duplicate base class specifier; we're going to
782 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000783 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000784
785 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000786 } else {
787 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000788 KnownBaseTypes[NewBaseType] = Bases[idx];
789 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000790 }
791 }
792
793 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000794 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000795
796 // Delete the remaining (good) base class specifiers, since their
797 // data has been copied into the CXXRecordDecl.
798 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000799 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000800
801 return Invalid;
802}
803
804/// ActOnBaseSpecifiers - Attach the given base specifiers to the
805/// class, after checking whether there are any duplicate base
806/// classes.
John McCall48871652010-08-21 09:40:31 +0000807void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000808 unsigned NumBases) {
809 if (!ClassDecl || !Bases || !NumBases)
810 return;
811
812 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000813 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000814 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000815}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000816
John McCalle78aac42010-03-10 03:28:59 +0000817static CXXRecordDecl *GetClassForType(QualType T) {
818 if (const RecordType *RT = T->getAs<RecordType>())
819 return cast<CXXRecordDecl>(RT->getDecl());
820 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
821 return ICT->getDecl();
822 else
823 return 0;
824}
825
Douglas Gregor36d1b142009-10-06 17:59:45 +0000826/// \brief Determine whether the type \p Derived is a C++ class that is
827/// derived from the type \p Base.
828bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
829 if (!getLangOptions().CPlusPlus)
830 return false;
John McCalle78aac42010-03-10 03:28:59 +0000831
832 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
833 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000834 return false;
835
John McCalle78aac42010-03-10 03:28:59 +0000836 CXXRecordDecl *BaseRD = GetClassForType(Base);
837 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000838 return false;
839
John McCall67da35c2010-02-04 22:26:26 +0000840 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
841 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000842}
843
844/// \brief Determine whether the type \p Derived is a C++ class that is
845/// derived from the type \p Base.
846bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
847 if (!getLangOptions().CPlusPlus)
848 return false;
849
John McCalle78aac42010-03-10 03:28:59 +0000850 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
851 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000852 return false;
853
John McCalle78aac42010-03-10 03:28:59 +0000854 CXXRecordDecl *BaseRD = GetClassForType(Base);
855 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000856 return false;
857
Douglas Gregor36d1b142009-10-06 17:59:45 +0000858 return DerivedRD->isDerivedFrom(BaseRD, Paths);
859}
860
Anders Carlssona70cff62010-04-24 19:06:50 +0000861void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000862 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000863 assert(BasePathArray.empty() && "Base path array must be empty!");
864 assert(Paths.isRecordingPaths() && "Must record paths!");
865
866 const CXXBasePath &Path = Paths.front();
867
868 // We first go backward and check if we have a virtual base.
869 // FIXME: It would be better if CXXBasePath had the base specifier for
870 // the nearest virtual base.
871 unsigned Start = 0;
872 for (unsigned I = Path.size(); I != 0; --I) {
873 if (Path[I - 1].Base->isVirtual()) {
874 Start = I - 1;
875 break;
876 }
877 }
878
879 // Now add all bases.
880 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000881 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000882}
883
Douglas Gregor88d292c2010-05-13 16:44:06 +0000884/// \brief Determine whether the given base path includes a virtual
885/// base class.
John McCallcf142162010-08-07 06:22:56 +0000886bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
887 for (CXXCastPath::const_iterator B = BasePath.begin(),
888 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000889 B != BEnd; ++B)
890 if ((*B)->isVirtual())
891 return true;
892
893 return false;
894}
895
Douglas Gregor36d1b142009-10-06 17:59:45 +0000896/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
897/// conversion (where Derived and Base are class types) is
898/// well-formed, meaning that the conversion is unambiguous (and
899/// that all of the base classes are accessible). Returns true
900/// and emits a diagnostic if the code is ill-formed, returns false
901/// otherwise. Loc is the location where this routine should point to
902/// if there is an error, and Range is the source range to highlight
903/// if there is an error.
904bool
905Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000906 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000907 unsigned AmbigiousBaseConvID,
908 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000909 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000910 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000911 // First, determine whether the path from Derived to Base is
912 // ambiguous. This is slightly more expensive than checking whether
913 // the Derived to Base conversion exists, because here we need to
914 // explore multiple paths to determine if there is an ambiguity.
915 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
916 /*DetectVirtual=*/false);
917 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
918 assert(DerivationOkay &&
919 "Can only be used with a derived-to-base conversion");
920 (void)DerivationOkay;
921
922 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000923 if (InaccessibleBaseID) {
924 // Check that the base class can be accessed.
925 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
926 InaccessibleBaseID)) {
927 case AR_inaccessible:
928 return true;
929 case AR_accessible:
930 case AR_dependent:
931 case AR_delayed:
932 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000933 }
John McCall5b0829a2010-02-10 09:31:12 +0000934 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000935
936 // Build a base path if necessary.
937 if (BasePath)
938 BuildBasePathArray(Paths, *BasePath);
939 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000940 }
941
942 // We know that the derived-to-base conversion is ambiguous, and
943 // we're going to produce a diagnostic. Perform the derived-to-base
944 // search just one more time to compute all of the possible paths so
945 // that we can print them out. This is more expensive than any of
946 // the previous derived-to-base checks we've done, but at this point
947 // performance isn't as much of an issue.
948 Paths.clear();
949 Paths.setRecordingPaths(true);
950 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
951 assert(StillOkay && "Can only be used with a derived-to-base conversion");
952 (void)StillOkay;
953
954 // Build up a textual representation of the ambiguous paths, e.g.,
955 // D -> B -> A, that will be used to illustrate the ambiguous
956 // conversions in the diagnostic. We only print one of the paths
957 // to each base class subobject.
958 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
959
960 Diag(Loc, AmbigiousBaseConvID)
961 << Derived << Base << PathDisplayStr << Range << Name;
962 return true;
963}
964
965bool
966Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000967 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000968 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000969 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000970 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000971 IgnoreAccess ? 0
972 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000973 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000974 Loc, Range, DeclarationName(),
975 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000976}
977
978
979/// @brief Builds a string representing ambiguous paths from a
980/// specific derived class to different subobjects of the same base
981/// class.
982///
983/// This function builds a string that can be used in error messages
984/// to show the different paths that one can take through the
985/// inheritance hierarchy to go from the derived class to different
986/// subobjects of a base class. The result looks something like this:
987/// @code
988/// struct D -> struct B -> struct A
989/// struct D -> struct C -> struct A
990/// @endcode
991std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
992 std::string PathDisplayStr;
993 std::set<unsigned> DisplayedPaths;
994 for (CXXBasePaths::paths_iterator Path = Paths.begin();
995 Path != Paths.end(); ++Path) {
996 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
997 // We haven't displayed a path to this particular base
998 // class subobject yet.
999 PathDisplayStr += "\n ";
1000 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1001 for (CXXBasePath::const_iterator Element = Path->begin();
1002 Element != Path->end(); ++Element)
1003 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1004 }
1005 }
1006
1007 return PathDisplayStr;
1008}
1009
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001010//===----------------------------------------------------------------------===//
1011// C++ class member Handling
1012//===----------------------------------------------------------------------===//
1013
Abramo Bagnarad7340582010-06-05 05:09:32 +00001014/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001015Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1016 SourceLocation ASLoc,
1017 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001018 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001019 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001020 ASLoc, ColonLoc);
1021 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001022 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001023}
1024
Anders Carlssonfd835532011-01-20 05:57:14 +00001025/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001026void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +00001027 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1028 if (!MD || !MD->isVirtual())
1029 return;
1030
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001031 if (MD->isDependentContext())
1032 return;
1033
Anders Carlssonfd835532011-01-20 05:57:14 +00001034 // C++0x [class.virtual]p3:
1035 // If a virtual function is marked with the virt-specifier override and does
1036 // not override a member function of a base class,
1037 // the program is ill-formed.
1038 bool HasOverriddenMethods =
1039 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001040 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001041 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001042 diag::err_function_marked_override_not_overriding)
1043 << MD->getDeclName();
1044 return;
1045 }
1046}
1047
Anders Carlsson3f610c72011-01-20 16:25:36 +00001048/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1049/// function overrides a virtual member function marked 'final', according to
1050/// C++0x [class.virtual]p3.
1051bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1052 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001053 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001054 return false;
1055
1056 Diag(New->getLocation(), diag::err_final_function_overridden)
1057 << New->getDeclName();
1058 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1059 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001060}
1061
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001062/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1063/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001064/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1065/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1066/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001067Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001068Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001069 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001070 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith938f40b2011-06-11 17:19:42 +00001071 ExprTy *InitExpr, bool HasDeferredInit,
1072 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001073 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001074 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1075 DeclarationName Name = NameInfo.getName();
1076 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001077
1078 // For anonymous bitfields, the location should point to the type.
1079 if (Loc.isInvalid())
1080 Loc = D.getSourceRange().getBegin();
1081
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001082 Expr *BitWidth = static_cast<Expr*>(BW);
1083 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001084
John McCallb1cd7da2010-06-04 08:34:12 +00001085 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001086 assert(!DS.isFriendSpecified());
Richard Smith938f40b2011-06-11 17:19:42 +00001087 assert(!Init || !HasDeferredInit);
John McCall07e91c02009-08-06 02:15:43 +00001088
John McCallb1cd7da2010-06-04 08:34:12 +00001089 bool isFunc = false;
1090 if (D.isFunctionDeclarator())
1091 isFunc = true;
1092 else if (D.getNumTypeObjects() == 0 &&
1093 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +00001094 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +00001095 isFunc = TDType->isFunctionType();
1096 }
1097
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001098 // C++ 9.2p6: A member shall not be declared to have automatic storage
1099 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001100 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1101 // data members and cannot be applied to names declared const or static,
1102 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001103 switch (DS.getStorageClassSpec()) {
1104 case DeclSpec::SCS_unspecified:
1105 case DeclSpec::SCS_typedef:
1106 case DeclSpec::SCS_static:
1107 // FALL THROUGH.
1108 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001109 case DeclSpec::SCS_mutable:
1110 if (isFunc) {
1111 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001112 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001113 else
Chris Lattner3b054132008-11-19 05:08:23 +00001114 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001115
Sebastian Redl8071edb2008-11-17 23:24:37 +00001116 // FIXME: It would be nicer if the keyword was ignored only for this
1117 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001118 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001119 }
1120 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001121 default:
1122 if (DS.getStorageClassSpecLoc().isValid())
1123 Diag(DS.getStorageClassSpecLoc(),
1124 diag::err_storageclass_invalid_for_member);
1125 else
1126 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1127 D.getMutableDeclSpec().ClearStorageClassSpecs();
1128 }
1129
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001130 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1131 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001132 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001133
1134 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001135 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001136 CXXScopeSpec &SS = D.getCXXScopeSpec();
1137
Douglas Gregora007d362010-10-13 22:19:53 +00001138 if (SS.isSet() && !SS.isInvalid()) {
1139 // The user provided a superfluous scope specifier inside a class
1140 // definition:
1141 //
1142 // class X {
1143 // int X::member;
1144 // };
1145 DeclContext *DC = 0;
1146 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1147 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1148 << Name << FixItHint::CreateRemoval(SS.getRange());
1149 else
1150 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1151 << Name << SS.getRange();
1152
1153 SS.clear();
1154 }
1155
Douglas Gregor3447e762009-08-20 22:52:58 +00001156 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001157 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001158 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001159 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001160 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001161 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001162 assert(!HasDeferredInit);
1163
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001164 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001165 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001166 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001167 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001168
1169 // Non-instance-fields can't have a bitfield.
1170 if (BitWidth) {
1171 if (Member->isInvalidDecl()) {
1172 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001173 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001174 // C++ 9.6p3: A bit-field shall not be a static member.
1175 // "static member 'A' cannot be a bit-field"
1176 Diag(Loc, diag::err_static_not_bitfield)
1177 << Name << BitWidth->getSourceRange();
1178 } else if (isa<TypedefDecl>(Member)) {
1179 // "typedef member 'x' cannot be a bit-field"
1180 Diag(Loc, diag::err_typedef_not_bitfield)
1181 << Name << BitWidth->getSourceRange();
1182 } else {
1183 // A function typedef ("typedef int f(); f a;").
1184 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1185 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001186 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001187 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001188 }
Mike Stump11289f42009-09-09 15:08:12 +00001189
Chris Lattnerd26760a2009-03-05 23:01:03 +00001190 BitWidth = 0;
1191 Member->setInvalidDecl();
1192 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001193
1194 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Douglas Gregor3447e762009-08-20 22:52:58 +00001196 // If we have declared a member function template, set the access of the
1197 // templated declaration as well.
1198 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1199 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001200 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001201
Anders Carlsson13a69102011-01-20 04:34:22 +00001202 if (VS.isOverrideSpecified()) {
1203 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1204 if (!MD || !MD->isVirtual()) {
1205 Diag(Member->getLocStart(),
1206 diag::override_keyword_only_allowed_on_virtual_member_functions)
1207 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001208 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001209 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001210 }
1211 if (VS.isFinalSpecified()) {
1212 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1213 if (!MD || !MD->isVirtual()) {
1214 Diag(Member->getLocStart(),
1215 diag::override_keyword_only_allowed_on_virtual_member_functions)
1216 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001217 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001218 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001219 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001220
Douglas Gregorf2f08062011-03-08 17:10:18 +00001221 if (VS.getLastLocation().isValid()) {
1222 // Update the end location of a method that has a virt-specifiers.
1223 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1224 MD->setRangeEnd(VS.getLastLocation());
1225 }
1226
Anders Carlssonc87f8612011-01-20 06:29:02 +00001227 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001228
Douglas Gregor92751d42008-11-17 22:58:34 +00001229 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001230
Douglas Gregor0c880302009-03-11 23:00:04 +00001231 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001232 AddInitializerToDecl(Member, Init, false,
1233 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith938f40b2011-06-11 17:19:42 +00001234 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1235 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1236 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1237 // data member if a brace-or-equal-initializer is provided.
1238 Diag(Loc, diag::err_auto_var_requires_init)
1239 << Name << cast<ValueDecl>(Member)->getType();
1240 Member->setInvalidDecl();
1241 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001242
Richard Smithb2bc2e62011-02-21 20:05:19 +00001243 FinalizeDeclaration(Member);
1244
John McCall25849ca2011-02-15 07:12:36 +00001245 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001246 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001247 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001248}
1249
Richard Smith938f40b2011-06-11 17:19:42 +00001250/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1251/// in-class initializer for a non-static C++ class member. Such parsing
1252/// is deferred until the class is complete.
1253void
1254Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1255 Expr *InitExpr) {
1256 FieldDecl *FD = cast<FieldDecl>(D);
1257
1258 if (!InitExpr) {
1259 FD->setInvalidDecl();
1260 FD->removeInClassInitializer();
1261 return;
1262 }
1263
1264 ExprResult Init = InitExpr;
1265 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1266 // FIXME: if there is no EqualLoc, this is list-initialization.
1267 Init = PerformCopyInitialization(
1268 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1269 if (Init.isInvalid()) {
1270 FD->setInvalidDecl();
1271 return;
1272 }
1273
1274 CheckImplicitConversions(Init.get(), EqualLoc);
1275 }
1276
1277 // C++0x [class.base.init]p7:
1278 // The initialization of each base and member constitutes a
1279 // full-expression.
1280 Init = MaybeCreateExprWithCleanups(Init);
1281 if (Init.isInvalid()) {
1282 FD->setInvalidDecl();
1283 return;
1284 }
1285
1286 InitExpr = Init.release();
1287
1288 FD->setInClassInitializer(InitExpr);
1289}
1290
Douglas Gregor15e77a22009-12-31 09:10:24 +00001291/// \brief Find the direct and/or virtual base specifiers that
1292/// correspond to the given base type, for use in base initialization
1293/// within a constructor.
1294static bool FindBaseInitializer(Sema &SemaRef,
1295 CXXRecordDecl *ClassDecl,
1296 QualType BaseType,
1297 const CXXBaseSpecifier *&DirectBaseSpec,
1298 const CXXBaseSpecifier *&VirtualBaseSpec) {
1299 // First, check for a direct base class.
1300 DirectBaseSpec = 0;
1301 for (CXXRecordDecl::base_class_const_iterator Base
1302 = ClassDecl->bases_begin();
1303 Base != ClassDecl->bases_end(); ++Base) {
1304 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1305 // We found a direct base of this type. That's what we're
1306 // initializing.
1307 DirectBaseSpec = &*Base;
1308 break;
1309 }
1310 }
1311
1312 // Check for a virtual base class.
1313 // FIXME: We might be able to short-circuit this if we know in advance that
1314 // there are no virtual bases.
1315 VirtualBaseSpec = 0;
1316 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1317 // We haven't found a base yet; search the class hierarchy for a
1318 // virtual base class.
1319 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1320 /*DetectVirtual=*/false);
1321 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1322 BaseType, Paths)) {
1323 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1324 Path != Paths.end(); ++Path) {
1325 if (Path->back().Base->isVirtual()) {
1326 VirtualBaseSpec = Path->back().Base;
1327 break;
1328 }
1329 }
1330 }
1331 }
1332
1333 return DirectBaseSpec || VirtualBaseSpec;
1334}
1335
Douglas Gregore8381c02008-11-05 04:29:56 +00001336/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001337MemInitResult
John McCall48871652010-08-21 09:40:31 +00001338Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001339 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001340 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001341 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001342 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001343 SourceLocation IdLoc,
1344 SourceLocation LParenLoc,
1345 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001346 SourceLocation RParenLoc,
1347 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001348 if (!ConstructorD)
1349 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001350
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001351 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001352
1353 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001354 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001355 if (!Constructor) {
1356 // The user wrote a constructor initializer on a function that is
1357 // not a C++ constructor. Ignore the error for now, because we may
1358 // have more member initializers coming; we'll diagnose it just
1359 // once in ActOnMemInitializers.
1360 return true;
1361 }
1362
1363 CXXRecordDecl *ClassDecl = Constructor->getParent();
1364
1365 // C++ [class.base.init]p2:
1366 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001367 // constructor's class and, if not found in that scope, are looked
1368 // up in the scope containing the constructor's definition.
1369 // [Note: if the constructor's class contains a member with the
1370 // same name as a direct or virtual base class of the class, a
1371 // mem-initializer-id naming the member or base class and composed
1372 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001373 // mem-initializer-id for the hidden base class may be specified
1374 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001375 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001376 // Look for a member, first.
1377 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001378 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001379 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001380 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001381 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001382
Douglas Gregor44e7df62011-01-04 00:32:56 +00001383 if (Member) {
1384 if (EllipsisLoc.isValid())
1385 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1386 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1387
Francois Pichetd583da02010-12-04 09:14:42 +00001388 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001389 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001390 }
1391
Francois Pichetd583da02010-12-04 09:14:42 +00001392 // Handle anonymous union case.
1393 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001394 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1395 if (EllipsisLoc.isValid())
1396 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1397 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1398
Francois Pichetd583da02010-12-04 09:14:42 +00001399 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1400 NumArgs, IdLoc,
1401 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001402 }
Francois Pichetd583da02010-12-04 09:14:42 +00001403 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001404 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001405 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001406 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001407 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001408
1409 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001410 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001411 } else {
1412 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1413 LookupParsedName(R, S, &SS);
1414
1415 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1416 if (!TyD) {
1417 if (R.isAmbiguous()) return true;
1418
John McCallda6841b2010-04-09 19:01:14 +00001419 // We don't want access-control diagnostics here.
1420 R.suppressDiagnostics();
1421
Douglas Gregora3b624a2010-01-19 06:46:48 +00001422 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1423 bool NotUnknownSpecialization = false;
1424 DeclContext *DC = computeDeclContext(SS, false);
1425 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1426 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1427
1428 if (!NotUnknownSpecialization) {
1429 // When the scope specifier can refer to a member of an unknown
1430 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001431 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1432 SS.getWithLocInContext(Context),
1433 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001434 if (BaseType.isNull())
1435 return true;
1436
Douglas Gregora3b624a2010-01-19 06:46:48 +00001437 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001438 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001439 }
1440 }
1441
Douglas Gregor15e77a22009-12-31 09:10:24 +00001442 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001443 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001444 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1445 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001446 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001447 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001448 // We have found a non-static data member with a similar
1449 // name to what was typed; complain and initialize that
1450 // member.
1451 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1452 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001453 << FixItHint::CreateReplacement(R.getNameLoc(),
1454 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001455 Diag(Member->getLocation(), diag::note_previous_decl)
1456 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001457
1458 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1459 LParenLoc, RParenLoc);
1460 }
1461 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1462 const CXXBaseSpecifier *DirectBaseSpec;
1463 const CXXBaseSpecifier *VirtualBaseSpec;
1464 if (FindBaseInitializer(*this, ClassDecl,
1465 Context.getTypeDeclType(Type),
1466 DirectBaseSpec, VirtualBaseSpec)) {
1467 // We have found a direct or virtual base class with a
1468 // similar name to what was typed; complain and initialize
1469 // that base class.
1470 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1471 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001472 << FixItHint::CreateReplacement(R.getNameLoc(),
1473 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001474
1475 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1476 : VirtualBaseSpec;
1477 Diag(BaseSpec->getSourceRange().getBegin(),
1478 diag::note_base_class_specified_here)
1479 << BaseSpec->getType()
1480 << BaseSpec->getSourceRange();
1481
Douglas Gregor15e77a22009-12-31 09:10:24 +00001482 TyD = Type;
1483 }
1484 }
1485 }
1486
Douglas Gregora3b624a2010-01-19 06:46:48 +00001487 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001488 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1489 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1490 return true;
1491 }
John McCallb5a0d312009-12-21 10:41:20 +00001492 }
1493
Douglas Gregora3b624a2010-01-19 06:46:48 +00001494 if (BaseType.isNull()) {
1495 BaseType = Context.getTypeDeclType(TyD);
1496 if (SS.isSet()) {
1497 NestedNameSpecifier *Qualifier =
1498 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001499
Douglas Gregora3b624a2010-01-19 06:46:48 +00001500 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001501 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001502 }
John McCallb5a0d312009-12-21 10:41:20 +00001503 }
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
John McCallbcd03502009-12-07 02:54:59 +00001506 if (!TInfo)
1507 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001508
John McCallbcd03502009-12-07 02:54:59 +00001509 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001510 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001511}
1512
John McCalle22a04a2009-11-04 23:02:40 +00001513/// Checks an initializer expression for use of uninitialized fields, such as
1514/// containing the field that is being initialized. Returns true if there is an
1515/// uninitialized field was used an updates the SourceLocation parameter; false
1516/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001517static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001518 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001519 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001520 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1521
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001522 if (isa<CallExpr>(S)) {
1523 // Do not descend into function calls or constructors, as the use
1524 // of an uninitialized field may be valid. One would have to inspect
1525 // the contents of the function/ctor to determine if it is safe or not.
1526 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1527 // may be safe, depending on what the function/ctor does.
1528 return false;
1529 }
1530 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1531 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001532
1533 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1534 // The member expression points to a static data member.
1535 assert(VD->isStaticDataMember() &&
1536 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001537 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001538 return false;
1539 }
1540
1541 if (isa<EnumConstantDecl>(RhsField)) {
1542 // The member expression points to an enum.
1543 return false;
1544 }
1545
John McCalle22a04a2009-11-04 23:02:40 +00001546 if (RhsField == LhsField) {
1547 // Initializing a field with itself. Throw a warning.
1548 // But wait; there are exceptions!
1549 // Exception #1: The field may not belong to this record.
1550 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001551 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001552 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1553 // Even though the field matches, it does not belong to this record.
1554 return false;
1555 }
1556 // None of the exceptions triggered; return true to indicate an
1557 // uninitialized field was used.
1558 *L = ME->getMemberLoc();
1559 return true;
1560 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001561 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001562 // sizeof/alignof doesn't reference contents, do not warn.
1563 return false;
1564 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1565 // address-of doesn't reference contents (the pointer may be dereferenced
1566 // in the same expression but it would be rare; and weird).
1567 if (UOE->getOpcode() == UO_AddrOf)
1568 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001569 }
John McCall8322c3a2011-02-13 04:07:26 +00001570 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001571 if (!*it) {
1572 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001573 continue;
1574 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001575 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1576 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001577 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001578 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001579}
1580
John McCallfaf5fb42010-08-26 23:41:50 +00001581MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001582Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001583 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001584 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001585 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001586 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1587 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1588 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001589 "Member must be a FieldDecl or IndirectFieldDecl");
1590
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001591 if (Member->isInvalidDecl())
1592 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001593
John McCalle22a04a2009-11-04 23:02:40 +00001594 // Diagnose value-uses of fields to initialize themselves, e.g.
1595 // foo(foo)
1596 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001597 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001598 for (unsigned i = 0; i < NumArgs; ++i) {
1599 SourceLocation L;
1600 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1601 // FIXME: Return true in the case when other fields are used before being
1602 // uninitialized. For example, let this field be the i'th field. When
1603 // initializing the i'th field, throw a warning if any of the >= i'th
1604 // fields are used, as they are not yet initialized.
1605 // Right now we are only handling the case where the i'th field uses
1606 // itself in its initializer.
1607 Diag(L, diag::warn_field_is_uninit);
1608 }
1609 }
1610
Eli Friedman8e1433b2009-07-29 19:44:27 +00001611 bool HasDependentArg = false;
1612 for (unsigned i = 0; i < NumArgs; i++)
1613 HasDependentArg |= Args[i]->isTypeDependent();
1614
Chandler Carruthd44c3102010-12-06 09:23:57 +00001615 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001616 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617 // Can't check initialization for a member of dependent type or when
1618 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001619 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1620 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001621
1622 // Erase any temporaries within this evaluation context; we're not
1623 // going to track them in the AST, since we'll be rebuilding the
1624 // ASTs during template instantiation.
1625 ExprTemporaries.erase(
1626 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1627 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001628 } else {
1629 // Initialize the member.
1630 InitializedEntity MemberEntity =
1631 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1632 : InitializedEntity::InitializeMember(IndirectMember, 0);
1633 InitializationKind Kind =
1634 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001635
Chandler Carruthd44c3102010-12-06 09:23:57 +00001636 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1637
1638 ExprResult MemberInit =
1639 InitSeq.Perform(*this, MemberEntity, Kind,
1640 MultiExprArg(*this, Args, NumArgs), 0);
1641 if (MemberInit.isInvalid())
1642 return true;
1643
1644 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1645
1646 // C++0x [class.base.init]p7:
1647 // The initialization of each base and member constitutes a
1648 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001649 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001650 if (MemberInit.isInvalid())
1651 return true;
1652
1653 // If we are in a dependent context, template instantiation will
1654 // perform this type-checking again. Just save the arguments that we
1655 // received in a ParenListExpr.
1656 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1657 // of the information that we have about the member
1658 // initializer. However, deconstructing the ASTs is a dicey process,
1659 // and this approach is far more likely to get the corner cases right.
1660 if (CurContext->isDependentContext())
1661 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1662 RParenLoc);
1663 else
1664 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001665 }
1666
Chandler Carruthd44c3102010-12-06 09:23:57 +00001667 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001668 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001669 IdLoc, LParenLoc, Init,
1670 RParenLoc);
1671 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001672 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001673 IdLoc, LParenLoc, Init,
1674 RParenLoc);
1675 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001676}
1677
John McCallfaf5fb42010-08-26 23:41:50 +00001678MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001679Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1680 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001681 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001682 SourceLocation LParenLoc,
1683 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001684 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001685 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1686 if (!LangOpts.CPlusPlus0x)
1687 return Diag(Loc, diag::err_delegation_0x_only)
1688 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001689
Alexis Huntc5575cc2011-02-26 19:13:13 +00001690 // Initialize the object.
1691 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1692 QualType(ClassDecl->getTypeForDecl(), 0));
1693 InitializationKind Kind =
1694 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1695
1696 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1697
1698 ExprResult DelegationInit =
1699 InitSeq.Perform(*this, DelegationEntity, Kind,
1700 MultiExprArg(*this, Args, NumArgs), 0);
1701 if (DelegationInit.isInvalid())
1702 return true;
1703
1704 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001705 CXXConstructorDecl *Constructor
1706 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001707 assert(Constructor && "Delegating constructor with no target?");
1708
1709 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1710
1711 // C++0x [class.base.init]p7:
1712 // The initialization of each base and member constitutes a
1713 // full-expression.
1714 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1715 if (DelegationInit.isInvalid())
1716 return true;
1717
1718 // If we are in a dependent context, template instantiation will
1719 // perform this type-checking again. Just save the arguments that we
1720 // received in a ParenListExpr.
1721 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1722 // of the information that we have about the base
1723 // initializer. However, deconstructing the ASTs is a dicey process,
1724 // and this approach is far more likely to get the corner cases right.
1725 if (CurContext->isDependentContext()) {
1726 ExprResult Init
1727 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1728 NumArgs, RParenLoc));
1729 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1730 Constructor, Init.takeAs<Expr>(),
1731 RParenLoc);
1732 }
1733
1734 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1735 DelegationInit.takeAs<Expr>(),
1736 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001737}
1738
1739MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001740Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001741 Expr **Args, unsigned NumArgs,
1742 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001743 CXXRecordDecl *ClassDecl,
1744 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001745 bool HasDependentArg = false;
1746 for (unsigned i = 0; i < NumArgs; i++)
1747 HasDependentArg |= Args[i]->isTypeDependent();
1748
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001749 SourceLocation BaseLoc
1750 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1751
1752 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1753 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1754 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1755
1756 // C++ [class.base.init]p2:
1757 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001758 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001759 // of that class, the mem-initializer is ill-formed. A
1760 // mem-initializer-list can initialize a base class using any
1761 // name that denotes that base class type.
1762 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1763
Douglas Gregor44e7df62011-01-04 00:32:56 +00001764 if (EllipsisLoc.isValid()) {
1765 // This is a pack expansion.
1766 if (!BaseType->containsUnexpandedParameterPack()) {
1767 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1768 << SourceRange(BaseLoc, RParenLoc);
1769
1770 EllipsisLoc = SourceLocation();
1771 }
1772 } else {
1773 // Check for any unexpanded parameter packs.
1774 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1775 return true;
1776
1777 for (unsigned I = 0; I != NumArgs; ++I)
1778 if (DiagnoseUnexpandedParameterPack(Args[I]))
1779 return true;
1780 }
1781
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001782 // Check for direct and virtual base classes.
1783 const CXXBaseSpecifier *DirectBaseSpec = 0;
1784 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1785 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001786 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1787 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001788 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1789 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001790
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001791 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1792 VirtualBaseSpec);
1793
1794 // C++ [base.class.init]p2:
1795 // Unless the mem-initializer-id names a nonstatic data member of the
1796 // constructor's class or a direct or virtual base of that class, the
1797 // mem-initializer is ill-formed.
1798 if (!DirectBaseSpec && !VirtualBaseSpec) {
1799 // If the class has any dependent bases, then it's possible that
1800 // one of those types will resolve to the same type as
1801 // BaseType. Therefore, just treat this as a dependent base
1802 // class initialization. FIXME: Should we try to check the
1803 // initialization anyway? It seems odd.
1804 if (ClassDecl->hasAnyDependentBases())
1805 Dependent = true;
1806 else
1807 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1808 << BaseType << Context.getTypeDeclType(ClassDecl)
1809 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1810 }
1811 }
1812
1813 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001814 // Can't check initialization for a base of dependent type or when
1815 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001816 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001817 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1818 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001819
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001820 // Erase any temporaries within this evaluation context; we're not
1821 // going to track them in the AST, since we'll be rebuilding the
1822 // ASTs during template instantiation.
1823 ExprTemporaries.erase(
1824 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1825 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001826
Alexis Hunt1d792652011-01-08 20:30:50 +00001827 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001828 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001829 LParenLoc,
1830 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001831 RParenLoc,
1832 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001833 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001834
1835 // C++ [base.class.init]p2:
1836 // If a mem-initializer-id is ambiguous because it designates both
1837 // a direct non-virtual base class and an inherited virtual base
1838 // class, the mem-initializer is ill-formed.
1839 if (DirectBaseSpec && VirtualBaseSpec)
1840 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001841 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001842
1843 CXXBaseSpecifier *BaseSpec
1844 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1845 if (!BaseSpec)
1846 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1847
1848 // Initialize the base.
1849 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001850 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001851 InitializationKind Kind =
1852 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1853
1854 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1855
John McCalldadc5752010-08-24 06:29:42 +00001856 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001857 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001858 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001859 if (BaseInit.isInvalid())
1860 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001861
1862 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001863
1864 // C++0x [class.base.init]p7:
1865 // The initialization of each base and member constitutes a
1866 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001867 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001868 if (BaseInit.isInvalid())
1869 return true;
1870
1871 // If we are in a dependent context, template instantiation will
1872 // perform this type-checking again. Just save the arguments that we
1873 // received in a ParenListExpr.
1874 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1875 // of the information that we have about the base
1876 // initializer. However, deconstructing the ASTs is a dicey process,
1877 // and this approach is far more likely to get the corner cases right.
1878 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001879 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001880 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1881 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001882 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001883 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001884 LParenLoc,
1885 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001886 RParenLoc,
1887 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001888 }
1889
Alexis Hunt1d792652011-01-08 20:30:50 +00001890 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001891 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001892 LParenLoc,
1893 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001894 RParenLoc,
1895 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001896}
1897
Anders Carlsson1b00e242010-04-23 03:10:23 +00001898/// ImplicitInitializerKind - How an implicit base or member initializer should
1899/// initialize its base or member.
1900enum ImplicitInitializerKind {
1901 IIK_Default,
1902 IIK_Copy,
1903 IIK_Move
1904};
1905
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001906static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001907BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001908 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001909 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001910 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001911 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001912 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001913 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1914 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001915
John McCalldadc5752010-08-24 06:29:42 +00001916 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001917
1918 switch (ImplicitInitKind) {
1919 case IIK_Default: {
1920 InitializationKind InitKind
1921 = InitializationKind::CreateDefault(Constructor->getLocation());
1922 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1923 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001924 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001925 break;
1926 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001927
Anders Carlsson1b00e242010-04-23 03:10:23 +00001928 case IIK_Copy: {
1929 ParmVarDecl *Param = Constructor->getParamDecl(0);
1930 QualType ParamType = Param->getType().getNonReferenceType();
1931
1932 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001933 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001934 Constructor->getLocation(), ParamType,
1935 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001936
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001937 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001938 QualType ArgTy =
1939 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1940 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001941
1942 CXXCastPath BasePath;
1943 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001944 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1945 CK_UncheckedDerivedToBase,
1946 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001947
Anders Carlsson1b00e242010-04-23 03:10:23 +00001948 InitializationKind InitKind
1949 = InitializationKind::CreateDirect(Constructor->getLocation(),
1950 SourceLocation(), SourceLocation());
1951 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1952 &CopyCtorArg, 1);
1953 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001954 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001955 break;
1956 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001957
Anders Carlsson1b00e242010-04-23 03:10:23 +00001958 case IIK_Move:
1959 assert(false && "Unhandled initializer kind!");
1960 }
John McCallb268a282010-08-23 23:25:46 +00001961
Douglas Gregora40433a2010-12-07 00:41:46 +00001962 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001963 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001964 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001965
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001966 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001967 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001968 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1969 SourceLocation()),
1970 BaseSpec->isVirtual(),
1971 SourceLocation(),
1972 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001973 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001974 SourceLocation());
1975
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001976 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001977}
1978
Anders Carlsson3c1db572010-04-23 02:15:47 +00001979static bool
1980BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001981 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001982 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001983 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001984 if (Field->isInvalidDecl())
1985 return true;
1986
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001987 SourceLocation Loc = Constructor->getLocation();
1988
Anders Carlsson423f5d82010-04-23 16:04:08 +00001989 if (ImplicitInitKind == IIK_Copy) {
1990 ParmVarDecl *Param = Constructor->getParamDecl(0);
1991 QualType ParamType = Param->getType().getNonReferenceType();
1992
1993 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001994 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001995 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001996
1997 // Build a reference to this field within the parameter.
1998 CXXScopeSpec SS;
1999 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2000 Sema::LookupMemberName);
2001 MemberLookup.addDecl(Field, AS_public);
2002 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00002003 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00002004 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002005 ParamType, Loc,
2006 /*IsArrow=*/false,
2007 SS,
2008 /*FirstQualifierInScope=*/0,
2009 MemberLookup,
2010 /*TemplateArgs=*/0);
2011 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002012 return true;
2013
Douglas Gregor94f9a482010-05-05 05:51:00 +00002014 // When the field we are copying is an array, create index variables for
2015 // each dimension of the array. We use these index variables to subscript
2016 // the source array, and other clients (e.g., CodeGen) will perform the
2017 // necessary iteration with these index variables.
2018 llvm::SmallVector<VarDecl *, 4> IndexVariables;
2019 QualType BaseType = Field->getType();
2020 QualType SizeType = SemaRef.Context.getSizeType();
2021 while (const ConstantArrayType *Array
2022 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2023 // Create the iteration variable for this array index.
2024 IdentifierInfo *IterationVarName = 0;
2025 {
2026 llvm::SmallString<8> Str;
2027 llvm::raw_svector_ostream OS(Str);
2028 OS << "__i" << IndexVariables.size();
2029 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2030 }
2031 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002032 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002033 IterationVarName, SizeType,
2034 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002035 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002036 IndexVariables.push_back(IterationVar);
2037
2038 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002039 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002040 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002041 assert(!IterationVarRef.isInvalid() &&
2042 "Reference to invented variable cannot fail!");
2043
2044 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00002045 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002046 Loc,
John McCallb268a282010-08-23 23:25:46 +00002047 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002048 Loc);
2049 if (CopyCtorArg.isInvalid())
2050 return true;
2051
2052 BaseType = Array->getElementType();
2053 }
2054
2055 // Construct the entity that we will be initializing. For an array, this
2056 // will be first element in the array, which may require several levels
2057 // of array-subscript entities.
2058 llvm::SmallVector<InitializedEntity, 4> Entities;
2059 Entities.reserve(1 + IndexVariables.size());
2060 Entities.push_back(InitializedEntity::InitializeMember(Field));
2061 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2062 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2063 0,
2064 Entities.back()));
2065
2066 // Direct-initialize to use the copy constructor.
2067 InitializationKind InitKind =
2068 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2069
2070 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2071 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2072 &CopyCtorArgE, 1);
2073
John McCalldadc5752010-08-24 06:29:42 +00002074 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002075 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002076 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002077 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002078 if (MemberInit.isInvalid())
2079 return true;
2080
2081 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00002082 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002083 MemberInit.takeAs<Expr>(), Loc,
2084 IndexVariables.data(),
2085 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002086 return false;
2087 }
2088
Anders Carlsson423f5d82010-04-23 16:04:08 +00002089 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2090
Anders Carlsson3c1db572010-04-23 02:15:47 +00002091 QualType FieldBaseElementType =
2092 SemaRef.Context.getBaseElementType(Field->getType());
2093
Anders Carlsson3c1db572010-04-23 02:15:47 +00002094 if (FieldBaseElementType->isRecordType()) {
2095 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002096 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002097 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002098
2099 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002100 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002101 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002102
Douglas Gregora40433a2010-12-07 00:41:46 +00002103 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002104 if (MemberInit.isInvalid())
2105 return true;
2106
2107 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002108 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002109 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002110 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002111 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002112 return false;
2113 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002114
Alexis Hunt8b455182011-05-17 00:19:05 +00002115 if (!Field->getParent()->isUnion()) {
2116 if (FieldBaseElementType->isReferenceType()) {
2117 SemaRef.Diag(Constructor->getLocation(),
2118 diag::err_uninitialized_member_in_ctor)
2119 << (int)Constructor->isImplicit()
2120 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2121 << 0 << Field->getDeclName();
2122 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2123 return true;
2124 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002125
Alexis Hunt8b455182011-05-17 00:19:05 +00002126 if (FieldBaseElementType.isConstQualified()) {
2127 SemaRef.Diag(Constructor->getLocation(),
2128 diag::err_uninitialized_member_in_ctor)
2129 << (int)Constructor->isImplicit()
2130 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2131 << 1 << Field->getDeclName();
2132 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2133 return true;
2134 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002135 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002136
2137 // Nothing to initialize.
2138 CXXMemberInit = 0;
2139 return false;
2140}
John McCallbc83b3f2010-05-20 23:23:51 +00002141
2142namespace {
2143struct BaseAndFieldInfo {
2144 Sema &S;
2145 CXXConstructorDecl *Ctor;
2146 bool AnyErrorsInInits;
2147 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002148 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2149 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002150
2151 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2152 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2153 // FIXME: Handle implicit move constructors.
2154 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2155 IIK = IIK_Copy;
2156 else
2157 IIK = IIK_Default;
2158 }
2159};
2160}
2161
Richard Smith938f40b2011-06-11 17:19:42 +00002162static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallbc83b3f2010-05-20 23:23:51 +00002163 FieldDecl *Top, FieldDecl *Field) {
2164
Chandler Carruth139e9622010-06-30 02:59:29 +00002165 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002166 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002167 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002168 return false;
2169 }
2170
Richard Smith938f40b2011-06-11 17:19:42 +00002171 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2172 // has a brace-or-equal-initializer, the entity is initialized as specified
2173 // in [dcl.init].
2174 if (Field->hasInClassInitializer()) {
2175 Info.AllToInit.push_back(
2176 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2177 SourceLocation(),
2178 SourceLocation(), 0,
2179 SourceLocation()));
2180 return false;
2181 }
2182
John McCallbc83b3f2010-05-20 23:23:51 +00002183 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2184 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2185 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002186 CXXRecordDecl *FieldClassDecl
2187 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002188
2189 // Even though union members never have non-trivial default
2190 // constructions in C++03, we still build member initializers for aggregate
2191 // record types which can be union members, and C++0x allows non-trivial
2192 // default constructors for union members, so we ensure that only one
2193 // member is initialized for these.
2194 if (FieldClassDecl->isUnion()) {
2195 // First check for an explicit initializer for one field.
2196 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2197 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002198 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002199 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002200
2201 // Once we've initialized a field of an anonymous union, the union
2202 // field in the class is also initialized, so exit immediately.
2203 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002204 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002205 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002206 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002207 }
2208 }
2209
2210 // Fallthrough and construct a default initializer for the union as
2211 // a whole, which can call its default constructor if such a thing exists
2212 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2213 // behavior going forward with C++0x, when anonymous unions there are
2214 // finalized, we should revisit this.
2215 } else {
2216 // For structs, we simply descend through to initialize all members where
2217 // necessary.
2218 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2219 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith938f40b2011-06-11 17:19:42 +00002220 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruth139e9622010-06-30 02:59:29 +00002221 return true;
2222 }
2223 }
John McCallbc83b3f2010-05-20 23:23:51 +00002224 }
2225
2226 // Don't try to build an implicit initializer if there were semantic
2227 // errors in any of the initializers (and therefore we might be
2228 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002229 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002230 return false;
2231
Alexis Hunt1d792652011-01-08 20:30:50 +00002232 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002233 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2234 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002235
Francois Pichetd583da02010-12-04 09:14:42 +00002236 if (Init)
2237 Info.AllToInit.push_back(Init);
2238
John McCallbc83b3f2010-05-20 23:23:51 +00002239 return false;
2240}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002241
2242bool
2243Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2244 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002245 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002246 Constructor->setNumCtorInitializers(1);
2247 CXXCtorInitializer **initializer =
2248 new (Context) CXXCtorInitializer*[1];
2249 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2250 Constructor->setCtorInitializers(initializer);
2251
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002252 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2253 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2254 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2255 }
2256
Alexis Hunte2622992011-05-05 00:05:47 +00002257 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002258
Alexis Hunt61bc1732011-05-01 07:04:31 +00002259 return false;
2260}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002261
Eli Friedman9cf6b592009-11-09 19:20:36 +00002262bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002263Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2264 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002265 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002266 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002267 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002268 // Just store the initializers as written, they will be checked during
2269 // instantiation.
2270 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002271 Constructor->setNumCtorInitializers(NumInitializers);
2272 CXXCtorInitializer **baseOrMemberInitializers =
2273 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002274 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002275 NumInitializers * sizeof(CXXCtorInitializer*));
2276 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002277 }
2278
2279 return false;
2280 }
2281
John McCallbc83b3f2010-05-20 23:23:51 +00002282 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002283
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002284 // We need to build the initializer AST according to order of construction
2285 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002286 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002287 if (!ClassDecl)
2288 return true;
2289
Eli Friedman9cf6b592009-11-09 19:20:36 +00002290 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002291
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002292 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002293 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002294
2295 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002296 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002297 else
Francois Pichetd583da02010-12-04 09:14:42 +00002298 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002299 }
2300
Anders Carlsson43c64af2010-04-21 19:52:01 +00002301 // Keep track of the direct virtual bases.
2302 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2303 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2304 E = ClassDecl->bases_end(); I != E; ++I) {
2305 if (I->isVirtual())
2306 DirectVBases.insert(I);
2307 }
2308
Anders Carlssondb0a9652010-04-02 06:26:44 +00002309 // Push virtual bases before others.
2310 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2311 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2312
Alexis Hunt1d792652011-01-08 20:30:50 +00002313 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002314 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2315 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002316 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002317 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002318 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002319 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002320 VBase, IsInheritedVirtualBase,
2321 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002322 HadError = true;
2323 continue;
2324 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002325
John McCallbc83b3f2010-05-20 23:23:51 +00002326 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002327 }
2328 }
Mike Stump11289f42009-09-09 15:08:12 +00002329
John McCallbc83b3f2010-05-20 23:23:51 +00002330 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2332 E = ClassDecl->bases_end(); Base != E; ++Base) {
2333 // Virtuals are in the virtual base list and already constructed.
2334 if (Base->isVirtual())
2335 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002336
Alexis Hunt1d792652011-01-08 20:30:50 +00002337 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002338 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2339 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002340 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002341 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002342 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002343 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002344 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002345 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002346 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002347 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002348
John McCallbc83b3f2010-05-20 23:23:51 +00002349 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002350 }
2351 }
Mike Stump11289f42009-09-09 15:08:12 +00002352
John McCallbc83b3f2010-05-20 23:23:51 +00002353 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002354 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002355 E = ClassDecl->field_end(); Field != E; ++Field) {
2356 if ((*Field)->getType()->isIncompleteArrayType()) {
2357 assert(ClassDecl->hasFlexibleArrayMember() &&
2358 "Incomplete array type is not valid");
2359 continue;
2360 }
Richard Smith938f40b2011-06-11 17:19:42 +00002361 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002362 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002363 }
Mike Stump11289f42009-09-09 15:08:12 +00002364
John McCallbc83b3f2010-05-20 23:23:51 +00002365 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002366 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002367 Constructor->setNumCtorInitializers(NumInitializers);
2368 CXXCtorInitializer **baseOrMemberInitializers =
2369 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002370 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002371 NumInitializers * sizeof(CXXCtorInitializer*));
2372 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002373
John McCalla6309952010-03-16 21:39:52 +00002374 // Constructors implicitly reference the base and member
2375 // destructors.
2376 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2377 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002378 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002379
2380 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002381}
2382
Eli Friedman952c15d2009-07-21 19:28:10 +00002383static void *GetKeyForTopLevelField(FieldDecl *Field) {
2384 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002385 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002386 if (RT->getDecl()->isAnonymousStructOrUnion())
2387 return static_cast<void *>(RT->getDecl());
2388 }
2389 return static_cast<void *>(Field);
2390}
2391
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002392static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002393 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002394}
2395
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002396static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002397 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002398 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002399 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002400
Eli Friedman952c15d2009-07-21 19:28:10 +00002401 // For fields injected into the class via declaration of an anonymous union,
2402 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002403 FieldDecl *Field = Member->getAnyMember();
2404
John McCall23eebd92010-04-10 09:28:51 +00002405 // If the field is a member of an anonymous struct or union, our key
2406 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002407 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002408 if (RD->isAnonymousStructOrUnion()) {
2409 while (true) {
2410 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2411 if (Parent->isAnonymousStructOrUnion())
2412 RD = Parent;
2413 else
2414 break;
2415 }
2416
Anders Carlsson83ac3122010-03-30 16:19:37 +00002417 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002418 }
Mike Stump11289f42009-09-09 15:08:12 +00002419
Anders Carlssona942dcd2010-03-30 15:39:27 +00002420 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002421}
2422
Anders Carlssone857b292010-04-02 03:37:03 +00002423static void
2424DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002425 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002426 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002427 unsigned NumInits) {
2428 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002429 return;
Mike Stump11289f42009-09-09 15:08:12 +00002430
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002431 // Don't check initializers order unless the warning is enabled at the
2432 // location of at least one initializer.
2433 bool ShouldCheckOrder = false;
2434 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002435 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002436 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2437 Init->getSourceLocation())
2438 != Diagnostic::Ignored) {
2439 ShouldCheckOrder = true;
2440 break;
2441 }
2442 }
2443 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002444 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002445
John McCallbb7b6582010-04-10 07:37:23 +00002446 // Build the list of bases and members in the order that they'll
2447 // actually be initialized. The explicit initializers should be in
2448 // this same order but may be missing things.
2449 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002450
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002451 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2452
John McCallbb7b6582010-04-10 07:37:23 +00002453 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002454 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002455 ClassDecl->vbases_begin(),
2456 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002457 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002458
John McCallbb7b6582010-04-10 07:37:23 +00002459 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002460 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002461 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002462 if (Base->isVirtual())
2463 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002464 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
John McCallbb7b6582010-04-10 07:37:23 +00002467 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002468 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2469 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002470 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002471
John McCallbb7b6582010-04-10 07:37:23 +00002472 unsigned NumIdealInits = IdealInitKeys.size();
2473 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002474
Alexis Hunt1d792652011-01-08 20:30:50 +00002475 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002476 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002477 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002478 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002479
2480 // Scan forward to try to find this initializer in the idealized
2481 // initializers list.
2482 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2483 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002484 break;
John McCallbb7b6582010-04-10 07:37:23 +00002485
2486 // If we didn't find this initializer, it must be because we
2487 // scanned past it on a previous iteration. That can only
2488 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002489 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002490 Sema::SemaDiagnosticBuilder D =
2491 SemaRef.Diag(PrevInit->getSourceLocation(),
2492 diag::warn_initializer_out_of_order);
2493
Francois Pichetd583da02010-12-04 09:14:42 +00002494 if (PrevInit->isAnyMemberInitializer())
2495 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002496 else
2497 D << 1 << PrevInit->getBaseClassInfo()->getType();
2498
Francois Pichetd583da02010-12-04 09:14:42 +00002499 if (Init->isAnyMemberInitializer())
2500 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002501 else
2502 D << 1 << Init->getBaseClassInfo()->getType();
2503
2504 // Move back to the initializer's location in the ideal list.
2505 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2506 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002507 break;
John McCallbb7b6582010-04-10 07:37:23 +00002508
2509 assert(IdealIndex != NumIdealInits &&
2510 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002511 }
John McCallbb7b6582010-04-10 07:37:23 +00002512
2513 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002514 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002515}
2516
John McCall23eebd92010-04-10 09:28:51 +00002517namespace {
2518bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002519 CXXCtorInitializer *Init,
2520 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002521 if (!PrevInit) {
2522 PrevInit = Init;
2523 return false;
2524 }
2525
2526 if (FieldDecl *Field = Init->getMember())
2527 S.Diag(Init->getSourceLocation(),
2528 diag::err_multiple_mem_initialization)
2529 << Field->getDeclName()
2530 << Init->getSourceRange();
2531 else {
John McCall424cec92011-01-19 06:33:43 +00002532 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002533 assert(BaseClass && "neither field nor base");
2534 S.Diag(Init->getSourceLocation(),
2535 diag::err_multiple_base_initialization)
2536 << QualType(BaseClass, 0)
2537 << Init->getSourceRange();
2538 }
2539 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2540 << 0 << PrevInit->getSourceRange();
2541
2542 return true;
2543}
2544
Alexis Hunt1d792652011-01-08 20:30:50 +00002545typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002546typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2547
2548bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002549 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002550 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002551 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002552 RecordDecl *Parent = Field->getParent();
2553 if (!Parent->isAnonymousStructOrUnion())
2554 return false;
2555
2556 NamedDecl *Child = Field;
2557 do {
2558 if (Parent->isUnion()) {
2559 UnionEntry &En = Unions[Parent];
2560 if (En.first && En.first != Child) {
2561 S.Diag(Init->getSourceLocation(),
2562 diag::err_multiple_mem_union_initialization)
2563 << Field->getDeclName()
2564 << Init->getSourceRange();
2565 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2566 << 0 << En.second->getSourceRange();
2567 return true;
2568 } else if (!En.first) {
2569 En.first = Child;
2570 En.second = Init;
2571 }
2572 }
2573
2574 Child = Parent;
2575 Parent = cast<RecordDecl>(Parent->getDeclContext());
2576 } while (Parent->isAnonymousStructOrUnion());
2577
2578 return false;
2579}
2580}
2581
Anders Carlssone857b292010-04-02 03:37:03 +00002582/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002583void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002584 SourceLocation ColonLoc,
2585 MemInitTy **meminits, unsigned NumMemInits,
2586 bool AnyErrors) {
2587 if (!ConstructorDecl)
2588 return;
2589
2590 AdjustDeclIfTemplate(ConstructorDecl);
2591
2592 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002593 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002594
2595 if (!Constructor) {
2596 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2597 return;
2598 }
2599
Alexis Hunt1d792652011-01-08 20:30:50 +00002600 CXXCtorInitializer **MemInits =
2601 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002602
2603 // Mapping for the duplicate initializers check.
2604 // For member initializers, this is keyed with a FieldDecl*.
2605 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002606 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002607
2608 // Mapping for the inconsistent anonymous-union initializers check.
2609 RedundantUnionMap MemberUnions;
2610
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002611 bool HadError = false;
2612 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002613 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002614
Abramo Bagnara341d7832010-05-26 18:09:23 +00002615 // Set the source order index.
2616 Init->setSourceOrder(i);
2617
Francois Pichetd583da02010-12-04 09:14:42 +00002618 if (Init->isAnyMemberInitializer()) {
2619 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002620 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2621 CheckRedundantUnionInit(*this, Init, MemberUnions))
2622 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002623 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002624 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2625 if (CheckRedundantInit(*this, Init, Members[Key]))
2626 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002627 } else {
2628 assert(Init->isDelegatingInitializer());
2629 // This must be the only initializer
2630 if (i != 0 || NumMemInits > 1) {
2631 Diag(MemInits[0]->getSourceLocation(),
2632 diag::err_delegating_initializer_alone)
2633 << MemInits[0]->getSourceRange();
2634 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002635 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002636 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002637 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002638 // Return immediately as the initializer is set.
2639 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002640 }
Anders Carlssone857b292010-04-02 03:37:03 +00002641 }
2642
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002643 if (HadError)
2644 return;
2645
Anders Carlssone857b292010-04-02 03:37:03 +00002646 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002647
Alexis Hunt1d792652011-01-08 20:30:50 +00002648 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002649}
2650
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002651void
John McCalla6309952010-03-16 21:39:52 +00002652Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2653 CXXRecordDecl *ClassDecl) {
2654 // Ignore dependent contexts.
2655 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002656 return;
John McCall1064d7e2010-03-16 05:22:47 +00002657
2658 // FIXME: all the access-control diagnostics are positioned on the
2659 // field/base declaration. That's probably good; that said, the
2660 // user might reasonably want to know why the destructor is being
2661 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002662
Anders Carlssondee9a302009-11-17 04:44:12 +00002663 // Non-static data members.
2664 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2665 E = ClassDecl->field_end(); I != E; ++I) {
2666 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002667 if (Field->isInvalidDecl())
2668 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002669 QualType FieldType = Context.getBaseElementType(Field->getType());
2670
2671 const RecordType* RT = FieldType->getAs<RecordType>();
2672 if (!RT)
2673 continue;
2674
2675 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002676 if (FieldClassDecl->isInvalidDecl())
2677 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002678 if (FieldClassDecl->hasTrivialDestructor())
2679 continue;
2680
Douglas Gregore71edda2010-07-01 22:47:18 +00002681 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002682 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002683 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002684 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002685 << Field->getDeclName()
2686 << FieldType);
2687
John McCalla6309952010-03-16 21:39:52 +00002688 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002689 }
2690
John McCall1064d7e2010-03-16 05:22:47 +00002691 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2692
Anders Carlssondee9a302009-11-17 04:44:12 +00002693 // Bases.
2694 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2695 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002696 // Bases are always records in a well-formed non-dependent class.
2697 const RecordType *RT = Base->getType()->getAs<RecordType>();
2698
2699 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002700 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002701 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002702
John McCall1064d7e2010-03-16 05:22:47 +00002703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002704 // If our base class is invalid, we probably can't get its dtor anyway.
2705 if (BaseClassDecl->isInvalidDecl())
2706 continue;
2707 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002708 if (BaseClassDecl->hasTrivialDestructor())
2709 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002710
Douglas Gregore71edda2010-07-01 22:47:18 +00002711 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002712 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002713
2714 // FIXME: caret should be on the start of the class name
2715 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002716 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002717 << Base->getType()
2718 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002719
John McCalla6309952010-03-16 21:39:52 +00002720 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002721 }
2722
2723 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002724 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2725 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002726
2727 // Bases are always records in a well-formed non-dependent class.
2728 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2729
2730 // Ignore direct virtual bases.
2731 if (DirectVirtualBases.count(RT))
2732 continue;
2733
John McCall1064d7e2010-03-16 05:22:47 +00002734 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002735 // If our base class is invalid, we probably can't get its dtor anyway.
2736 if (BaseClassDecl->isInvalidDecl())
2737 continue;
2738 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002739 if (BaseClassDecl->hasTrivialDestructor())
2740 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002741
Douglas Gregore71edda2010-07-01 22:47:18 +00002742 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002743 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002744 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002745 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002746 << VBase->getType());
2747
John McCalla6309952010-03-16 21:39:52 +00002748 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002749 }
2750}
2751
John McCall48871652010-08-21 09:40:31 +00002752void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002753 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002754 return;
Mike Stump11289f42009-09-09 15:08:12 +00002755
Mike Stump11289f42009-09-09 15:08:12 +00002756 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002757 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002758 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002759}
2760
Mike Stump11289f42009-09-09 15:08:12 +00002761bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002762 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002763 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002764 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002765 else
John McCall02db245d2010-08-18 09:41:07 +00002766 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002767}
2768
Anders Carlssoneabf7702009-08-27 00:13:57 +00002769bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002770 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002771 if (!getLangOptions().CPlusPlus)
2772 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002773
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002774 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002775 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002776
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002777 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002778 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002779 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002780 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002781
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002782 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002783 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002786 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002787 if (!RT)
2788 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002789
John McCall67da35c2010-02-04 22:26:26 +00002790 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002791
John McCall02db245d2010-08-18 09:41:07 +00002792 // We can't answer whether something is abstract until it has a
2793 // definition. If it's currently being defined, we'll walk back
2794 // over all the declarations when we have a full definition.
2795 const CXXRecordDecl *Def = RD->getDefinition();
2796 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002797 return false;
2798
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002799 if (!RD->isAbstract())
2800 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002801
Anders Carlssoneabf7702009-08-27 00:13:57 +00002802 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002803 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002804
John McCall02db245d2010-08-18 09:41:07 +00002805 return true;
2806}
2807
2808void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2809 // Check if we've already emitted the list of pure virtual functions
2810 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002811 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002812 return;
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregor4165bd62010-03-23 23:47:56 +00002814 CXXFinalOverriderMap FinalOverriders;
2815 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002816
Anders Carlssona2f74f32010-06-03 01:00:02 +00002817 // Keep a set of seen pure methods so we won't diagnose the same method
2818 // more than once.
2819 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2820
Douglas Gregor4165bd62010-03-23 23:47:56 +00002821 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2822 MEnd = FinalOverriders.end();
2823 M != MEnd;
2824 ++M) {
2825 for (OverridingMethods::iterator SO = M->second.begin(),
2826 SOEnd = M->second.end();
2827 SO != SOEnd; ++SO) {
2828 // C++ [class.abstract]p4:
2829 // A class is abstract if it contains or inherits at least one
2830 // pure virtual function for which the final overrider is pure
2831 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002832
Douglas Gregor4165bd62010-03-23 23:47:56 +00002833 //
2834 if (SO->second.size() != 1)
2835 continue;
2836
2837 if (!SO->second.front().Method->isPure())
2838 continue;
2839
Anders Carlssona2f74f32010-06-03 01:00:02 +00002840 if (!SeenPureMethods.insert(SO->second.front().Method))
2841 continue;
2842
Douglas Gregor4165bd62010-03-23 23:47:56 +00002843 Diag(SO->second.front().Method->getLocation(),
2844 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002845 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002846 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002847 }
2848
2849 if (!PureVirtualClassDiagSet)
2850 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2851 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002852}
2853
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002854namespace {
John McCall02db245d2010-08-18 09:41:07 +00002855struct AbstractUsageInfo {
2856 Sema &S;
2857 CXXRecordDecl *Record;
2858 CanQualType AbstractType;
2859 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002860
John McCall02db245d2010-08-18 09:41:07 +00002861 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2862 : S(S), Record(Record),
2863 AbstractType(S.Context.getCanonicalType(
2864 S.Context.getTypeDeclType(Record))),
2865 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002866
John McCall02db245d2010-08-18 09:41:07 +00002867 void DiagnoseAbstractType() {
2868 if (Invalid) return;
2869 S.DiagnoseAbstractType(Record);
2870 Invalid = true;
2871 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002872
John McCall02db245d2010-08-18 09:41:07 +00002873 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2874};
2875
2876struct CheckAbstractUsage {
2877 AbstractUsageInfo &Info;
2878 const NamedDecl *Ctx;
2879
2880 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2881 : Info(Info), Ctx(Ctx) {}
2882
2883 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2884 switch (TL.getTypeLocClass()) {
2885#define ABSTRACT_TYPELOC(CLASS, PARENT)
2886#define TYPELOC(CLASS, PARENT) \
2887 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2888#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002889 }
John McCall02db245d2010-08-18 09:41:07 +00002890 }
Mike Stump11289f42009-09-09 15:08:12 +00002891
John McCall02db245d2010-08-18 09:41:07 +00002892 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2893 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2894 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002895 if (!TL.getArg(I))
2896 continue;
2897
John McCall02db245d2010-08-18 09:41:07 +00002898 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2899 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002900 }
John McCall02db245d2010-08-18 09:41:07 +00002901 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002902
John McCall02db245d2010-08-18 09:41:07 +00002903 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2904 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2905 }
Mike Stump11289f42009-09-09 15:08:12 +00002906
John McCall02db245d2010-08-18 09:41:07 +00002907 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2908 // Visit the type parameters from a permissive context.
2909 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2910 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2911 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2912 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2913 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2914 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002915 }
John McCall02db245d2010-08-18 09:41:07 +00002916 }
Mike Stump11289f42009-09-09 15:08:12 +00002917
John McCall02db245d2010-08-18 09:41:07 +00002918 // Visit pointee types from a permissive context.
2919#define CheckPolymorphic(Type) \
2920 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2921 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2922 }
2923 CheckPolymorphic(PointerTypeLoc)
2924 CheckPolymorphic(ReferenceTypeLoc)
2925 CheckPolymorphic(MemberPointerTypeLoc)
2926 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002927
John McCall02db245d2010-08-18 09:41:07 +00002928 /// Handle all the types we haven't given a more specific
2929 /// implementation for above.
2930 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2931 // Every other kind of type that we haven't called out already
2932 // that has an inner type is either (1) sugar or (2) contains that
2933 // inner type in some way as a subobject.
2934 if (TypeLoc Next = TL.getNextTypeLoc())
2935 return Visit(Next, Sel);
2936
2937 // If there's no inner type and we're in a permissive context,
2938 // don't diagnose.
2939 if (Sel == Sema::AbstractNone) return;
2940
2941 // Check whether the type matches the abstract type.
2942 QualType T = TL.getType();
2943 if (T->isArrayType()) {
2944 Sel = Sema::AbstractArrayType;
2945 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002946 }
John McCall02db245d2010-08-18 09:41:07 +00002947 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2948 if (CT != Info.AbstractType) return;
2949
2950 // It matched; do some magic.
2951 if (Sel == Sema::AbstractArrayType) {
2952 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2953 << T << TL.getSourceRange();
2954 } else {
2955 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2956 << Sel << T << TL.getSourceRange();
2957 }
2958 Info.DiagnoseAbstractType();
2959 }
2960};
2961
2962void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2963 Sema::AbstractDiagSelID Sel) {
2964 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2965}
2966
2967}
2968
2969/// Check for invalid uses of an abstract type in a method declaration.
2970static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2971 CXXMethodDecl *MD) {
2972 // No need to do the check on definitions, which require that
2973 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002974 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002975 return;
2976
2977 // For safety's sake, just ignore it if we don't have type source
2978 // information. This should never happen for non-implicit methods,
2979 // but...
2980 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2981 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2982}
2983
2984/// Check for invalid uses of an abstract type within a class definition.
2985static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2986 CXXRecordDecl *RD) {
2987 for (CXXRecordDecl::decl_iterator
2988 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2989 Decl *D = *I;
2990 if (D->isImplicit()) continue;
2991
2992 // Methods and method templates.
2993 if (isa<CXXMethodDecl>(D)) {
2994 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2995 } else if (isa<FunctionTemplateDecl>(D)) {
2996 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2997 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2998
2999 // Fields and static variables.
3000 } else if (isa<FieldDecl>(D)) {
3001 FieldDecl *FD = cast<FieldDecl>(D);
3002 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3003 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3004 } else if (isa<VarDecl>(D)) {
3005 VarDecl *VD = cast<VarDecl>(D);
3006 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3007 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3008
3009 // Nested classes and class templates.
3010 } else if (isa<CXXRecordDecl>(D)) {
3011 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3012 } else if (isa<ClassTemplateDecl>(D)) {
3013 CheckAbstractClassUsage(Info,
3014 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3015 }
3016 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003017}
3018
Douglas Gregorc99f1552009-12-03 18:33:45 +00003019/// \brief Perform semantic checks on a class definition that has been
3020/// completing, introducing implicitly-declared members, checking for
3021/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003022void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003023 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003024 return;
3025
John McCall02db245d2010-08-18 09:41:07 +00003026 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3027 AbstractUsageInfo Info(*this, Record);
3028 CheckAbstractClassUsage(Info, Record);
3029 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003030
3031 // If this is not an aggregate type and has no user-declared constructor,
3032 // complain about any non-static data members of reference or const scalar
3033 // type, since they will never get initializers.
3034 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3035 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3036 bool Complained = false;
3037 for (RecordDecl::field_iterator F = Record->field_begin(),
3038 FEnd = Record->field_end();
3039 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003040 if (F->hasInClassInitializer())
3041 continue;
3042
Douglas Gregor454a5b62010-04-15 00:00:53 +00003043 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003044 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003045 if (!Complained) {
3046 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3047 << Record->getTagKind() << Record;
3048 Complained = true;
3049 }
3050
3051 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3052 << F->getType()->isReferenceType()
3053 << F->getDeclName();
3054 }
3055 }
3056 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003057
Anders Carlssone771e762011-01-25 18:08:22 +00003058 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003059 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003060
3061 if (Record->getIdentifier()) {
3062 // C++ [class.mem]p13:
3063 // If T is the name of a class, then each of the following shall have a
3064 // name different from T:
3065 // - every member of every anonymous union that is a member of class T.
3066 //
3067 // C++ [class.mem]p14:
3068 // In addition, if class T has a user-declared constructor (12.1), every
3069 // non-static data member of class T shall have a name different from T.
3070 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003071 R.first != R.second; ++R.first) {
3072 NamedDecl *D = *R.first;
3073 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3074 isa<IndirectFieldDecl>(D)) {
3075 Diag(D->getLocation(), diag::err_member_name_of_class)
3076 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003077 break;
3078 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003079 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003080 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003081
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003082 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003083 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003084 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003085 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003086 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3087 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3088 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003089
3090 // See if a method overloads virtual methods in a base
3091 /// class without overriding any.
3092 if (!Record->isDependentType()) {
3093 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3094 MEnd = Record->method_end();
3095 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003096 if (!(*M)->isStatic())
3097 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003098 }
3099 }
Sebastian Redl08905022011-02-05 19:23:19 +00003100
3101 // Declare inherited constructors. We do this eagerly here because:
3102 // - The standard requires an eager diagnostic for conflicting inherited
3103 // constructors from different classes.
3104 // - The lazy declaration of the other implicit constructors is so as to not
3105 // waste space and performance on classes that are not meant to be
3106 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3107 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003108 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003109
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003110 if (!Record->isDependentType())
3111 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003112}
3113
3114void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003115 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3116 ME = Record->method_end();
3117 MI != ME; ++MI) {
3118 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3119 switch (getSpecialMember(*MI)) {
3120 case CXXDefaultConstructor:
3121 CheckExplicitlyDefaultedDefaultConstructor(
3122 cast<CXXConstructorDecl>(*MI));
3123 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003124
Alexis Huntf91729462011-05-12 22:46:25 +00003125 case CXXDestructor:
3126 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3127 break;
3128
3129 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003130 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3131 break;
3132
Alexis Huntf91729462011-05-12 22:46:25 +00003133 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003134 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003135 break;
3136
Alexis Hunt119c10e2011-05-25 23:16:36 +00003137 case CXXMoveConstructor:
3138 case CXXMoveAssignment:
3139 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3140 break;
3141
Alexis Huntf91729462011-05-12 22:46:25 +00003142 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003143 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003144 llvm_unreachable("non-special member explicitly defaulted!");
3145 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003146 }
3147 }
3148
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003149}
3150
3151void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3152 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3153
3154 // Whether this was the first-declared instance of the constructor.
3155 // This affects whether we implicitly add an exception spec (and, eventually,
3156 // constexpr). It is also ill-formed to explicitly default a constructor such
3157 // that it would be deleted. (C++0x [decl.fct.def.default])
3158 bool First = CD == CD->getCanonicalDecl();
3159
Alexis Hunt913820d2011-05-13 06:10:58 +00003160 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003161 if (CD->getNumParams() != 0) {
3162 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3163 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003164 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003165 }
3166
3167 ImplicitExceptionSpecification Spec
3168 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3169 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003170 if (EPI.ExceptionSpecType == EST_Delayed) {
3171 // Exception specification depends on some deferred part of the class. We'll
3172 // try again when the class's definition has been fully processed.
3173 return;
3174 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003175 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3176 *ExceptionType = Context.getFunctionType(
3177 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3178
3179 if (CtorType->hasExceptionSpec()) {
3180 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003181 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003182 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003183 PDiag(),
3184 ExceptionType, SourceLocation(),
3185 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003186 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003187 }
3188 } else if (First) {
3189 // We set the declaration to have the computed exception spec here.
3190 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003191 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003192 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3193 }
Alexis Huntb3153022011-05-12 03:51:48 +00003194
Alexis Hunt913820d2011-05-13 06:10:58 +00003195 if (HadError) {
3196 CD->setInvalidDecl();
3197 return;
3198 }
3199
Alexis Huntb3153022011-05-12 03:51:48 +00003200 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003201 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003202 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003203 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003204 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003205 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003206 CD->setInvalidDecl();
3207 }
3208 }
3209}
3210
3211void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3212 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3213
3214 // Whether this was the first-declared instance of the constructor.
3215 bool First = CD == CD->getCanonicalDecl();
3216
3217 bool HadError = false;
3218 if (CD->getNumParams() != 1) {
3219 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3220 << CD->getSourceRange();
3221 HadError = true;
3222 }
3223
3224 ImplicitExceptionSpecification Spec(Context);
3225 bool Const;
3226 llvm::tie(Spec, Const) =
3227 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3228
3229 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3230 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3231 *ExceptionType = Context.getFunctionType(
3232 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3233
3234 // Check for parameter type matching.
3235 // This is a copy ctor so we know it's a cv-qualified reference to T.
3236 QualType ArgType = CtorType->getArgType(0);
3237 if (ArgType->getPointeeType().isVolatileQualified()) {
3238 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3239 HadError = true;
3240 }
3241 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3242 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3243 HadError = true;
3244 }
3245
3246 if (CtorType->hasExceptionSpec()) {
3247 if (CheckEquivalentExceptionSpec(
3248 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003249 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003250 PDiag(),
3251 ExceptionType, SourceLocation(),
3252 CtorType, CD->getLocation())) {
3253 HadError = true;
3254 }
3255 } else if (First) {
3256 // We set the declaration to have the computed exception spec here.
3257 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003258 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003259 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3260 }
3261
3262 if (HadError) {
3263 CD->setInvalidDecl();
3264 return;
3265 }
3266
3267 if (ShouldDeleteCopyConstructor(CD)) {
3268 if (First) {
3269 CD->setDeletedAsWritten();
3270 } else {
3271 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003272 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003273 CD->setInvalidDecl();
3274 }
Alexis Huntb3153022011-05-12 03:51:48 +00003275 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003276}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003277
Alexis Huntc9a55732011-05-14 05:23:28 +00003278void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3279 assert(MD->isExplicitlyDefaulted());
3280
3281 // Whether this was the first-declared instance of the operator
3282 bool First = MD == MD->getCanonicalDecl();
3283
3284 bool HadError = false;
3285 if (MD->getNumParams() != 1) {
3286 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3287 << MD->getSourceRange();
3288 HadError = true;
3289 }
3290
3291 QualType ReturnType =
3292 MD->getType()->getAs<FunctionType>()->getResultType();
3293 if (!ReturnType->isLValueReferenceType() ||
3294 !Context.hasSameType(
3295 Context.getCanonicalType(ReturnType->getPointeeType()),
3296 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3297 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3298 HadError = true;
3299 }
3300
3301 ImplicitExceptionSpecification Spec(Context);
3302 bool Const;
3303 llvm::tie(Spec, Const) =
3304 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3305
3306 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3307 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3308 *ExceptionType = Context.getFunctionType(
3309 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3310
Alexis Huntc9a55732011-05-14 05:23:28 +00003311 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003312 if (!ArgType->isReferenceType()) {
3313 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003314 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003315 } else {
3316 if (ArgType->getPointeeType().isVolatileQualified()) {
3317 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3318 HadError = true;
3319 }
3320 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3321 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3322 HadError = true;
3323 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003324 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003325
Alexis Huntc9a55732011-05-14 05:23:28 +00003326 if (OperType->getTypeQuals()) {
3327 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3328 HadError = true;
3329 }
3330
3331 if (OperType->hasExceptionSpec()) {
3332 if (CheckEquivalentExceptionSpec(
3333 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003334 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003335 PDiag(),
3336 ExceptionType, SourceLocation(),
3337 OperType, MD->getLocation())) {
3338 HadError = true;
3339 }
3340 } else if (First) {
3341 // We set the declaration to have the computed exception spec here.
3342 // We duplicate the one parameter type.
3343 EPI.RefQualifier = OperType->getRefQualifier();
3344 EPI.ExtInfo = OperType->getExtInfo();
3345 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3346 }
3347
3348 if (HadError) {
3349 MD->setInvalidDecl();
3350 return;
3351 }
3352
3353 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3354 if (First) {
3355 MD->setDeletedAsWritten();
3356 } else {
3357 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003358 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003359 MD->setInvalidDecl();
3360 }
3361 }
3362}
3363
Alexis Huntf91729462011-05-12 22:46:25 +00003364void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3365 assert(DD->isExplicitlyDefaulted());
3366
3367 // Whether this was the first-declared instance of the destructor.
3368 bool First = DD == DD->getCanonicalDecl();
3369
3370 ImplicitExceptionSpecification Spec
3371 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3372 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3373 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3374 *ExceptionType = Context.getFunctionType(
3375 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3376
3377 if (DtorType->hasExceptionSpec()) {
3378 if (CheckEquivalentExceptionSpec(
3379 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003380 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003381 PDiag(),
3382 ExceptionType, SourceLocation(),
3383 DtorType, DD->getLocation())) {
3384 DD->setInvalidDecl();
3385 return;
3386 }
3387 } else if (First) {
3388 // We set the declaration to have the computed exception spec here.
3389 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003390 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003391 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3392 }
3393
3394 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003395 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003396 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003397 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003398 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003399 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003400 DD->setInvalidDecl();
3401 }
Alexis Huntf91729462011-05-12 22:46:25 +00003402 }
Alexis Huntf91729462011-05-12 22:46:25 +00003403}
3404
Alexis Huntea6f0322011-05-11 22:34:38 +00003405bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3406 CXXRecordDecl *RD = CD->getParent();
3407 assert(!RD->isDependentType() && "do deletion after instantiation");
3408 if (!LangOpts.CPlusPlus0x)
3409 return false;
3410
Alexis Hunte77a28f2011-05-18 03:41:58 +00003411 SourceLocation Loc = CD->getLocation();
3412
Alexis Huntea6f0322011-05-11 22:34:38 +00003413 // Do access control from the constructor
3414 ContextRAII CtorContext(*this, CD);
3415
3416 bool Union = RD->isUnion();
3417 bool AllConst = true;
3418
Alexis Huntea6f0322011-05-11 22:34:38 +00003419 // We do this because we should never actually use an anonymous
3420 // union's constructor.
3421 if (Union && RD->isAnonymousStructOrUnion())
3422 return false;
3423
3424 // FIXME: We should put some diagnostic logic right into this function.
3425
3426 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003427 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003428
3429 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3430 BE = RD->bases_end();
3431 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003432 // We'll handle this one later
3433 if (BI->isVirtual())
3434 continue;
3435
Alexis Huntea6f0322011-05-11 22:34:38 +00003436 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3437 assert(BaseDecl && "base isn't a CXXRecordDecl");
3438
3439 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003440 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003441 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3442 if (BaseDtor->isDeleted())
3443 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003444 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003445 AR_accessible)
3446 return true;
3447
Alexis Huntea6f0322011-05-11 22:34:38 +00003448 // -- any [direct base class either] has no default constructor or
3449 // overload resolution as applied to [its] default constructor
3450 // results in an ambiguity or in a function that is deleted or
3451 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003452 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3453 if (!BaseDefault || BaseDefault->isDeleted())
3454 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003455
Alexis Hunteef8ee02011-06-10 03:50:41 +00003456 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3457 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003458 return true;
3459 }
3460
3461 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3462 BE = RD->vbases_end();
3463 BI != BE; ++BI) {
3464 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3465 assert(BaseDecl && "base isn't a CXXRecordDecl");
3466
3467 // -- any [virtual base class] has a type with a destructor that is
3468 // delete or inaccessible from the defaulted default constructor
3469 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3470 if (BaseDtor->isDeleted())
3471 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003472 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003473 AR_accessible)
3474 return true;
3475
3476 // -- any [virtual base class either] has no default constructor or
3477 // overload resolution as applied to [its] default constructor
3478 // results in an ambiguity or in a function that is deleted or
3479 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003480 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3481 if (!BaseDefault || BaseDefault->isDeleted())
3482 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003483
Alexis Hunteef8ee02011-06-10 03:50:41 +00003484 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3485 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003486 return true;
3487 }
3488
3489 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3490 FE = RD->field_end();
3491 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003492 if (FI->isInvalidDecl())
3493 continue;
3494
Alexis Huntea6f0322011-05-11 22:34:38 +00003495 QualType FieldType = Context.getBaseElementType(FI->getType());
3496 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003497
Alexis Huntea6f0322011-05-11 22:34:38 +00003498 // -- any non-static data member with no brace-or-equal-initializer is of
3499 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003500 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003501 return true;
3502
3503 // -- X is a union and all its variant members are of const-qualified type
3504 // (or array thereof)
3505 if (Union && !FieldType.isConstQualified())
3506 AllConst = false;
3507
3508 if (FieldRecord) {
3509 // -- X is a union-like class that has a variant member with a non-trivial
3510 // default constructor
3511 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3512 return true;
3513
3514 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3515 if (FieldDtor->isDeleted())
3516 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003517 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003518 AR_accessible)
3519 return true;
3520
3521 // -- any non-variant non-static data member of const-qualified type (or
3522 // array thereof) with no brace-or-equal-initializer does not have a
3523 // user-provided default constructor
3524 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003525 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003526 !FieldRecord->hasUserProvidedDefaultConstructor())
3527 return true;
3528
3529 if (!Union && FieldRecord->isUnion() &&
3530 FieldRecord->isAnonymousStructOrUnion()) {
3531 // We're okay to reuse AllConst here since we only care about the
3532 // value otherwise if we're in a union.
3533 AllConst = true;
3534
3535 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3536 UE = FieldRecord->field_end();
3537 UI != UE; ++UI) {
3538 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3539 CXXRecordDecl *UnionFieldRecord =
3540 UnionFieldType->getAsCXXRecordDecl();
3541
3542 if (!UnionFieldType.isConstQualified())
3543 AllConst = false;
3544
3545 if (UnionFieldRecord &&
3546 !UnionFieldRecord->hasTrivialDefaultConstructor())
3547 return true;
3548 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003549
Alexis Huntea6f0322011-05-11 22:34:38 +00003550 if (AllConst)
3551 return true;
3552
3553 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003554 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003555 continue;
3556 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003557
Richard Smith938f40b2011-06-11 17:19:42 +00003558 // -- any non-static data member with no brace-or-equal-initializer has
3559 // class type M (or array thereof) and either M has no default
3560 // constructor or overload resolution as applied to M's default
3561 // constructor results in an ambiguity or in a function that is deleted
3562 // or inaccessible from the defaulted default constructor.
3563 if (!FI->hasInClassInitializer()) {
3564 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3565 if (!FieldDefault || FieldDefault->isDeleted())
3566 return true;
3567 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3568 PDiag()) != AR_accessible)
3569 return true;
3570 }
3571 } else if (!Union && FieldType.isConstQualified() &&
3572 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003573 // -- any non-variant non-static data member of const-qualified type (or
3574 // array thereof) with no brace-or-equal-initializer does not have a
3575 // user-provided default constructor
3576 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003577 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003578 }
3579
3580 if (Union && AllConst)
3581 return true;
3582
3583 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003584}
3585
Alexis Hunt913820d2011-05-13 06:10:58 +00003586bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003587 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003588 assert(!RD->isDependentType() && "do deletion after instantiation");
3589 if (!LangOpts.CPlusPlus0x)
3590 return false;
3591
Alexis Hunte77a28f2011-05-18 03:41:58 +00003592 SourceLocation Loc = CD->getLocation();
3593
Alexis Hunt913820d2011-05-13 06:10:58 +00003594 // Do access control from the constructor
3595 ContextRAII CtorContext(*this, CD);
3596
Alexis Hunt899bd442011-06-10 04:44:37 +00003597 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003598
Alexis Huntc9a55732011-05-14 05:23:28 +00003599 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3600 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003601 unsigned ArgQuals =
3602 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3603 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003604
3605 // We do this because we should never actually use an anonymous
3606 // union's constructor.
3607 if (Union && RD->isAnonymousStructOrUnion())
3608 return false;
3609
3610 // FIXME: We should put some diagnostic logic right into this function.
3611
3612 // C++0x [class.copy]/11
3613 // A defaulted [copy] constructor for class X is defined as delete if X has:
3614
3615 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3616 BE = RD->bases_end();
3617 BI != BE; ++BI) {
3618 // We'll handle this one later
3619 if (BI->isVirtual())
3620 continue;
3621
3622 QualType BaseType = BI->getType();
3623 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3624 assert(BaseDecl && "base isn't a CXXRecordDecl");
3625
3626 // -- any [direct base class] of a type with a destructor that is deleted or
3627 // inaccessible from the defaulted constructor
3628 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3629 if (BaseDtor->isDeleted())
3630 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003631 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003632 AR_accessible)
3633 return true;
3634
3635 // -- a [direct base class] B that cannot be [copied] because overload
3636 // resolution, as applied to B's [copy] constructor, results in an
3637 // ambiguity or a function that is deleted or inaccessible from the
3638 // defaulted constructor
Alexis Huntb1b368f2011-06-10 12:07:09 +00003639 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003640 if (!BaseCtor || BaseCtor->isDeleted())
3641 return true;
3642 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3643 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003644 return true;
3645 }
3646
3647 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3648 BE = RD->vbases_end();
3649 BI != BE; ++BI) {
3650 QualType BaseType = BI->getType();
3651 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3652 assert(BaseDecl && "base isn't a CXXRecordDecl");
3653
Alexis Hunteef8ee02011-06-10 03:50:41 +00003654 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003655 // inaccessible from the defaulted constructor
3656 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3657 if (BaseDtor->isDeleted())
3658 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003659 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003660 AR_accessible)
3661 return true;
3662
3663 // -- a [virtual base class] B that cannot be [copied] because overload
3664 // resolution, as applied to B's [copy] constructor, results in an
3665 // ambiguity or a function that is deleted or inaccessible from the
3666 // defaulted constructor
Alexis Huntb1b368f2011-06-10 12:07:09 +00003667 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003668 if (!BaseCtor || BaseCtor->isDeleted())
3669 return true;
3670 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3671 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003672 return true;
3673 }
3674
3675 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3676 FE = RD->field_end();
3677 FI != FE; ++FI) {
3678 QualType FieldType = Context.getBaseElementType(FI->getType());
3679
3680 // -- for a copy constructor, a non-static data member of rvalue reference
3681 // type
3682 if (FieldType->isRValueReferenceType())
3683 return true;
3684
3685 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3686
3687 if (FieldRecord) {
3688 // This is an anonymous union
3689 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3690 // Anonymous unions inside unions do not variant members create
3691 if (!Union) {
3692 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3693 UE = FieldRecord->field_end();
3694 UI != UE; ++UI) {
3695 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3696 CXXRecordDecl *UnionFieldRecord =
3697 UnionFieldType->getAsCXXRecordDecl();
3698
3699 // -- a variant member with a non-trivial [copy] constructor and X
3700 // is a union-like class
3701 if (UnionFieldRecord &&
3702 !UnionFieldRecord->hasTrivialCopyConstructor())
3703 return true;
3704 }
3705 }
3706
3707 // Don't try to initalize an anonymous union
3708 continue;
3709 } else {
3710 // -- a variant member with a non-trivial [copy] constructor and X is a
3711 // union-like class
3712 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3713 return true;
3714
3715 // -- any [non-static data member] of a type with a destructor that is
3716 // deleted or inaccessible from the defaulted constructor
3717 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3718 if (FieldDtor->isDeleted())
3719 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003720 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003721 AR_accessible)
3722 return true;
3723 }
Alexis Hunt899bd442011-06-10 04:44:37 +00003724
3725 // -- a [non-static data member of class type (or array thereof)] B that
3726 // cannot be [copied] because overload resolution, as applied to B's
3727 // [copy] constructor, results in an ambiguity or a function that is
3728 // deleted or inaccessible from the defaulted constructor
Alexis Huntb1b368f2011-06-10 12:07:09 +00003729 CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3730 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003731 if (!FieldCtor || FieldCtor->isDeleted())
3732 return true;
3733 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3734 PDiag()) != AR_accessible)
3735 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00003736 }
Alexis Hunt913820d2011-05-13 06:10:58 +00003737 }
3738
3739 return false;
3740}
3741
Alexis Huntb2f27802011-05-14 05:23:24 +00003742bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3743 CXXRecordDecl *RD = MD->getParent();
3744 assert(!RD->isDependentType() && "do deletion after instantiation");
3745 if (!LangOpts.CPlusPlus0x)
3746 return false;
3747
Alexis Hunte77a28f2011-05-18 03:41:58 +00003748 SourceLocation Loc = MD->getLocation();
3749
Alexis Huntb2f27802011-05-14 05:23:24 +00003750 // Do access control from the constructor
3751 ContextRAII MethodContext(*this, MD);
3752
3753 bool Union = RD->isUnion();
3754
Alexis Huntb1b368f2011-06-10 12:07:09 +00003755 bool ConstArg =
3756 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
Alexis Huntb2f27802011-05-14 05:23:24 +00003757
3758 // We do this because we should never actually use an anonymous
3759 // union's constructor.
3760 if (Union && RD->isAnonymousStructOrUnion())
3761 return false;
3762
Alexis Huntb1b368f2011-06-10 12:07:09 +00003763 DeclarationName OperatorName =
3764 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3765 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3766 R.suppressDiagnostics();
3767
Alexis Huntb2f27802011-05-14 05:23:24 +00003768 // FIXME: We should put some diagnostic logic right into this function.
3769
3770 // C++0x [class.copy]/11
3771 // A defaulted [copy] assignment operator for class X is defined as deleted
3772 // if X has:
3773
3774 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3775 BE = RD->bases_end();
3776 BI != BE; ++BI) {
3777 // We'll handle this one later
3778 if (BI->isVirtual())
3779 continue;
3780
3781 QualType BaseType = BI->getType();
3782 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3783 assert(BaseDecl && "base isn't a CXXRecordDecl");
3784
3785 // -- a [direct base class] B that cannot be [copied] because overload
3786 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003787 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003788 // assignment operator
Alexis Huntb1b368f2011-06-10 12:07:09 +00003789
3790 LookupQualifiedName(R, BaseDecl, false);
3791
3792 // Filter out any result that isn't a copy-assignment operator.
3793 LookupResult::Filter F = R.makeFilter();
3794 while (F.hasNext()) {
3795 NamedDecl *D = F.next();
3796 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3797 if (Method->isCopyAssignmentOperator())
3798 continue;
3799
3800 F.erase();
3801 }
3802 F.done();
3803
3804 // Build a fake argument expression
3805 QualType ArgType = BaseType;
3806 QualType ThisType = BaseType;
3807 if (ConstArg)
3808 ArgType.addConst();
3809 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3810 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3811 };
3812
3813 OverloadCandidateSet OCS((Loc));
3814 OverloadCandidateSet::iterator Best;
3815
3816 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3817
3818 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3819 OR_Success)
Alexis Huntb2f27802011-05-14 05:23:24 +00003820 return true;
3821 }
3822
3823 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3824 BE = RD->vbases_end();
3825 BI != BE; ++BI) {
3826 QualType BaseType = BI->getType();
3827 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3828 assert(BaseDecl && "base isn't a CXXRecordDecl");
3829
Alexis Huntb2f27802011-05-14 05:23:24 +00003830 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003831 // resolution, as applied to B's [copy] assignment operator, results in
3832 // an ambiguity or a function that is deleted or inaccessible from the
3833 // assignment operator
Alexis Huntb1b368f2011-06-10 12:07:09 +00003834
3835 LookupQualifiedName(R, BaseDecl, false);
3836
3837 // Filter out any result that isn't a copy-assignment operator.
3838 LookupResult::Filter F = R.makeFilter();
3839 while (F.hasNext()) {
3840 NamedDecl *D = F.next();
3841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3842 if (Method->isCopyAssignmentOperator())
3843 continue;
3844
3845 F.erase();
3846 }
3847 F.done();
3848
3849 // Build a fake argument expression
3850 QualType ArgType = BaseType;
3851 QualType ThisType = BaseType;
3852 if (ConstArg)
3853 ArgType.addConst();
3854 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3855 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3856 };
3857
3858 OverloadCandidateSet OCS((Loc));
3859 OverloadCandidateSet::iterator Best;
3860
3861 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3862
3863 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3864 OR_Success)
Alexis Huntb2f27802011-05-14 05:23:24 +00003865 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003866 }
3867
3868 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3869 FE = RD->field_end();
3870 FI != FE; ++FI) {
3871 QualType FieldType = Context.getBaseElementType(FI->getType());
3872
3873 // -- a non-static data member of reference type
3874 if (FieldType->isReferenceType())
3875 return true;
3876
3877 // -- a non-static data member of const non-class type (or array thereof)
3878 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3879 return true;
3880
3881 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3882
3883 if (FieldRecord) {
3884 // This is an anonymous union
3885 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3886 // Anonymous unions inside unions do not variant members create
3887 if (!Union) {
3888 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3889 UE = FieldRecord->field_end();
3890 UI != UE; ++UI) {
3891 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3892 CXXRecordDecl *UnionFieldRecord =
3893 UnionFieldType->getAsCXXRecordDecl();
3894
3895 // -- a variant member with a non-trivial [copy] assignment operator
3896 // and X is a union-like class
3897 if (UnionFieldRecord &&
3898 !UnionFieldRecord->hasTrivialCopyAssignment())
3899 return true;
3900 }
3901 }
3902
3903 // Don't try to initalize an anonymous union
3904 continue;
3905 // -- a variant member with a non-trivial [copy] assignment operator
3906 // and X is a union-like class
3907 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3908 return true;
3909 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003910
Alexis Huntb1b368f2011-06-10 12:07:09 +00003911 LookupQualifiedName(R, FieldRecord, false);
3912
3913 // Filter out any result that isn't a copy-assignment operator.
3914 LookupResult::Filter F = R.makeFilter();
3915 while (F.hasNext()) {
3916 NamedDecl *D = F.next();
3917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3918 if (Method->isCopyAssignmentOperator())
3919 continue;
3920
3921 F.erase();
3922 }
3923 F.done();
3924
3925 // Build a fake argument expression
3926 QualType ArgType = FieldType;
3927 QualType ThisType = FieldType;
3928 if (ConstArg)
3929 ArgType.addConst();
3930 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3931 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3932 };
3933
3934 OverloadCandidateSet OCS((Loc));
3935 OverloadCandidateSet::iterator Best;
3936
3937 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3938
3939 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3940 OR_Success)
3941 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00003942 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003943 }
3944
3945 return false;
3946}
3947
Alexis Huntf91729462011-05-12 22:46:25 +00003948bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3949 CXXRecordDecl *RD = DD->getParent();
3950 assert(!RD->isDependentType() && "do deletion after instantiation");
3951 if (!LangOpts.CPlusPlus0x)
3952 return false;
3953
Alexis Hunte77a28f2011-05-18 03:41:58 +00003954 SourceLocation Loc = DD->getLocation();
3955
Alexis Huntf91729462011-05-12 22:46:25 +00003956 // Do access control from the destructor
3957 ContextRAII CtorContext(*this, DD);
3958
3959 bool Union = RD->isUnion();
3960
Alexis Hunt913820d2011-05-13 06:10:58 +00003961 // We do this because we should never actually use an anonymous
3962 // union's destructor.
3963 if (Union && RD->isAnonymousStructOrUnion())
3964 return false;
3965
Alexis Huntf91729462011-05-12 22:46:25 +00003966 // C++0x [class.dtor]p5
3967 // A defaulted destructor for a class X is defined as deleted if:
3968 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3969 BE = RD->bases_end();
3970 BI != BE; ++BI) {
3971 // We'll handle this one later
3972 if (BI->isVirtual())
3973 continue;
3974
3975 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3976 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3977 assert(BaseDtor && "base has no destructor");
3978
3979 // -- any direct or virtual base class has a deleted destructor or
3980 // a destructor that is inaccessible from the defaulted destructor
3981 if (BaseDtor->isDeleted())
3982 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003983 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003984 AR_accessible)
3985 return true;
3986 }
3987
3988 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3989 BE = RD->vbases_end();
3990 BI != BE; ++BI) {
3991 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3992 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3993 assert(BaseDtor && "base has no destructor");
3994
3995 // -- any direct or virtual base class has a deleted destructor or
3996 // a destructor that is inaccessible from the defaulted destructor
3997 if (BaseDtor->isDeleted())
3998 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003999 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004000 AR_accessible)
4001 return true;
4002 }
4003
4004 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4005 FE = RD->field_end();
4006 FI != FE; ++FI) {
4007 QualType FieldType = Context.getBaseElementType(FI->getType());
4008 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4009 if (FieldRecord) {
4010 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4011 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4012 UE = FieldRecord->field_end();
4013 UI != UE; ++UI) {
4014 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4015 CXXRecordDecl *UnionFieldRecord =
4016 UnionFieldType->getAsCXXRecordDecl();
4017
4018 // -- X is a union-like class that has a variant member with a non-
4019 // trivial destructor.
4020 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4021 return true;
4022 }
4023 // Technically we are supposed to do this next check unconditionally.
4024 // But that makes absolutely no sense.
4025 } else {
4026 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4027
4028 // -- any of the non-static data members has class type M (or array
4029 // thereof) and M has a deleted destructor or a destructor that is
4030 // inaccessible from the defaulted destructor
4031 if (FieldDtor->isDeleted())
4032 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004033 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004034 AR_accessible)
4035 return true;
4036
4037 // -- X is a union-like class that has a variant member with a non-
4038 // trivial destructor.
4039 if (Union && !FieldDtor->isTrivial())
4040 return true;
4041 }
4042 }
4043 }
4044
4045 if (DD->isVirtual()) {
4046 FunctionDecl *OperatorDelete = 0;
4047 DeclarationName Name =
4048 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004049 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004050 false))
4051 return true;
4052 }
4053
4054
4055 return false;
4056}
4057
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004058/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004059namespace {
4060 struct FindHiddenVirtualMethodData {
4061 Sema *S;
4062 CXXMethodDecl *Method;
4063 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4064 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4065 };
4066}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004067
4068/// \brief Member lookup function that determines whether a given C++
4069/// method overloads virtual methods in a base class without overriding any,
4070/// to be used with CXXRecordDecl::lookupInBases().
4071static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4072 CXXBasePath &Path,
4073 void *UserData) {
4074 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4075
4076 FindHiddenVirtualMethodData &Data
4077 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4078
4079 DeclarationName Name = Data.Method->getDeclName();
4080 assert(Name.getNameKind() == DeclarationName::Identifier);
4081
4082 bool foundSameNameMethod = false;
4083 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4084 for (Path.Decls = BaseRecord->lookup(Name);
4085 Path.Decls.first != Path.Decls.second;
4086 ++Path.Decls.first) {
4087 NamedDecl *D = *Path.Decls.first;
4088 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004089 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004090 foundSameNameMethod = true;
4091 // Interested only in hidden virtual methods.
4092 if (!MD->isVirtual())
4093 continue;
4094 // If the method we are checking overrides a method from its base
4095 // don't warn about the other overloaded methods.
4096 if (!Data.S->IsOverload(Data.Method, MD, false))
4097 return true;
4098 // Collect the overload only if its hidden.
4099 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4100 overloadedMethods.push_back(MD);
4101 }
4102 }
4103
4104 if (foundSameNameMethod)
4105 Data.OverloadedMethods.append(overloadedMethods.begin(),
4106 overloadedMethods.end());
4107 return foundSameNameMethod;
4108}
4109
4110/// \brief See if a method overloads virtual methods in a base class without
4111/// overriding any.
4112void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4113 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4114 MD->getLocation()) == Diagnostic::Ignored)
4115 return;
4116 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4117 return;
4118
4119 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4120 /*bool RecordPaths=*/false,
4121 /*bool DetectVirtual=*/false);
4122 FindHiddenVirtualMethodData Data;
4123 Data.Method = MD;
4124 Data.S = this;
4125
4126 // Keep the base methods that were overriden or introduced in the subclass
4127 // by 'using' in a set. A base method not in this set is hidden.
4128 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4129 res.first != res.second; ++res.first) {
4130 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4131 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4132 E = MD->end_overridden_methods();
4133 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004134 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004135 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004137 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004138 }
4139
4140 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4141 !Data.OverloadedMethods.empty()) {
4142 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4143 << MD << (Data.OverloadedMethods.size() > 1);
4144
4145 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4146 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4147 Diag(overloadedMD->getLocation(),
4148 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4149 }
4150 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004151}
4152
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004153void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004154 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004155 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004156 SourceLocation RBrac,
4157 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004158 if (!TagDecl)
4159 return;
Mike Stump11289f42009-09-09 15:08:12 +00004160
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004161 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004162
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004163 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004164 // strict aliasing violation!
4165 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004166 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004167
Douglas Gregor0be31a22010-07-02 17:43:08 +00004168 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004169 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004170}
4171
Douglas Gregor05379422008-11-03 17:51:48 +00004172/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4173/// special functions, such as the default constructor, copy
4174/// constructor, or destructor, to the given C++ class (C++
4175/// [special]p1). This routine can only be executed just before the
4176/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004177void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004178 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004179 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004180
Douglas Gregor54be3392010-07-01 17:57:27 +00004181 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004182 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004183
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004184 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4185 ++ASTContext::NumImplicitCopyAssignmentOperators;
4186
4187 // If we have a dynamic class, then the copy assignment operator may be
4188 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4189 // it shows up in the right place in the vtable and that we diagnose
4190 // problems with the implicit exception specification.
4191 if (ClassDecl->isDynamicClass())
4192 DeclareImplicitCopyAssignment(ClassDecl);
4193 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004194
Douglas Gregor7454c562010-07-02 20:37:36 +00004195 if (!ClassDecl->hasUserDeclaredDestructor()) {
4196 ++ASTContext::NumImplicitDestructors;
4197
4198 // If we have a dynamic class, then the destructor may be virtual, so we
4199 // have to declare the destructor immediately. This ensures that, e.g., it
4200 // shows up in the right place in the vtable and that we diagnose problems
4201 // with the implicit exception specification.
4202 if (ClassDecl->isDynamicClass())
4203 DeclareImplicitDestructor(ClassDecl);
4204 }
Douglas Gregor05379422008-11-03 17:51:48 +00004205}
4206
Francois Pichet1c229c02011-04-22 22:18:13 +00004207void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4208 if (!D)
4209 return;
4210
4211 int NumParamList = D->getNumTemplateParameterLists();
4212 for (int i = 0; i < NumParamList; i++) {
4213 TemplateParameterList* Params = D->getTemplateParameterList(i);
4214 for (TemplateParameterList::iterator Param = Params->begin(),
4215 ParamEnd = Params->end();
4216 Param != ParamEnd; ++Param) {
4217 NamedDecl *Named = cast<NamedDecl>(*Param);
4218 if (Named->getDeclName()) {
4219 S->AddDecl(Named);
4220 IdResolver.AddDecl(Named);
4221 }
4222 }
4223 }
4224}
4225
John McCall48871652010-08-21 09:40:31 +00004226void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004227 if (!D)
4228 return;
4229
4230 TemplateParameterList *Params = 0;
4231 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4232 Params = Template->getTemplateParameters();
4233 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4234 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4235 Params = PartialSpec->getTemplateParameters();
4236 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004237 return;
4238
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004239 for (TemplateParameterList::iterator Param = Params->begin(),
4240 ParamEnd = Params->end();
4241 Param != ParamEnd; ++Param) {
4242 NamedDecl *Named = cast<NamedDecl>(*Param);
4243 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004244 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004245 IdResolver.AddDecl(Named);
4246 }
4247 }
4248}
4249
John McCall48871652010-08-21 09:40:31 +00004250void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004251 if (!RecordD) return;
4252 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004253 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004254 PushDeclContext(S, Record);
4255}
4256
John McCall48871652010-08-21 09:40:31 +00004257void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004258 if (!RecordD) return;
4259 PopDeclContext();
4260}
4261
Douglas Gregor4d87df52008-12-16 21:30:33 +00004262/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4263/// parsing a top-level (non-nested) C++ class, and we are now
4264/// parsing those parts of the given Method declaration that could
4265/// not be parsed earlier (C++ [class.mem]p2), such as default
4266/// arguments. This action should enter the scope of the given
4267/// Method declaration as if we had just parsed the qualified method
4268/// name. However, it should not bring the parameters into scope;
4269/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004270void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004271}
4272
4273/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4274/// C++ method declaration. We're (re-)introducing the given
4275/// function parameter into scope for use in parsing later parts of
4276/// the method declaration. For example, we could see an
4277/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004278void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004279 if (!ParamD)
4280 return;
Mike Stump11289f42009-09-09 15:08:12 +00004281
John McCall48871652010-08-21 09:40:31 +00004282 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004283
4284 // If this parameter has an unparsed default argument, clear it out
4285 // to make way for the parsed default argument.
4286 if (Param->hasUnparsedDefaultArg())
4287 Param->setDefaultArg(0);
4288
John McCall48871652010-08-21 09:40:31 +00004289 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004290 if (Param->getDeclName())
4291 IdResolver.AddDecl(Param);
4292}
4293
4294/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4295/// processing the delayed method declaration for Method. The method
4296/// declaration is now considered finished. There may be a separate
4297/// ActOnStartOfFunctionDef action later (not necessarily
4298/// immediately!) for this method, if it was also defined inside the
4299/// class body.
John McCall48871652010-08-21 09:40:31 +00004300void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004301 if (!MethodD)
4302 return;
Mike Stump11289f42009-09-09 15:08:12 +00004303
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004304 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004305
John McCall48871652010-08-21 09:40:31 +00004306 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004307
4308 // Now that we have our default arguments, check the constructor
4309 // again. It could produce additional diagnostics or affect whether
4310 // the class has implicitly-declared destructors, among other
4311 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004312 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4313 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004314
4315 // Check the default arguments, which we may have added.
4316 if (!Method->isInvalidDecl())
4317 CheckCXXDefaultArguments(Method);
4318}
4319
Douglas Gregor831c93f2008-11-05 20:51:48 +00004320/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004321/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004322/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004323/// emit diagnostics and set the invalid bit to true. In any case, the type
4324/// will be updated to reflect a well-formed type for the constructor and
4325/// returned.
4326QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004327 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004328 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004329
4330 // C++ [class.ctor]p3:
4331 // A constructor shall not be virtual (10.3) or static (9.4). A
4332 // constructor can be invoked for a const, volatile or const
4333 // volatile object. A constructor shall not be declared const,
4334 // volatile, or const volatile (9.3.2).
4335 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004336 if (!D.isInvalidType())
4337 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4338 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4339 << SourceRange(D.getIdentifierLoc());
4340 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004341 }
John McCall8e7d6562010-08-26 03:08:43 +00004342 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004343 if (!D.isInvalidType())
4344 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4345 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4346 << SourceRange(D.getIdentifierLoc());
4347 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004348 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004349 }
Mike Stump11289f42009-09-09 15:08:12 +00004350
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004351 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004352 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004353 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004354 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4355 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004356 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004357 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4358 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004359 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004360 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4361 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004362 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004363 }
Mike Stump11289f42009-09-09 15:08:12 +00004364
Douglas Gregordb9d6642011-01-26 05:01:58 +00004365 // C++0x [class.ctor]p4:
4366 // A constructor shall not be declared with a ref-qualifier.
4367 if (FTI.hasRefQualifier()) {
4368 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4369 << FTI.RefQualifierIsLValueRef
4370 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4371 D.setInvalidType();
4372 }
4373
Douglas Gregor831c93f2008-11-05 20:51:48 +00004374 // Rebuild the function type "R" without any type qualifiers (in
4375 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004376 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004377 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004378 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4379 return R;
4380
4381 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4382 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004383 EPI.RefQualifier = RQ_None;
4384
Chris Lattner38378bf2009-04-25 08:28:21 +00004385 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004386 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004387}
4388
Douglas Gregor4d87df52008-12-16 21:30:33 +00004389/// CheckConstructor - Checks a fully-formed constructor for
4390/// well-formedness, issuing any diagnostics required. Returns true if
4391/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004392void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004393 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004394 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4395 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004396 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004397
4398 // C++ [class.copy]p3:
4399 // A declaration of a constructor for a class X is ill-formed if
4400 // its first parameter is of type (optionally cv-qualified) X and
4401 // either there are no other parameters or else all other
4402 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004403 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004404 ((Constructor->getNumParams() == 1) ||
4405 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004406 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4407 Constructor->getTemplateSpecializationKind()
4408 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004409 QualType ParamType = Constructor->getParamDecl(0)->getType();
4410 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4411 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004412 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004413 const char *ConstRef
4414 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4415 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004416 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004417 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004418
4419 // FIXME: Rather that making the constructor invalid, we should endeavor
4420 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004421 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004422 }
4423 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004424}
4425
John McCalldeb646e2010-08-04 01:04:25 +00004426/// CheckDestructor - Checks a fully-formed destructor definition for
4427/// well-formedness, issuing any diagnostics required. Returns true
4428/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004429bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004430 CXXRecordDecl *RD = Destructor->getParent();
4431
4432 if (Destructor->isVirtual()) {
4433 SourceLocation Loc;
4434
4435 if (!Destructor->isImplicit())
4436 Loc = Destructor->getLocation();
4437 else
4438 Loc = RD->getLocation();
4439
4440 // If we have a virtual destructor, look up the deallocation function
4441 FunctionDecl *OperatorDelete = 0;
4442 DeclarationName Name =
4443 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004444 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004445 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004446
4447 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004448
4449 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004450 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004451
4452 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004453}
4454
Mike Stump11289f42009-09-09 15:08:12 +00004455static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004456FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4457 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4458 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004459 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004460}
4461
Douglas Gregor831c93f2008-11-05 20:51:48 +00004462/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4463/// the well-formednes of the destructor declarator @p D with type @p
4464/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004465/// emit diagnostics and set the declarator to invalid. Even if this happens,
4466/// will be updated to reflect a well-formed type for the destructor and
4467/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004468QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004469 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004470 // C++ [class.dtor]p1:
4471 // [...] A typedef-name that names a class is a class-name
4472 // (7.1.3); however, a typedef-name that names a class shall not
4473 // be used as the identifier in the declarator for a destructor
4474 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004475 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004476 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004477 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004478 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004479 else if (const TemplateSpecializationType *TST =
4480 DeclaratorType->getAs<TemplateSpecializationType>())
4481 if (TST->isTypeAlias())
4482 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4483 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004484
4485 // C++ [class.dtor]p2:
4486 // A destructor is used to destroy objects of its class type. A
4487 // destructor takes no parameters, and no return type can be
4488 // specified for it (not even void). The address of a destructor
4489 // shall not be taken. A destructor shall not be static. A
4490 // destructor can be invoked for a const, volatile or const
4491 // volatile object. A destructor shall not be declared const,
4492 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004493 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004494 if (!D.isInvalidType())
4495 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4496 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004497 << SourceRange(D.getIdentifierLoc())
4498 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4499
John McCall8e7d6562010-08-26 03:08:43 +00004500 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004501 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004502 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004503 // Destructors don't have return types, but the parser will
4504 // happily parse something like:
4505 //
4506 // class X {
4507 // float ~X();
4508 // };
4509 //
4510 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004511 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4512 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4513 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004514 }
Mike Stump11289f42009-09-09 15:08:12 +00004515
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004516 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004517 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004518 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004519 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4520 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004521 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004522 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4523 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004524 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004525 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4526 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004527 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004528 }
4529
Douglas Gregordb9d6642011-01-26 05:01:58 +00004530 // C++0x [class.dtor]p2:
4531 // A destructor shall not be declared with a ref-qualifier.
4532 if (FTI.hasRefQualifier()) {
4533 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4534 << FTI.RefQualifierIsLValueRef
4535 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4536 D.setInvalidType();
4537 }
4538
Douglas Gregor831c93f2008-11-05 20:51:48 +00004539 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004540 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004541 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4542
4543 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004544 FTI.freeArgs();
4545 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004546 }
4547
Mike Stump11289f42009-09-09 15:08:12 +00004548 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004549 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004550 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004551 D.setInvalidType();
4552 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004553
4554 // Rebuild the function type "R" without any type qualifiers or
4555 // parameters (in case any of the errors above fired) and with
4556 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004557 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004558 if (!D.isInvalidType())
4559 return R;
4560
Douglas Gregor95755162010-07-01 05:10:53 +00004561 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004562 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4563 EPI.Variadic = false;
4564 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004565 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004566 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004567}
4568
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004569/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4570/// well-formednes of the conversion function declarator @p D with
4571/// type @p R. If there are any errors in the declarator, this routine
4572/// will emit diagnostics and return true. Otherwise, it will return
4573/// false. Either way, the type @p R will be updated to reflect a
4574/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004575void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004576 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004577 // C++ [class.conv.fct]p1:
4578 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004579 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004580 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004581 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004582 if (!D.isInvalidType())
4583 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4584 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4585 << SourceRange(D.getIdentifierLoc());
4586 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004587 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004588 }
John McCall212fa2e2010-04-13 00:04:31 +00004589
4590 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4591
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004592 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004593 // Conversion functions don't have return types, but the parser will
4594 // happily parse something like:
4595 //
4596 // class X {
4597 // float operator bool();
4598 // };
4599 //
4600 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004601 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4602 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4603 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004604 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004605 }
4606
John McCall212fa2e2010-04-13 00:04:31 +00004607 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4608
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004609 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004610 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004611 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4612
4613 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004614 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004615 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004616 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004617 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004618 D.setInvalidType();
4619 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004620
John McCall212fa2e2010-04-13 00:04:31 +00004621 // Diagnose "&operator bool()" and other such nonsense. This
4622 // is actually a gcc extension which we don't support.
4623 if (Proto->getResultType() != ConvType) {
4624 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4625 << Proto->getResultType();
4626 D.setInvalidType();
4627 ConvType = Proto->getResultType();
4628 }
4629
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004630 // C++ [class.conv.fct]p4:
4631 // The conversion-type-id shall not represent a function type nor
4632 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004633 if (ConvType->isArrayType()) {
4634 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4635 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004636 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004637 } else if (ConvType->isFunctionType()) {
4638 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4639 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004640 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004641 }
4642
4643 // Rebuild the function type "R" without any parameters (in case any
4644 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004645 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004646 if (D.isInvalidType())
4647 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004648
Douglas Gregor5fb53972009-01-14 15:45:31 +00004649 // C++0x explicit conversion operators.
4650 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004651 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004652 diag::warn_explicit_conversion_functions)
4653 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004654}
4655
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004656/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4657/// the declaration of the given C++ conversion function. This routine
4658/// is responsible for recording the conversion function in the C++
4659/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004660Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004661 assert(Conversion && "Expected to receive a conversion function declaration");
4662
Douglas Gregor4287b372008-12-12 08:25:50 +00004663 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004664
4665 // Make sure we aren't redeclaring the conversion function.
4666 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004667
4668 // C++ [class.conv.fct]p1:
4669 // [...] A conversion function is never used to convert a
4670 // (possibly cv-qualified) object to the (possibly cv-qualified)
4671 // same object type (or a reference to it), to a (possibly
4672 // cv-qualified) base class of that type (or a reference to it),
4673 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004674 // FIXME: Suppress this warning if the conversion function ends up being a
4675 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004676 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004677 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004678 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004679 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004680 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4681 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004682 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004683 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004684 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4685 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004686 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004687 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004688 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004689 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004690 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004691 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004692 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004693 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004694 }
4695
Douglas Gregor457104e2010-09-29 04:25:11 +00004696 if (FunctionTemplateDecl *ConversionTemplate
4697 = Conversion->getDescribedFunctionTemplate())
4698 return ConversionTemplate;
4699
John McCall48871652010-08-21 09:40:31 +00004700 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004701}
4702
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004703//===----------------------------------------------------------------------===//
4704// Namespace Handling
4705//===----------------------------------------------------------------------===//
4706
John McCallb1be5232010-08-26 09:15:37 +00004707
4708
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004709/// ActOnStartNamespaceDef - This is called at the start of a namespace
4710/// definition.
John McCall48871652010-08-21 09:40:31 +00004711Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004712 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004713 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004714 SourceLocation IdentLoc,
4715 IdentifierInfo *II,
4716 SourceLocation LBrace,
4717 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004718 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4719 // For anonymous namespace, take the location of the left brace.
4720 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004721 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004722 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004723 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004724
4725 Scope *DeclRegionScope = NamespcScope->getParent();
4726
Anders Carlssona7bcade2010-02-07 01:09:23 +00004727 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4728
John McCall2faf32c2010-12-10 02:59:44 +00004729 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4730 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004731
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004732 if (II) {
4733 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004734 // The identifier in an original-namespace-definition shall not
4735 // have been previously defined in the declarative region in
4736 // which the original-namespace-definition appears. The
4737 // identifier in an original-namespace-definition is the name of
4738 // the namespace. Subsequently in that declarative region, it is
4739 // treated as an original-namespace-name.
4740 //
4741 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004742 // look through using directives, just look for any ordinary names.
4743
4744 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4745 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4746 Decl::IDNS_Namespace;
4747 NamedDecl *PrevDecl = 0;
4748 for (DeclContext::lookup_result R
4749 = CurContext->getRedeclContext()->lookup(II);
4750 R.first != R.second; ++R.first) {
4751 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4752 PrevDecl = *R.first;
4753 break;
4754 }
4755 }
4756
Douglas Gregor91f84212008-12-11 16:49:14 +00004757 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4758 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004759 if (Namespc->isInline() != OrigNS->isInline()) {
4760 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004761 if (OrigNS->isInline()) {
4762 // The user probably just forgot the 'inline', so suggest that it
4763 // be added back.
4764 Diag(Namespc->getLocation(),
4765 diag::warn_inline_namespace_reopened_noninline)
4766 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4767 } else {
4768 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4769 << Namespc->isInline();
4770 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004771 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004772
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004773 // Recover by ignoring the new namespace's inline status.
4774 Namespc->setInline(OrigNS->isInline());
4775 }
4776
Douglas Gregor91f84212008-12-11 16:49:14 +00004777 // Attach this namespace decl to the chain of extended namespace
4778 // definitions.
4779 OrigNS->setNextNamespace(Namespc);
4780 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004781
Mike Stump11289f42009-09-09 15:08:12 +00004782 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004783 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004784 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004785 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004786 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004787 } else if (PrevDecl) {
4788 // This is an invalid name redefinition.
4789 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4790 << Namespc->getDeclName();
4791 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4792 Namespc->setInvalidDecl();
4793 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004794 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004795 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004796 // This is the first "real" definition of the namespace "std", so update
4797 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004798 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004799 // We had already defined a dummy namespace "std". Link this new
4800 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004801 StdNS->setNextNamespace(Namespc);
4802 StdNS->setLocation(IdentLoc);
4803 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004804 }
4805
4806 // Make our StdNamespace cache point at the first real definition of the
4807 // "std" namespace.
4808 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00004809 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004810
4811 PushOnScopeChains(Namespc, DeclRegionScope);
4812 } else {
John McCall4fa53422009-10-01 00:25:31 +00004813 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004814 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004815
4816 // Link the anonymous namespace into its parent.
4817 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004818 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004819 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4820 PrevDecl = TU->getAnonymousNamespace();
4821 TU->setAnonymousNamespace(Namespc);
4822 } else {
4823 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4824 PrevDecl = ND->getAnonymousNamespace();
4825 ND->setAnonymousNamespace(Namespc);
4826 }
4827
4828 // Link the anonymous namespace with its previous declaration.
4829 if (PrevDecl) {
4830 assert(PrevDecl->isAnonymousNamespace());
4831 assert(!PrevDecl->getNextNamespace());
4832 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4833 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004834
4835 if (Namespc->isInline() != PrevDecl->isInline()) {
4836 // inline-ness must match
4837 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4838 << Namespc->isInline();
4839 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4840 Namespc->setInvalidDecl();
4841 // Recover by ignoring the new namespace's inline status.
4842 Namespc->setInline(PrevDecl->isInline());
4843 }
John McCall0db42252009-12-16 02:06:49 +00004844 }
John McCall4fa53422009-10-01 00:25:31 +00004845
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004846 CurContext->addDecl(Namespc);
4847
John McCall4fa53422009-10-01 00:25:31 +00004848 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4849 // behaves as if it were replaced by
4850 // namespace unique { /* empty body */ }
4851 // using namespace unique;
4852 // namespace unique { namespace-body }
4853 // where all occurrences of 'unique' in a translation unit are
4854 // replaced by the same identifier and this identifier differs
4855 // from all other identifiers in the entire program.
4856
4857 // We just create the namespace with an empty name and then add an
4858 // implicit using declaration, just like the standard suggests.
4859 //
4860 // CodeGen enforces the "universally unique" aspect by giving all
4861 // declarations semantically contained within an anonymous
4862 // namespace internal linkage.
4863
John McCall0db42252009-12-16 02:06:49 +00004864 if (!PrevDecl) {
4865 UsingDirectiveDecl* UD
4866 = UsingDirectiveDecl::Create(Context, CurContext,
4867 /* 'using' */ LBrace,
4868 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004869 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004870 /* identifier */ SourceLocation(),
4871 Namespc,
4872 /* Ancestor */ CurContext);
4873 UD->setImplicit();
4874 CurContext->addDecl(UD);
4875 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004876 }
4877
4878 // Although we could have an invalid decl (i.e. the namespace name is a
4879 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004880 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4881 // for the namespace has the declarations that showed up in that particular
4882 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004883 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004884 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004885}
4886
Sebastian Redla6602e92009-11-23 15:34:23 +00004887/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4888/// is a namespace alias, returns the namespace it points to.
4889static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4890 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4891 return AD->getNamespace();
4892 return dyn_cast_or_null<NamespaceDecl>(D);
4893}
4894
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004895/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4896/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004897void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004898 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4899 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004900 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004901 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004902 if (Namespc->hasAttr<VisibilityAttr>())
4903 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004904}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004905
John McCall28a0cf72010-08-25 07:42:41 +00004906CXXRecordDecl *Sema::getStdBadAlloc() const {
4907 return cast_or_null<CXXRecordDecl>(
4908 StdBadAlloc.get(Context.getExternalSource()));
4909}
4910
4911NamespaceDecl *Sema::getStdNamespace() const {
4912 return cast_or_null<NamespaceDecl>(
4913 StdNamespace.get(Context.getExternalSource()));
4914}
4915
Douglas Gregorcdf87022010-06-29 17:53:46 +00004916/// \brief Retrieve the special "std" namespace, which may require us to
4917/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004918NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004919 if (!StdNamespace) {
4920 // The "std" namespace has not yet been defined, so build one implicitly.
4921 StdNamespace = NamespaceDecl::Create(Context,
4922 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004923 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004924 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004925 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004926 }
4927
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004928 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004929}
4930
Douglas Gregora172e082011-03-26 22:25:30 +00004931/// \brief Determine whether a using statement is in a context where it will be
4932/// apply in all contexts.
4933static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4934 switch (CurContext->getDeclKind()) {
4935 case Decl::TranslationUnit:
4936 return true;
4937 case Decl::LinkageSpec:
4938 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4939 default:
4940 return false;
4941 }
4942}
4943
John McCall48871652010-08-21 09:40:31 +00004944Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004945 SourceLocation UsingLoc,
4946 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004947 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004948 SourceLocation IdentLoc,
4949 IdentifierInfo *NamespcName,
4950 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004951 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4952 assert(NamespcName && "Invalid NamespcName.");
4953 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004954
4955 // This can only happen along a recovery path.
4956 while (S->getFlags() & Scope::TemplateParamScope)
4957 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004958 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004959
Douglas Gregor889ceb72009-02-03 19:21:40 +00004960 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004961 NestedNameSpecifier *Qualifier = 0;
4962 if (SS.isSet())
4963 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4964
Douglas Gregor34074322009-01-14 22:20:51 +00004965 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004966 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4967 LookupParsedName(R, S, &SS);
4968 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004969 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004970
Douglas Gregorcdf87022010-06-29 17:53:46 +00004971 if (R.empty()) {
4972 // Allow "using namespace std;" or "using namespace ::std;" even if
4973 // "std" hasn't been defined yet, for GCC compatibility.
4974 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4975 NamespcName->isStr("std")) {
4976 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004977 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004978 R.resolveKind();
4979 }
4980 // Otherwise, attempt typo correction.
4981 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4982 CTC_NoKeywords, 0)) {
4983 if (R.getAsSingle<NamespaceDecl>() ||
4984 R.getAsSingle<NamespaceAliasDecl>()) {
4985 if (DeclContext *DC = computeDeclContext(SS, false))
4986 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4987 << NamespcName << DC << Corrected << SS.getRange()
4988 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4989 else
4990 Diag(IdentLoc, diag::err_using_directive_suggest)
4991 << NamespcName << Corrected
4992 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4993 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4994 << Corrected;
4995
4996 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004997 } else {
4998 R.clear();
4999 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005000 }
5001 }
5002 }
5003
John McCall9f3059a2009-10-09 21:13:30 +00005004 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00005005 NamedDecl *Named = R.getFoundDecl();
5006 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5007 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00005008 // C++ [namespace.udir]p1:
5009 // A using-directive specifies that the names in the nominated
5010 // namespace can be used in the scope in which the
5011 // using-directive appears after the using-directive. During
5012 // unqualified name lookup (3.4.1), the names appear as if they
5013 // were declared in the nearest enclosing namespace which
5014 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00005015 // namespace. [Note: in this context, "contains" means "contains
5016 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00005017
5018 // Find enclosing context containing both using-directive and
5019 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00005020 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005021 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5022 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5023 CommonAncestor = CommonAncestor->getParent();
5024
Sebastian Redla6602e92009-11-23 15:34:23 +00005025 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00005026 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00005027 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005028
Douglas Gregora172e082011-03-26 22:25:30 +00005029 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00005030 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00005031 Diag(IdentLoc, diag::warn_using_directive_in_header);
5032 }
5033
Douglas Gregor889ceb72009-02-03 19:21:40 +00005034 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005035 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00005036 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00005037 }
5038
Douglas Gregor889ceb72009-02-03 19:21:40 +00005039 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00005040 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00005041}
5042
5043void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5044 // If scope has associated entity, then using directive is at namespace
5045 // or translation unit scope. We add UsingDirectiveDecls, into
5046 // it's lookup structure.
5047 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005048 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00005049 else
5050 // Otherwise it is block-sope. using-directives will affect lookup
5051 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00005052 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00005053}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005054
Douglas Gregorfec52632009-06-20 00:51:54 +00005055
John McCall48871652010-08-21 09:40:31 +00005056Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00005057 AccessSpecifier AS,
5058 bool HasUsingKeyword,
5059 SourceLocation UsingLoc,
5060 CXXScopeSpec &SS,
5061 UnqualifiedId &Name,
5062 AttributeList *AttrList,
5063 bool IsTypeName,
5064 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00005065 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00005066
Douglas Gregor220f4272009-11-04 16:30:06 +00005067 switch (Name.getKind()) {
5068 case UnqualifiedId::IK_Identifier:
5069 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00005070 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00005071 case UnqualifiedId::IK_ConversionFunctionId:
5072 break;
5073
5074 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00005075 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00005076 // C++0x inherited constructors.
5077 if (getLangOptions().CPlusPlus0x) break;
5078
Douglas Gregor220f4272009-11-04 16:30:06 +00005079 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5080 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005081 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005082
5083 case UnqualifiedId::IK_DestructorName:
5084 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5085 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005086 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005087
5088 case UnqualifiedId::IK_TemplateId:
5089 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5090 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005091 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005092 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005093
5094 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5095 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005096 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005097 return 0;
John McCall3969e302009-12-08 07:46:18 +00005098
John McCalla0097262009-12-11 02:10:03 +00005099 // Warn about using declarations.
5100 // TODO: store that the declaration was written without 'using' and
5101 // talk about access decls instead of using decls in the
5102 // diagnostics.
5103 if (!HasUsingKeyword) {
5104 UsingLoc = Name.getSourceRange().getBegin();
5105
5106 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005107 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005108 }
5109
Douglas Gregorc4356532010-12-16 00:46:58 +00005110 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5111 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5112 return 0;
5113
John McCall3f746822009-11-17 05:59:44 +00005114 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005115 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005116 /* IsInstantiation */ false,
5117 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005118 if (UD)
5119 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005120
John McCall48871652010-08-21 09:40:31 +00005121 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005122}
5123
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005124/// \brief Determine whether a using declaration considers the given
5125/// declarations as "equivalent", e.g., if they are redeclarations of
5126/// the same entity or are both typedefs of the same type.
5127static bool
5128IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5129 bool &SuppressRedeclaration) {
5130 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5131 SuppressRedeclaration = false;
5132 return true;
5133 }
5134
Richard Smithdda56e42011-04-15 14:24:37 +00005135 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5136 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005137 SuppressRedeclaration = true;
5138 return Context.hasSameType(TD1->getUnderlyingType(),
5139 TD2->getUnderlyingType());
5140 }
5141
5142 return false;
5143}
5144
5145
John McCall84d87672009-12-10 09:41:52 +00005146/// Determines whether to create a using shadow decl for a particular
5147/// decl, given the set of decls existing prior to this using lookup.
5148bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5149 const LookupResult &Previous) {
5150 // Diagnose finding a decl which is not from a base class of the
5151 // current class. We do this now because there are cases where this
5152 // function will silently decide not to build a shadow decl, which
5153 // will pre-empt further diagnostics.
5154 //
5155 // We don't need to do this in C++0x because we do the check once on
5156 // the qualifier.
5157 //
5158 // FIXME: diagnose the following if we care enough:
5159 // struct A { int foo; };
5160 // struct B : A { using A::foo; };
5161 // template <class T> struct C : A {};
5162 // template <class T> struct D : C<T> { using B::foo; } // <---
5163 // This is invalid (during instantiation) in C++03 because B::foo
5164 // resolves to the using decl in B, which is not a base class of D<T>.
5165 // We can't diagnose it immediately because C<T> is an unknown
5166 // specialization. The UsingShadowDecl in D<T> then points directly
5167 // to A::foo, which will look well-formed when we instantiate.
5168 // The right solution is to not collapse the shadow-decl chain.
5169 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5170 DeclContext *OrigDC = Orig->getDeclContext();
5171
5172 // Handle enums and anonymous structs.
5173 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5174 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5175 while (OrigRec->isAnonymousStructOrUnion())
5176 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5177
5178 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5179 if (OrigDC == CurContext) {
5180 Diag(Using->getLocation(),
5181 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005182 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005183 Diag(Orig->getLocation(), diag::note_using_decl_target);
5184 return true;
5185 }
5186
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005187 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005188 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005189 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005190 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005191 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005192 Diag(Orig->getLocation(), diag::note_using_decl_target);
5193 return true;
5194 }
5195 }
5196
5197 if (Previous.empty()) return false;
5198
5199 NamedDecl *Target = Orig;
5200 if (isa<UsingShadowDecl>(Target))
5201 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5202
John McCalla17e83e2009-12-11 02:33:26 +00005203 // If the target happens to be one of the previous declarations, we
5204 // don't have a conflict.
5205 //
5206 // FIXME: but we might be increasing its access, in which case we
5207 // should redeclare it.
5208 NamedDecl *NonTag = 0, *Tag = 0;
5209 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5210 I != E; ++I) {
5211 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005212 bool Result;
5213 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5214 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005215
5216 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5217 }
5218
John McCall84d87672009-12-10 09:41:52 +00005219 if (Target->isFunctionOrFunctionTemplate()) {
5220 FunctionDecl *FD;
5221 if (isa<FunctionTemplateDecl>(Target))
5222 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5223 else
5224 FD = cast<FunctionDecl>(Target);
5225
5226 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005227 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005228 case Ovl_Overload:
5229 return false;
5230
5231 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005232 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005233 break;
5234
5235 // We found a decl with the exact signature.
5236 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005237 // If we're in a record, we want to hide the target, so we
5238 // return true (without a diagnostic) to tell the caller not to
5239 // build a shadow decl.
5240 if (CurContext->isRecord())
5241 return true;
5242
5243 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005244 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005245 break;
5246 }
5247
5248 Diag(Target->getLocation(), diag::note_using_decl_target);
5249 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5250 return true;
5251 }
5252
5253 // Target is not a function.
5254
John McCall84d87672009-12-10 09:41:52 +00005255 if (isa<TagDecl>(Target)) {
5256 // No conflict between a tag and a non-tag.
5257 if (!Tag) return false;
5258
John McCalle29c5cd2009-12-10 19:51:03 +00005259 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005260 Diag(Target->getLocation(), diag::note_using_decl_target);
5261 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5262 return true;
5263 }
5264
5265 // No conflict between a tag and a non-tag.
5266 if (!NonTag) return false;
5267
John McCalle29c5cd2009-12-10 19:51:03 +00005268 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005269 Diag(Target->getLocation(), diag::note_using_decl_target);
5270 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5271 return true;
5272}
5273
John McCall3f746822009-11-17 05:59:44 +00005274/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005275UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005276 UsingDecl *UD,
5277 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005278
5279 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005280 NamedDecl *Target = Orig;
5281 if (isa<UsingShadowDecl>(Target)) {
5282 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5283 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005284 }
5285
5286 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005287 = UsingShadowDecl::Create(Context, CurContext,
5288 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005289 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005290
5291 Shadow->setAccess(UD->getAccess());
5292 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5293 Shadow->setInvalidDecl();
5294
John McCall3f746822009-11-17 05:59:44 +00005295 if (S)
John McCall3969e302009-12-08 07:46:18 +00005296 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005297 else
John McCall3969e302009-12-08 07:46:18 +00005298 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005299
John McCall3969e302009-12-08 07:46:18 +00005300
John McCall84d87672009-12-10 09:41:52 +00005301 return Shadow;
5302}
John McCall3969e302009-12-08 07:46:18 +00005303
John McCall84d87672009-12-10 09:41:52 +00005304/// Hides a using shadow declaration. This is required by the current
5305/// using-decl implementation when a resolvable using declaration in a
5306/// class is followed by a declaration which would hide or override
5307/// one or more of the using decl's targets; for example:
5308///
5309/// struct Base { void foo(int); };
5310/// struct Derived : Base {
5311/// using Base::foo;
5312/// void foo(int);
5313/// };
5314///
5315/// The governing language is C++03 [namespace.udecl]p12:
5316///
5317/// When a using-declaration brings names from a base class into a
5318/// derived class scope, member functions in the derived class
5319/// override and/or hide member functions with the same name and
5320/// parameter types in a base class (rather than conflicting).
5321///
5322/// There are two ways to implement this:
5323/// (1) optimistically create shadow decls when they're not hidden
5324/// by existing declarations, or
5325/// (2) don't create any shadow decls (or at least don't make them
5326/// visible) until we've fully parsed/instantiated the class.
5327/// The problem with (1) is that we might have to retroactively remove
5328/// a shadow decl, which requires several O(n) operations because the
5329/// decl structures are (very reasonably) not designed for removal.
5330/// (2) avoids this but is very fiddly and phase-dependent.
5331void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005332 if (Shadow->getDeclName().getNameKind() ==
5333 DeclarationName::CXXConversionFunctionName)
5334 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5335
John McCall84d87672009-12-10 09:41:52 +00005336 // Remove it from the DeclContext...
5337 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005338
John McCall84d87672009-12-10 09:41:52 +00005339 // ...and the scope, if applicable...
5340 if (S) {
John McCall48871652010-08-21 09:40:31 +00005341 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005342 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005343 }
5344
John McCall84d87672009-12-10 09:41:52 +00005345 // ...and the using decl.
5346 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5347
5348 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005349 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005350}
5351
John McCalle61f2ba2009-11-18 02:36:19 +00005352/// Builds a using declaration.
5353///
5354/// \param IsInstantiation - Whether this call arises from an
5355/// instantiation of an unresolved using declaration. We treat
5356/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005357NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5358 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005359 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005360 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005361 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005362 bool IsInstantiation,
5363 bool IsTypeName,
5364 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005365 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005366 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005367 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005368
Anders Carlssonf038fc22009-08-28 05:49:21 +00005369 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005370
Anders Carlsson59140b32009-08-28 03:16:11 +00005371 if (SS.isEmpty()) {
5372 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005373 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005374 }
Mike Stump11289f42009-09-09 15:08:12 +00005375
John McCall84d87672009-12-10 09:41:52 +00005376 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005377 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005378 ForRedeclaration);
5379 Previous.setHideTags(false);
5380 if (S) {
5381 LookupName(Previous, S);
5382
5383 // It is really dumb that we have to do this.
5384 LookupResult::Filter F = Previous.makeFilter();
5385 while (F.hasNext()) {
5386 NamedDecl *D = F.next();
5387 if (!isDeclInScope(D, CurContext, S))
5388 F.erase();
5389 }
5390 F.done();
5391 } else {
5392 assert(IsInstantiation && "no scope in non-instantiation");
5393 assert(CurContext->isRecord() && "scope not record in instantiation");
5394 LookupQualifiedName(Previous, CurContext);
5395 }
5396
John McCall84d87672009-12-10 09:41:52 +00005397 // Check for invalid redeclarations.
5398 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5399 return 0;
5400
5401 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005402 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5403 return 0;
5404
John McCall84c16cf2009-11-12 03:15:40 +00005405 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005406 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005407 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005408 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005409 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005410 // FIXME: not all declaration name kinds are legal here
5411 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5412 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005413 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005414 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005415 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005416 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5417 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005418 }
John McCallb96ec562009-12-04 22:46:56 +00005419 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005420 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5421 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005422 }
John McCallb96ec562009-12-04 22:46:56 +00005423 D->setAccess(AS);
5424 CurContext->addDecl(D);
5425
5426 if (!LookupContext) return D;
5427 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005428
John McCall0b66eb32010-05-01 00:40:08 +00005429 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005430 UD->setInvalidDecl();
5431 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005432 }
5433
Sebastian Redl08905022011-02-05 19:23:19 +00005434 // Constructor inheriting using decls get special treatment.
5435 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005436 if (CheckInheritedConstructorUsingDecl(UD))
5437 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005438 return UD;
5439 }
5440
5441 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005442
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005443 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005444 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005445
John McCall3969e302009-12-08 07:46:18 +00005446 // Unlike most lookups, we don't always want to hide tag
5447 // declarations: tag names are visible through the using declaration
5448 // even if hidden by ordinary names, *except* in a dependent context
5449 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005450 if (!IsInstantiation)
5451 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005452
John McCall27b18f82009-11-17 02:14:36 +00005453 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005454
John McCall9f3059a2009-10-09 21:13:30 +00005455 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005456 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005457 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005458 UD->setInvalidDecl();
5459 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005460 }
5461
John McCallb96ec562009-12-04 22:46:56 +00005462 if (R.isAmbiguous()) {
5463 UD->setInvalidDecl();
5464 return UD;
5465 }
Mike Stump11289f42009-09-09 15:08:12 +00005466
John McCalle61f2ba2009-11-18 02:36:19 +00005467 if (IsTypeName) {
5468 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005469 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005470 Diag(IdentLoc, diag::err_using_typename_non_type);
5471 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5472 Diag((*I)->getUnderlyingDecl()->getLocation(),
5473 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005474 UD->setInvalidDecl();
5475 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005476 }
5477 } else {
5478 // If we asked for a non-typename and we got a type, error out,
5479 // but only if this is an instantiation of an unresolved using
5480 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005481 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005482 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5483 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005484 UD->setInvalidDecl();
5485 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005486 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005487 }
5488
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005489 // C++0x N2914 [namespace.udecl]p6:
5490 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005491 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005492 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5493 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005494 UD->setInvalidDecl();
5495 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005496 }
Mike Stump11289f42009-09-09 15:08:12 +00005497
John McCall84d87672009-12-10 09:41:52 +00005498 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5499 if (!CheckUsingShadowDecl(UD, *I, Previous))
5500 BuildUsingShadowDecl(S, UD, *I);
5501 }
John McCall3f746822009-11-17 05:59:44 +00005502
5503 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005504}
5505
Sebastian Redl08905022011-02-05 19:23:19 +00005506/// Additional checks for a using declaration referring to a constructor name.
5507bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5508 if (UD->isTypeName()) {
5509 // FIXME: Cannot specify typename when specifying constructor
5510 return true;
5511 }
5512
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005513 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005514 assert(SourceType &&
5515 "Using decl naming constructor doesn't have type in scope spec.");
5516 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5517
5518 // Check whether the named type is a direct base class.
5519 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5520 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5521 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5522 BaseIt != BaseE; ++BaseIt) {
5523 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5524 if (CanonicalSourceType == BaseType)
5525 break;
5526 }
5527
5528 if (BaseIt == BaseE) {
5529 // Did not find SourceType in the bases.
5530 Diag(UD->getUsingLocation(),
5531 diag::err_using_decl_constructor_not_in_direct_base)
5532 << UD->getNameInfo().getSourceRange()
5533 << QualType(SourceType, 0) << TargetClass;
5534 return true;
5535 }
5536
5537 BaseIt->setInheritConstructors();
5538
5539 return false;
5540}
5541
John McCall84d87672009-12-10 09:41:52 +00005542/// Checks that the given using declaration is not an invalid
5543/// redeclaration. Note that this is checking only for the using decl
5544/// itself, not for any ill-formedness among the UsingShadowDecls.
5545bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5546 bool isTypeName,
5547 const CXXScopeSpec &SS,
5548 SourceLocation NameLoc,
5549 const LookupResult &Prev) {
5550 // C++03 [namespace.udecl]p8:
5551 // C++0x [namespace.udecl]p10:
5552 // A using-declaration is a declaration and can therefore be used
5553 // repeatedly where (and only where) multiple declarations are
5554 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005555 //
John McCall032092f2010-11-29 18:01:58 +00005556 // That's in non-member contexts.
5557 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005558 return false;
5559
5560 NestedNameSpecifier *Qual
5561 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5562
5563 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5564 NamedDecl *D = *I;
5565
5566 bool DTypename;
5567 NestedNameSpecifier *DQual;
5568 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5569 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005570 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005571 } else if (UnresolvedUsingValueDecl *UD
5572 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5573 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005574 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005575 } else if (UnresolvedUsingTypenameDecl *UD
5576 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5577 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005578 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005579 } else continue;
5580
5581 // using decls differ if one says 'typename' and the other doesn't.
5582 // FIXME: non-dependent using decls?
5583 if (isTypeName != DTypename) continue;
5584
5585 // using decls differ if they name different scopes (but note that
5586 // template instantiation can cause this check to trigger when it
5587 // didn't before instantiation).
5588 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5589 Context.getCanonicalNestedNameSpecifier(DQual))
5590 continue;
5591
5592 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005593 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005594 return true;
5595 }
5596
5597 return false;
5598}
5599
John McCall3969e302009-12-08 07:46:18 +00005600
John McCallb96ec562009-12-04 22:46:56 +00005601/// Checks that the given nested-name qualifier used in a using decl
5602/// in the current context is appropriately related to the current
5603/// scope. If an error is found, diagnoses it and returns true.
5604bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5605 const CXXScopeSpec &SS,
5606 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005607 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005608
John McCall3969e302009-12-08 07:46:18 +00005609 if (!CurContext->isRecord()) {
5610 // C++03 [namespace.udecl]p3:
5611 // C++0x [namespace.udecl]p8:
5612 // A using-declaration for a class member shall be a member-declaration.
5613
5614 // If we weren't able to compute a valid scope, it must be a
5615 // dependent class scope.
5616 if (!NamedContext || NamedContext->isRecord()) {
5617 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5618 << SS.getRange();
5619 return true;
5620 }
5621
5622 // Otherwise, everything is known to be fine.
5623 return false;
5624 }
5625
5626 // The current scope is a record.
5627
5628 // If the named context is dependent, we can't decide much.
5629 if (!NamedContext) {
5630 // FIXME: in C++0x, we can diagnose if we can prove that the
5631 // nested-name-specifier does not refer to a base class, which is
5632 // still possible in some cases.
5633
5634 // Otherwise we have to conservatively report that things might be
5635 // okay.
5636 return false;
5637 }
5638
5639 if (!NamedContext->isRecord()) {
5640 // Ideally this would point at the last name in the specifier,
5641 // but we don't have that level of source info.
5642 Diag(SS.getRange().getBegin(),
5643 diag::err_using_decl_nested_name_specifier_is_not_class)
5644 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5645 return true;
5646 }
5647
Douglas Gregor7c842292010-12-21 07:41:49 +00005648 if (!NamedContext->isDependentContext() &&
5649 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5650 return true;
5651
John McCall3969e302009-12-08 07:46:18 +00005652 if (getLangOptions().CPlusPlus0x) {
5653 // C++0x [namespace.udecl]p3:
5654 // In a using-declaration used as a member-declaration, the
5655 // nested-name-specifier shall name a base class of the class
5656 // being defined.
5657
5658 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5659 cast<CXXRecordDecl>(NamedContext))) {
5660 if (CurContext == NamedContext) {
5661 Diag(NameLoc,
5662 diag::err_using_decl_nested_name_specifier_is_current_class)
5663 << SS.getRange();
5664 return true;
5665 }
5666
5667 Diag(SS.getRange().getBegin(),
5668 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5669 << (NestedNameSpecifier*) SS.getScopeRep()
5670 << cast<CXXRecordDecl>(CurContext)
5671 << SS.getRange();
5672 return true;
5673 }
5674
5675 return false;
5676 }
5677
5678 // C++03 [namespace.udecl]p4:
5679 // A using-declaration used as a member-declaration shall refer
5680 // to a member of a base class of the class being defined [etc.].
5681
5682 // Salient point: SS doesn't have to name a base class as long as
5683 // lookup only finds members from base classes. Therefore we can
5684 // diagnose here only if we can prove that that can't happen,
5685 // i.e. if the class hierarchies provably don't intersect.
5686
5687 // TODO: it would be nice if "definitely valid" results were cached
5688 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5689 // need to be repeated.
5690
5691 struct UserData {
5692 llvm::DenseSet<const CXXRecordDecl*> Bases;
5693
5694 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5695 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5696 Data->Bases.insert(Base);
5697 return true;
5698 }
5699
5700 bool hasDependentBases(const CXXRecordDecl *Class) {
5701 return !Class->forallBases(collect, this);
5702 }
5703
5704 /// Returns true if the base is dependent or is one of the
5705 /// accumulated base classes.
5706 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5707 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5708 return !Data->Bases.count(Base);
5709 }
5710
5711 bool mightShareBases(const CXXRecordDecl *Class) {
5712 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5713 }
5714 };
5715
5716 UserData Data;
5717
5718 // Returns false if we find a dependent base.
5719 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5720 return false;
5721
5722 // Returns false if the class has a dependent base or if it or one
5723 // of its bases is present in the base set of the current context.
5724 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5725 return false;
5726
5727 Diag(SS.getRange().getBegin(),
5728 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5729 << (NestedNameSpecifier*) SS.getScopeRep()
5730 << cast<CXXRecordDecl>(CurContext)
5731 << SS.getRange();
5732
5733 return true;
John McCallb96ec562009-12-04 22:46:56 +00005734}
5735
Richard Smithdda56e42011-04-15 14:24:37 +00005736Decl *Sema::ActOnAliasDeclaration(Scope *S,
5737 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005738 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005739 SourceLocation UsingLoc,
5740 UnqualifiedId &Name,
5741 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005742 // Skip up to the relevant declaration scope.
5743 while (S->getFlags() & Scope::TemplateParamScope)
5744 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005745 assert((S->getFlags() & Scope::DeclScope) &&
5746 "got alias-declaration outside of declaration scope");
5747
5748 if (Type.isInvalid())
5749 return 0;
5750
5751 bool Invalid = false;
5752 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5753 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005754 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005755
5756 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5757 return 0;
5758
5759 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005760 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005761 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005762 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5763 TInfo->getTypeLoc().getBeginLoc());
5764 }
Richard Smithdda56e42011-04-15 14:24:37 +00005765
5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5767 LookupName(Previous, S);
5768
5769 // Warn about shadowing the name of a template parameter.
5770 if (Previous.isSingleResult() &&
5771 Previous.getFoundDecl()->isTemplateParameter()) {
5772 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5773 Previous.getFoundDecl()))
5774 Invalid = true;
5775 Previous.clear();
5776 }
5777
5778 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5779 "name in alias declaration must be an identifier");
5780 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5781 Name.StartLocation,
5782 Name.Identifier, TInfo);
5783
5784 NewTD->setAccess(AS);
5785
5786 if (Invalid)
5787 NewTD->setInvalidDecl();
5788
Richard Smith3f1b5d02011-05-05 21:57:07 +00005789 CheckTypedefForVariablyModifiedType(S, NewTD);
5790 Invalid |= NewTD->isInvalidDecl();
5791
Richard Smithdda56e42011-04-15 14:24:37 +00005792 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005793
5794 NamedDecl *NewND;
5795 if (TemplateParamLists.size()) {
5796 TypeAliasTemplateDecl *OldDecl = 0;
5797 TemplateParameterList *OldTemplateParams = 0;
5798
5799 if (TemplateParamLists.size() != 1) {
5800 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5801 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5802 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5803 }
5804 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5805
5806 // Only consider previous declarations in the same scope.
5807 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5808 /*ExplicitInstantiationOrSpecialization*/false);
5809 if (!Previous.empty()) {
5810 Redeclaration = true;
5811
5812 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5813 if (!OldDecl && !Invalid) {
5814 Diag(UsingLoc, diag::err_redefinition_different_kind)
5815 << Name.Identifier;
5816
5817 NamedDecl *OldD = Previous.getRepresentativeDecl();
5818 if (OldD->getLocation().isValid())
5819 Diag(OldD->getLocation(), diag::note_previous_definition);
5820
5821 Invalid = true;
5822 }
5823
5824 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5825 if (TemplateParameterListsAreEqual(TemplateParams,
5826 OldDecl->getTemplateParameters(),
5827 /*Complain=*/true,
5828 TPL_TemplateMatch))
5829 OldTemplateParams = OldDecl->getTemplateParameters();
5830 else
5831 Invalid = true;
5832
5833 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5834 if (!Invalid &&
5835 !Context.hasSameType(OldTD->getUnderlyingType(),
5836 NewTD->getUnderlyingType())) {
5837 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5838 // but we can't reasonably accept it.
5839 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5840 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5841 if (OldTD->getLocation().isValid())
5842 Diag(OldTD->getLocation(), diag::note_previous_definition);
5843 Invalid = true;
5844 }
5845 }
5846 }
5847
5848 // Merge any previous default template arguments into our parameters,
5849 // and check the parameter list.
5850 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5851 TPC_TypeAliasTemplate))
5852 return 0;
5853
5854 TypeAliasTemplateDecl *NewDecl =
5855 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5856 Name.Identifier, TemplateParams,
5857 NewTD);
5858
5859 NewDecl->setAccess(AS);
5860
5861 if (Invalid)
5862 NewDecl->setInvalidDecl();
5863 else if (OldDecl)
5864 NewDecl->setPreviousDeclaration(OldDecl);
5865
5866 NewND = NewDecl;
5867 } else {
5868 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5869 NewND = NewTD;
5870 }
Richard Smithdda56e42011-04-15 14:24:37 +00005871
5872 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005873 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005874
Richard Smith3f1b5d02011-05-05 21:57:07 +00005875 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005876}
5877
John McCall48871652010-08-21 09:40:31 +00005878Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005879 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005880 SourceLocation AliasLoc,
5881 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005882 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005883 SourceLocation IdentLoc,
5884 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005885
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005886 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005887 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5888 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005889
Anders Carlssondca83c42009-03-28 06:23:46 +00005890 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005891 NamedDecl *PrevDecl
5892 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5893 ForRedeclaration);
5894 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5895 PrevDecl = 0;
5896
5897 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005898 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005899 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005900 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005901 // FIXME: At some point, we'll want to create the (redundant)
5902 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005903 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005904 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005905 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005906 }
Mike Stump11289f42009-09-09 15:08:12 +00005907
Anders Carlssondca83c42009-03-28 06:23:46 +00005908 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5909 diag::err_redefinition_different_kind;
5910 Diag(AliasLoc, DiagID) << Alias;
5911 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005912 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005913 }
5914
John McCall27b18f82009-11-17 02:14:36 +00005915 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005916 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005917
John McCall9f3059a2009-10-09 21:13:30 +00005918 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005919 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5920 CTC_NoKeywords, 0)) {
5921 if (R.getAsSingle<NamespaceDecl>() ||
5922 R.getAsSingle<NamespaceAliasDecl>()) {
5923 if (DeclContext *DC = computeDeclContext(SS, false))
5924 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5925 << Ident << DC << Corrected << SS.getRange()
5926 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5927 else
5928 Diag(IdentLoc, diag::err_using_directive_suggest)
5929 << Ident << Corrected
5930 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5931
5932 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5933 << Corrected;
5934
5935 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00005936 } else {
5937 R.clear();
5938 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005939 }
5940 }
5941
5942 if (R.empty()) {
5943 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005944 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005945 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005946 }
Mike Stump11289f42009-09-09 15:08:12 +00005947
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005948 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005949 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005950 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005951 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005952
John McCalld8d0d432010-02-16 06:53:13 +00005953 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005954 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005955}
5956
Douglas Gregora57478e2010-05-01 15:04:51 +00005957namespace {
5958 /// \brief Scoped object used to handle the state changes required in Sema
5959 /// to implicitly define the body of a C++ member function;
5960 class ImplicitlyDefinedFunctionScope {
5961 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005962 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005963
5964 public:
5965 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005966 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005967 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005968 S.PushFunctionScope();
5969 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5970 }
5971
5972 ~ImplicitlyDefinedFunctionScope() {
5973 S.PopExpressionEvaluationContext();
5974 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005975 }
5976 };
5977}
5978
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005979Sema::ImplicitExceptionSpecification
5980Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005981 // C++ [except.spec]p14:
5982 // An implicitly declared special member function (Clause 12) shall have an
5983 // exception-specification. [...]
5984 ImplicitExceptionSpecification ExceptSpec(Context);
5985
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005986 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005987 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5988 BEnd = ClassDecl->bases_end();
5989 B != BEnd; ++B) {
5990 if (B->isVirtual()) // Handled below.
5991 continue;
5992
Douglas Gregor9672f922010-07-03 00:47:00 +00005993 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5994 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005995 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5996 // If this is a deleted function, add it anyway. This might be conformant
5997 // with the standard. This might not. I'm not sure. It might not matter.
5998 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005999 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006000 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006001 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006002
6003 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006004 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6005 BEnd = ClassDecl->vbases_end();
6006 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00006007 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6008 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00006009 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6010 // If this is a deleted function, add it anyway. This might be conformant
6011 // with the standard. This might not. I'm not sure. It might not matter.
6012 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006013 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006014 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006015 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006016
6017 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006018 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6019 FEnd = ClassDecl->field_end();
6020 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00006021 if (F->hasInClassInitializer()) {
6022 if (Expr *E = F->getInClassInitializer())
6023 ExceptSpec.CalledExpr(E);
6024 else if (!F->isInvalidDecl())
6025 ExceptSpec.SetDelayed();
6026 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00006027 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00006028 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6029 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6030 // If this is a deleted function, add it anyway. This might be conformant
6031 // with the standard. This might not. I'm not sure. It might not matter.
6032 // In particular, the problem is that this function never gets called. It
6033 // might just be ill-formed because this function attempts to refer to
6034 // a deleted function here.
6035 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00006036 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00006037 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00006038 }
John McCalldb40c7f2010-12-14 08:05:40 +00006039
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006040 return ExceptSpec;
6041}
6042
6043CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6044 CXXRecordDecl *ClassDecl) {
6045 // C++ [class.ctor]p5:
6046 // A default constructor for a class X is a constructor of class X
6047 // that can be called without an argument. If there is no
6048 // user-declared constructor for class X, a default constructor is
6049 // implicitly declared. An implicitly-declared default constructor
6050 // is an inline public member of its class.
6051 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6052 "Should not build implicit default constructor!");
6053
6054 ImplicitExceptionSpecification Spec =
6055 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6056 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00006057
Douglas Gregor6d880b12010-07-01 22:31:05 +00006058 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006059 CanQualType ClassType
6060 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006061 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006062 DeclarationName Name
6063 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006064 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006065 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00006066 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006067 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00006068 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006069 /*TInfo=*/0,
6070 /*isExplicit=*/false,
6071 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006072 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006073 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00006074 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006075 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00006076 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00006077
6078 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00006079 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6080
Douglas Gregor0be31a22010-07-02 17:43:08 +00006081 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00006082 PushOnScopeChains(DefaultCon, S, false);
6083 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00006084
6085 if (ShouldDeleteDefaultConstructor(DefaultCon))
6086 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00006087
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006088 return DefaultCon;
6089}
6090
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006091void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6092 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00006093 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006094 !Constructor->doesThisDeclarationHaveABody() &&
6095 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006096 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006097
Anders Carlsson423f5d82010-04-23 16:04:08 +00006098 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00006099 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00006100
Douglas Gregora57478e2010-05-01 15:04:51 +00006101 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006102 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006103 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006104 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006105 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006106 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006107 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006108 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006109 }
Douglas Gregor73193272010-09-20 16:48:21 +00006110
6111 SourceLocation Loc = Constructor->getLocation();
6112 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6113
6114 Constructor->setUsed();
6115 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006116
6117 if (ASTMutationListener *L = getASTMutationListener()) {
6118 L->CompletedImplicitDefinition(Constructor);
6119 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006120}
6121
Richard Smith938f40b2011-06-11 17:19:42 +00006122/// Get any existing defaulted default constructor for the given class. Do not
6123/// implicitly define one if it does not exist.
6124static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6125 CXXRecordDecl *D) {
6126 ASTContext &Context = Self.Context;
6127 QualType ClassType = Context.getTypeDeclType(D);
6128 DeclarationName ConstructorName
6129 = Context.DeclarationNames.getCXXConstructorName(
6130 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6131
6132 DeclContext::lookup_const_iterator Con, ConEnd;
6133 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6134 Con != ConEnd; ++Con) {
6135 // A function template cannot be defaulted.
6136 if (isa<FunctionTemplateDecl>(*Con))
6137 continue;
6138
6139 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6140 if (Constructor->isDefaultConstructor())
6141 return Constructor->isDefaulted() ? Constructor : 0;
6142 }
6143 return 0;
6144}
6145
6146void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6147 if (!D) return;
6148 AdjustDeclIfTemplate(D);
6149
6150 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6151 CXXConstructorDecl *CtorDecl
6152 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6153
6154 if (!CtorDecl) return;
6155
6156 // Compute the exception specification for the default constructor.
6157 const FunctionProtoType *CtorTy =
6158 CtorDecl->getType()->castAs<FunctionProtoType>();
6159 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6160 ImplicitExceptionSpecification Spec =
6161 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6162 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6163 assert(EPI.ExceptionSpecType != EST_Delayed);
6164
6165 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6166 }
6167
6168 // If the default constructor is explicitly defaulted, checking the exception
6169 // specification is deferred until now.
6170 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6171 !ClassDecl->isDependentType())
6172 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6173}
6174
Sebastian Redl08905022011-02-05 19:23:19 +00006175void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6176 // We start with an initial pass over the base classes to collect those that
6177 // inherit constructors from. If there are none, we can forgo all further
6178 // processing.
6179 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6180 BasesVector BasesToInheritFrom;
6181 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6182 BaseE = ClassDecl->bases_end();
6183 BaseIt != BaseE; ++BaseIt) {
6184 if (BaseIt->getInheritConstructors()) {
6185 QualType Base = BaseIt->getType();
6186 if (Base->isDependentType()) {
6187 // If we inherit constructors from anything that is dependent, just
6188 // abort processing altogether. We'll get another chance for the
6189 // instantiations.
6190 return;
6191 }
6192 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6193 }
6194 }
6195 if (BasesToInheritFrom.empty())
6196 return;
6197
6198 // Now collect the constructors that we already have in the current class.
6199 // Those take precedence over inherited constructors.
6200 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6201 // unless there is a user-declared constructor with the same signature in
6202 // the class where the using-declaration appears.
6203 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6204 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6205 CtorE = ClassDecl->ctor_end();
6206 CtorIt != CtorE; ++CtorIt) {
6207 ExistingConstructors.insert(
6208 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6209 }
6210
6211 Scope *S = getScopeForContext(ClassDecl);
6212 DeclarationName CreatedCtorName =
6213 Context.DeclarationNames.getCXXConstructorName(
6214 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6215
6216 // Now comes the true work.
6217 // First, we keep a map from constructor types to the base that introduced
6218 // them. Needed for finding conflicting constructors. We also keep the
6219 // actually inserted declarations in there, for pretty diagnostics.
6220 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6221 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6222 ConstructorToSourceMap InheritedConstructors;
6223 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6224 BaseE = BasesToInheritFrom.end();
6225 BaseIt != BaseE; ++BaseIt) {
6226 const RecordType *Base = *BaseIt;
6227 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6228 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6229 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6230 CtorE = BaseDecl->ctor_end();
6231 CtorIt != CtorE; ++CtorIt) {
6232 // Find the using declaration for inheriting this base's constructors.
6233 DeclarationName Name =
6234 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6235 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6236 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6237 SourceLocation UsingLoc = UD ? UD->getLocation() :
6238 ClassDecl->getLocation();
6239
6240 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6241 // from the class X named in the using-declaration consists of actual
6242 // constructors and notional constructors that result from the
6243 // transformation of defaulted parameters as follows:
6244 // - all non-template default constructors of X, and
6245 // - for each non-template constructor of X that has at least one
6246 // parameter with a default argument, the set of constructors that
6247 // results from omitting any ellipsis parameter specification and
6248 // successively omitting parameters with a default argument from the
6249 // end of the parameter-type-list.
6250 CXXConstructorDecl *BaseCtor = *CtorIt;
6251 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6252 const FunctionProtoType *BaseCtorType =
6253 BaseCtor->getType()->getAs<FunctionProtoType>();
6254
6255 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6256 maxParams = BaseCtor->getNumParams();
6257 params <= maxParams; ++params) {
6258 // Skip default constructors. They're never inherited.
6259 if (params == 0)
6260 continue;
6261 // Skip copy and move constructors for the same reason.
6262 if (CanBeCopyOrMove && params == 1)
6263 continue;
6264
6265 // Build up a function type for this particular constructor.
6266 // FIXME: The working paper does not consider that the exception spec
6267 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006268 // source. This code doesn't yet, either. When it does, this code will
6269 // need to be delayed until after exception specifications and in-class
6270 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006271 const Type *NewCtorType;
6272 if (params == maxParams)
6273 NewCtorType = BaseCtorType;
6274 else {
6275 llvm::SmallVector<QualType, 16> Args;
6276 for (unsigned i = 0; i < params; ++i) {
6277 Args.push_back(BaseCtorType->getArgType(i));
6278 }
6279 FunctionProtoType::ExtProtoInfo ExtInfo =
6280 BaseCtorType->getExtProtoInfo();
6281 ExtInfo.Variadic = false;
6282 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6283 Args.data(), params, ExtInfo)
6284 .getTypePtr();
6285 }
6286 const Type *CanonicalNewCtorType =
6287 Context.getCanonicalType(NewCtorType);
6288
6289 // Now that we have the type, first check if the class already has a
6290 // constructor with this signature.
6291 if (ExistingConstructors.count(CanonicalNewCtorType))
6292 continue;
6293
6294 // Then we check if we have already declared an inherited constructor
6295 // with this signature.
6296 std::pair<ConstructorToSourceMap::iterator, bool> result =
6297 InheritedConstructors.insert(std::make_pair(
6298 CanonicalNewCtorType,
6299 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6300 if (!result.second) {
6301 // Already in the map. If it came from a different class, that's an
6302 // error. Not if it's from the same.
6303 CanQualType PreviousBase = result.first->second.first;
6304 if (CanonicalBase != PreviousBase) {
6305 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6306 const CXXConstructorDecl *PrevBaseCtor =
6307 PrevCtor->getInheritedConstructor();
6308 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6309
6310 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6311 Diag(BaseCtor->getLocation(),
6312 diag::note_using_decl_constructor_conflict_current_ctor);
6313 Diag(PrevBaseCtor->getLocation(),
6314 diag::note_using_decl_constructor_conflict_previous_ctor);
6315 Diag(PrevCtor->getLocation(),
6316 diag::note_using_decl_constructor_conflict_previous_using);
6317 }
6318 continue;
6319 }
6320
6321 // OK, we're there, now add the constructor.
6322 // C++0x [class.inhctor]p8: [...] that would be performed by a
6323 // user-writtern inline constructor [...]
6324 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6325 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006326 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6327 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006328 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006329 NewCtor->setAccess(BaseCtor->getAccess());
6330
6331 // Build up the parameter decls and add them.
6332 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6333 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006334 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6335 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006336 /*IdentifierInfo=*/0,
6337 BaseCtorType->getArgType(i),
6338 /*TInfo=*/0, SC_None,
6339 SC_None, /*DefaultArg=*/0));
6340 }
6341 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6342 NewCtor->setInheritedConstructor(BaseCtor);
6343
6344 PushOnScopeChains(NewCtor, S, false);
6345 ClassDecl->addDecl(NewCtor);
6346 result.first->second.second = NewCtor;
6347 }
6348 }
6349 }
6350}
6351
Alexis Huntf91729462011-05-12 22:46:25 +00006352Sema::ImplicitExceptionSpecification
6353Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006354 // C++ [except.spec]p14:
6355 // An implicitly declared special member function (Clause 12) shall have
6356 // an exception-specification.
6357 ImplicitExceptionSpecification ExceptSpec(Context);
6358
6359 // Direct base-class destructors.
6360 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6361 BEnd = ClassDecl->bases_end();
6362 B != BEnd; ++B) {
6363 if (B->isVirtual()) // Handled below.
6364 continue;
6365
6366 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6367 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006368 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006369 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006370
Douglas Gregorf1203042010-07-01 19:09:28 +00006371 // Virtual base-class destructors.
6372 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6373 BEnd = ClassDecl->vbases_end();
6374 B != BEnd; ++B) {
6375 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6376 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006377 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006378 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006379
Douglas Gregorf1203042010-07-01 19:09:28 +00006380 // Field destructors.
6381 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6382 FEnd = ClassDecl->field_end();
6383 F != FEnd; ++F) {
6384 if (const RecordType *RecordTy
6385 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6386 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006387 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006388 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006389
Alexis Huntf91729462011-05-12 22:46:25 +00006390 return ExceptSpec;
6391}
6392
6393CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6394 // C++ [class.dtor]p2:
6395 // If a class has no user-declared destructor, a destructor is
6396 // declared implicitly. An implicitly-declared destructor is an
6397 // inline public member of its class.
6398
6399 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006400 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006401 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6402
Douglas Gregor7454c562010-07-02 20:37:36 +00006403 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006404 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006405
Douglas Gregorf1203042010-07-01 19:09:28 +00006406 CanQualType ClassType
6407 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006408 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006409 DeclarationName Name
6410 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006411 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006412 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006413 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6414 /*isInline=*/true,
6415 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006416 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006417 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006418 Destructor->setImplicit();
6419 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006420
6421 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006422 ++ASTContext::NumImplicitDestructorsDeclared;
6423
6424 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006425 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006426 PushOnScopeChains(Destructor, S, false);
6427 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006428
6429 // This could be uniqued if it ever proves significant.
6430 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006431
6432 if (ShouldDeleteDestructor(Destructor))
6433 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006434
6435 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006436
Douglas Gregorf1203042010-07-01 19:09:28 +00006437 return Destructor;
6438}
6439
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006440void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006441 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006442 assert((Destructor->isDefaulted() &&
6443 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006444 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006445 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006446 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006447
Douglas Gregor54818f02010-05-12 16:39:35 +00006448 if (Destructor->isInvalidDecl())
6449 return;
6450
Douglas Gregora57478e2010-05-01 15:04:51 +00006451 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006452
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006453 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006454 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6455 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006456
Douglas Gregor54818f02010-05-12 16:39:35 +00006457 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006458 Diag(CurrentLocation, diag::note_member_synthesized_at)
6459 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6460
6461 Destructor->setInvalidDecl();
6462 return;
6463 }
6464
Douglas Gregor73193272010-09-20 16:48:21 +00006465 SourceLocation Loc = Destructor->getLocation();
6466 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6467
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006468 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006469 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006470
6471 if (ASTMutationListener *L = getASTMutationListener()) {
6472 L->CompletedImplicitDefinition(Destructor);
6473 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006474}
6475
Sebastian Redl623ea822011-05-19 05:13:44 +00006476void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6477 CXXDestructorDecl *destructor) {
6478 // C++11 [class.dtor]p3:
6479 // A declaration of a destructor that does not have an exception-
6480 // specification is implicitly considered to have the same exception-
6481 // specification as an implicit declaration.
6482 const FunctionProtoType *dtorType = destructor->getType()->
6483 getAs<FunctionProtoType>();
6484 if (dtorType->hasExceptionSpec())
6485 return;
6486
6487 ImplicitExceptionSpecification exceptSpec =
6488 ComputeDefaultedDtorExceptionSpec(classDecl);
6489
6490 // Replace the destructor's type.
6491 FunctionProtoType::ExtProtoInfo epi;
6492 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6493 epi.NumExceptions = exceptSpec.size();
6494 epi.Exceptions = exceptSpec.data();
6495 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6496
6497 destructor->setType(ty);
6498
6499 // FIXME: If the destructor has a body that could throw, and the newly created
6500 // spec doesn't allow exceptions, we should emit a warning, because this
6501 // change in behavior can break conforming C++03 programs at runtime.
6502 // However, we don't have a body yet, so it needs to be done somewhere else.
6503}
6504
Douglas Gregorb139cd52010-05-01 20:49:11 +00006505/// \brief Builds a statement that copies the given entity from \p From to
6506/// \c To.
6507///
6508/// This routine is used to copy the members of a class with an
6509/// implicitly-declared copy assignment operator. When the entities being
6510/// copied are arrays, this routine builds for loops to copy them.
6511///
6512/// \param S The Sema object used for type-checking.
6513///
6514/// \param Loc The location where the implicit copy is being generated.
6515///
6516/// \param T The type of the expressions being copied. Both expressions must
6517/// have this type.
6518///
6519/// \param To The expression we are copying to.
6520///
6521/// \param From The expression we are copying from.
6522///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006523/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6524/// Otherwise, it's a non-static member subobject.
6525///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006526/// \param Depth Internal parameter recording the depth of the recursion.
6527///
6528/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006529static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006530BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006531 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006532 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006533 // C++0x [class.copy]p30:
6534 // Each subobject is assigned in the manner appropriate to its type:
6535 //
6536 // - if the subobject is of class type, the copy assignment operator
6537 // for the class is used (as if by explicit qualification; that is,
6538 // ignoring any possible virtual overriding functions in more derived
6539 // classes);
6540 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6542
6543 // Look for operator=.
6544 DeclarationName Name
6545 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6546 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6547 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6548
6549 // Filter out any result that isn't a copy-assignment operator.
6550 LookupResult::Filter F = OpLookup.makeFilter();
6551 while (F.hasNext()) {
6552 NamedDecl *D = F.next();
6553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6554 if (Method->isCopyAssignmentOperator())
6555 continue;
6556
6557 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006558 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006559 F.done();
6560
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006561 // Suppress the protected check (C++ [class.protected]) for each of the
6562 // assignment operators we found. This strange dance is required when
6563 // we're assigning via a base classes's copy-assignment operator. To
6564 // ensure that we're getting the right base class subobject (without
6565 // ambiguities), we need to cast "this" to that subobject type; to
6566 // ensure that we don't go through the virtual call mechanism, we need
6567 // to qualify the operator= name with the base class (see below). However,
6568 // this means that if the base class has a protected copy assignment
6569 // operator, the protected member access check will fail. So, we
6570 // rewrite "protected" access to "public" access in this case, since we
6571 // know by construction that we're calling from a derived class.
6572 if (CopyingBaseSubobject) {
6573 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6574 L != LEnd; ++L) {
6575 if (L.getAccess() == AS_protected)
6576 L.setAccess(AS_public);
6577 }
6578 }
6579
Douglas Gregorb139cd52010-05-01 20:49:11 +00006580 // Create the nested-name-specifier that will be used to qualify the
6581 // reference to operator=; this is required to suppress the virtual
6582 // call mechanism.
6583 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006584 SS.MakeTrivial(S.Context,
6585 NestedNameSpecifier::Create(S.Context, 0, false,
6586 T.getTypePtr()),
6587 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006588
6589 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006590 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006591 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006592 /*FirstQualifierInScope=*/0, OpLookup,
6593 /*TemplateArgs=*/0,
6594 /*SuppressQualifierCheck=*/true);
6595 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006596 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006597
6598 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006599
John McCalldadc5752010-08-24 06:29:42 +00006600 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006601 OpEqualRef.takeAs<Expr>(),
6602 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006603 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006604 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006605
6606 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006607 }
John McCallab8c2732010-03-16 06:11:48 +00006608
Douglas Gregorb139cd52010-05-01 20:49:11 +00006609 // - if the subobject is of scalar type, the built-in assignment
6610 // operator is used.
6611 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6612 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006613 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006614 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006615 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006616
6617 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006618 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006619
6620 // - if the subobject is an array, each element is assigned, in the
6621 // manner appropriate to the element type;
6622
6623 // Construct a loop over the array bounds, e.g.,
6624 //
6625 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6626 //
6627 // that will copy each of the array elements.
6628 QualType SizeType = S.Context.getSizeType();
6629
6630 // Create the iteration variable.
6631 IdentifierInfo *IterationVarName = 0;
6632 {
6633 llvm::SmallString<8> Str;
6634 llvm::raw_svector_ostream OS(Str);
6635 OS << "__i" << Depth;
6636 IterationVarName = &S.Context.Idents.get(OS.str());
6637 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006638 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006639 IterationVarName, SizeType,
6640 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006641 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006642
6643 // Initialize the iteration variable to zero.
6644 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006645 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006646
6647 // Create a reference to the iteration variable; we'll use this several
6648 // times throughout.
6649 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006650 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006651 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6652
6653 // Create the DeclStmt that holds the iteration variable.
6654 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6655
6656 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006657 llvm::APInt Upper
6658 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006659 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006660 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006661 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6662 BO_NE, S.Context.BoolTy,
6663 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006664
6665 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006666 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006667 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6668 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006669
6670 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006671 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6672 IterationVarRef, Loc));
6673 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6674 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006675
6676 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006677 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6678 To, From, CopyingBaseSubobject,
6679 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006680 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006681 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006682
6683 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006684 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006685 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006686 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006687 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006688}
6689
Alexis Huntb1b368f2011-06-10 12:07:09 +00006690/// \brief Determine whether the given class has a copy assignment operator
6691/// that accepts a const-qualified argument.
6692static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6693 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6694
6695 if (!Class->hasDeclaredCopyAssignment())
6696 S.DeclareImplicitCopyAssignment(Class);
6697
6698 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6699 DeclarationName OpName
6700 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6701
6702 DeclContext::lookup_const_iterator Op, OpEnd;
6703 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6704 // C++ [class.copy]p9:
6705 // A user-declared copy assignment operator is a non-static non-template
6706 // member function of class X with exactly one parameter of type X, X&,
6707 // const X&, volatile X& or const volatile X&.
6708 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6709 if (!Method)
6710 continue;
6711
6712 if (Method->isStatic())
6713 continue;
6714 if (Method->getPrimaryTemplate())
6715 continue;
6716 const FunctionProtoType *FnType =
6717 Method->getType()->getAs<FunctionProtoType>();
6718 assert(FnType && "Overloaded operator has no prototype.");
6719 // Don't assert on this; an invalid decl might have been left in the AST.
6720 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6721 continue;
6722 bool AcceptsConst = true;
6723 QualType ArgType = FnType->getArgType(0);
6724 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6725 ArgType = Ref->getPointeeType();
6726 // Is it a non-const lvalue reference?
6727 if (!ArgType.isConstQualified())
6728 AcceptsConst = false;
6729 }
6730 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6731 continue;
6732
6733 // We have a single argument of type cv X or cv X&, i.e. we've found the
6734 // copy assignment operator. Return whether it accepts const arguments.
6735 return AcceptsConst;
6736 }
6737 assert(Class->isInvalidDecl() &&
6738 "No copy assignment operator declared in valid code.");
6739 return false;
6740}
6741
Alexis Hunt119f3652011-05-14 05:23:20 +00006742std::pair<Sema::ImplicitExceptionSpecification, bool>
6743Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6744 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006745 // C++ [class.copy]p10:
6746 // If the class definition does not explicitly declare a copy
6747 // assignment operator, one is declared implicitly.
6748 // The implicitly-defined copy assignment operator for a class X
6749 // will have the form
6750 //
6751 // X& X::operator=(const X&)
6752 //
6753 // if
6754 bool HasConstCopyAssignment = true;
6755
6756 // -- each direct base class B of X has a copy assignment operator
6757 // whose parameter is of type const B&, const volatile B& or B,
6758 // and
6759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6760 BaseEnd = ClassDecl->bases_end();
6761 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6762 assert(!Base->getType()->isDependentType() &&
6763 "Cannot generate implicit members for class with dependent bases.");
Alexis Huntb1b368f2011-06-10 12:07:09 +00006764 const CXXRecordDecl *BaseClassDecl
6765 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6766 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006767 }
6768
6769 // -- for all the nonstatic data members of X that are of a class
6770 // type M (or array thereof), each such class type has a copy
6771 // assignment operator whose parameter is of type const M&,
6772 // const volatile M& or M.
6773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6774 FieldEnd = ClassDecl->field_end();
6775 HasConstCopyAssignment && Field != FieldEnd;
6776 ++Field) {
6777 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Huntb1b368f2011-06-10 12:07:09 +00006778 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6779 const CXXRecordDecl *FieldClassDecl
6780 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6781 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006782 }
6783 }
6784
6785 // Otherwise, the implicitly declared copy assignment operator will
6786 // have the form
6787 //
6788 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006789
Douglas Gregor68e11362010-07-01 17:48:08 +00006790 // C++ [except.spec]p14:
6791 // An implicitly declared special member function (Clause 12) shall have an
6792 // exception-specification. [...]
6793 ImplicitExceptionSpecification ExceptSpec(Context);
6794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6795 BaseEnd = ClassDecl->bases_end();
6796 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006797 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006798 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Huntb1b368f2011-06-10 12:07:09 +00006799
6800 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6801 DeclareImplicitCopyAssignment(BaseClassDecl);
6802
6803 if (CXXMethodDecl *CopyAssign
6804 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
Douglas Gregor68e11362010-07-01 17:48:08 +00006805 ExceptSpec.CalledDecl(CopyAssign);
6806 }
6807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6808 FieldEnd = ClassDecl->field_end();
6809 Field != FieldEnd;
6810 ++Field) {
6811 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Huntb1b368f2011-06-10 12:07:09 +00006812 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6813 CXXRecordDecl *FieldClassDecl
6814 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6815
6816 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6817 DeclareImplicitCopyAssignment(FieldClassDecl);
6818
6819 if (CXXMethodDecl *CopyAssign
6820 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6821 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00006822 }
6823 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006824
Alexis Hunt119f3652011-05-14 05:23:20 +00006825 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6826}
6827
6828CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6829 // Note: The following rules are largely analoguous to the copy
6830 // constructor rules. Note that virtual bases are not taken into account
6831 // for determining the argument type of the operator. Note also that
6832 // operators taking an object instead of a reference are allowed.
6833
6834 ImplicitExceptionSpecification Spec(Context);
6835 bool Const;
6836 llvm::tie(Spec, Const) =
6837 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6838
6839 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6840 QualType RetType = Context.getLValueReferenceType(ArgType);
6841 if (Const)
6842 ArgType = ArgType.withConst();
6843 ArgType = Context.getLValueReferenceType(ArgType);
6844
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006845 // An implicitly-declared copy assignment operator is an inline public
6846 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006847 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006848 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006849 SourceLocation ClassLoc = ClassDecl->getLocation();
6850 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006851 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006852 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006853 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006854 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006855 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006856 /*isInline=*/true,
6857 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006858 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006859 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006860 CopyAssignment->setImplicit();
6861 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006862
6863 // Add the parameter to the operator.
6864 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006865 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006866 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006867 SC_None,
6868 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006869 CopyAssignment->setParams(&FromParam, 1);
6870
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006871 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006872 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006873
Douglas Gregor0be31a22010-07-02 17:43:08 +00006874 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006875 PushOnScopeChains(CopyAssignment, S, false);
6876 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006877
Alexis Hunte77a28f2011-05-18 03:41:58 +00006878 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6879 CopyAssignment->setDeletedAsWritten();
6880
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006881 AddOverriddenMethods(ClassDecl, CopyAssignment);
6882 return CopyAssignment;
6883}
6884
Douglas Gregorb139cd52010-05-01 20:49:11 +00006885void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6886 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006887 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006888 CopyAssignOperator->isOverloadedOperator() &&
6889 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006890 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006891 "DefineImplicitCopyAssignment called for wrong function");
6892
6893 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6894
6895 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6896 CopyAssignOperator->setInvalidDecl();
6897 return;
6898 }
6899
6900 CopyAssignOperator->setUsed();
6901
6902 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006903 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006904
6905 // C++0x [class.copy]p30:
6906 // The implicitly-defined or explicitly-defaulted copy assignment operator
6907 // for a non-union class X performs memberwise copy assignment of its
6908 // subobjects. The direct base classes of X are assigned first, in the
6909 // order of their declaration in the base-specifier-list, and then the
6910 // immediate non-static data members of X are assigned, in the order in
6911 // which they were declared in the class definition.
6912
6913 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006914 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006915
6916 // The parameter for the "other" object, which we are copying from.
6917 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6918 Qualifiers OtherQuals = Other->getType().getQualifiers();
6919 QualType OtherRefType = Other->getType();
6920 if (const LValueReferenceType *OtherRef
6921 = OtherRefType->getAs<LValueReferenceType>()) {
6922 OtherRefType = OtherRef->getPointeeType();
6923 OtherQuals = OtherRefType.getQualifiers();
6924 }
6925
6926 // Our location for everything implicitly-generated.
6927 SourceLocation Loc = CopyAssignOperator->getLocation();
6928
6929 // Construct a reference to the "other" object. We'll be using this
6930 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006931 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006932 assert(OtherRef && "Reference to parameter cannot fail!");
6933
6934 // Construct the "this" pointer. We'll be using this throughout the generated
6935 // ASTs.
6936 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6937 assert(This && "Reference to this cannot fail!");
6938
6939 // Assign base classes.
6940 bool Invalid = false;
6941 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6942 E = ClassDecl->bases_end(); Base != E; ++Base) {
6943 // Form the assignment:
6944 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6945 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006946 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006947 Invalid = true;
6948 continue;
6949 }
6950
John McCallcf142162010-08-07 06:22:56 +00006951 CXXCastPath BasePath;
6952 BasePath.push_back(Base);
6953
Douglas Gregorb139cd52010-05-01 20:49:11 +00006954 // Construct the "from" expression, which is an implicit cast to the
6955 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006956 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006957 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6958 CK_UncheckedDerivedToBase,
6959 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006960
6961 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006962 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006963
6964 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006965 To = ImpCastExprToType(To.take(),
6966 Context.getCVRQualifiedType(BaseType,
6967 CopyAssignOperator->getTypeQualifiers()),
6968 CK_UncheckedDerivedToBase,
6969 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006970
6971 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006972 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006973 To.get(), From,
6974 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006975 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006976 Diag(CurrentLocation, diag::note_member_synthesized_at)
6977 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6978 CopyAssignOperator->setInvalidDecl();
6979 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006980 }
6981
6982 // Success! Record the copy.
6983 Statements.push_back(Copy.takeAs<Expr>());
6984 }
6985
6986 // \brief Reference to the __builtin_memcpy function.
6987 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006988 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006989 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006990
6991 // Assign non-static members.
6992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6993 FieldEnd = ClassDecl->field_end();
6994 Field != FieldEnd; ++Field) {
6995 // Check for members of reference type; we can't copy those.
6996 if (Field->getType()->isReferenceType()) {
6997 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6998 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6999 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007000 Diag(CurrentLocation, diag::note_member_synthesized_at)
7001 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007002 Invalid = true;
7003 continue;
7004 }
7005
7006 // Check for members of const-qualified, non-class type.
7007 QualType BaseType = Context.getBaseElementType(Field->getType());
7008 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7009 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7010 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7011 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007012 Diag(CurrentLocation, diag::note_member_synthesized_at)
7013 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007014 Invalid = true;
7015 continue;
7016 }
7017
7018 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007019 if (FieldType->isIncompleteArrayType()) {
7020 assert(ClassDecl->hasFlexibleArrayMember() &&
7021 "Incomplete array type is not valid");
7022 continue;
7023 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007024
7025 // Build references to the field in the object we're copying from and to.
7026 CXXScopeSpec SS; // Intentionally empty
7027 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7028 LookupMemberName);
7029 MemberLookup.addDecl(*Field);
7030 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00007031 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00007032 Loc, /*IsArrow=*/false,
7033 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00007034 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00007035 Loc, /*IsArrow=*/true,
7036 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007037 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7038 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7039
7040 // If the field should be copied with __builtin_memcpy rather than via
7041 // explicit assignments, do so. This optimization only applies for arrays
7042 // of scalars and arrays of class type with trivial copy-assignment
7043 // operators.
7044 if (FieldType->isArrayType() &&
7045 (!BaseType->isRecordType() ||
7046 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
7047 ->hasTrivialCopyAssignment())) {
7048 // Compute the size of the memory buffer to be copied.
7049 QualType SizeType = Context.getSizeType();
7050 llvm::APInt Size(Context.getTypeSize(SizeType),
7051 Context.getTypeSizeInChars(BaseType).getQuantity());
7052 for (const ConstantArrayType *Array
7053 = Context.getAsConstantArrayType(FieldType);
7054 Array;
7055 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00007056 llvm::APInt ArraySize
7057 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007058 Size *= ArraySize;
7059 }
7060
7061 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00007062 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7063 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007064
7065 bool NeedsCollectableMemCpy =
7066 (BaseType->isRecordType() &&
7067 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7068
7069 if (NeedsCollectableMemCpy) {
7070 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00007071 // Create a reference to the __builtin_objc_memmove_collectable function.
7072 LookupResult R(*this,
7073 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007074 Loc, LookupOrdinaryName);
7075 LookupName(R, TUScope, true);
7076
7077 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7078 if (!CollectableMemCpy) {
7079 // Something went horribly wrong earlier, and we will have
7080 // complained about it.
7081 Invalid = true;
7082 continue;
7083 }
7084
7085 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7086 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007087 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007088 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7089 }
7090 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007091 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007092 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007093 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7094 LookupOrdinaryName);
7095 LookupName(R, TUScope, true);
7096
7097 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7098 if (!BuiltinMemCpy) {
7099 // Something went horribly wrong earlier, and we will have complained
7100 // about it.
7101 Invalid = true;
7102 continue;
7103 }
7104
7105 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7106 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00007107 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007108 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7109 }
7110
John McCall37ad5512010-08-23 06:44:23 +00007111 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007112 CallArgs.push_back(To.takeAs<Expr>());
7113 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007114 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00007115 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007116 if (NeedsCollectableMemCpy)
7117 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007118 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007119 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007120 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007121 else
7122 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007123 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007124 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007125 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007126
Douglas Gregorb139cd52010-05-01 20:49:11 +00007127 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7128 Statements.push_back(Call.takeAs<Expr>());
7129 continue;
7130 }
7131
7132 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007133 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00007134 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007135 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007136 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007137 Diag(CurrentLocation, diag::note_member_synthesized_at)
7138 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7139 CopyAssignOperator->setInvalidDecl();
7140 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007141 }
7142
7143 // Success! Record the copy.
7144 Statements.push_back(Copy.takeAs<Stmt>());
7145 }
7146
7147 if (!Invalid) {
7148 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007149 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007150
John McCalldadc5752010-08-24 06:29:42 +00007151 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007152 if (Return.isInvalid())
7153 Invalid = true;
7154 else {
7155 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007156
7157 if (Trap.hasErrorOccurred()) {
7158 Diag(CurrentLocation, diag::note_member_synthesized_at)
7159 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7160 Invalid = true;
7161 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007162 }
7163 }
7164
7165 if (Invalid) {
7166 CopyAssignOperator->setInvalidDecl();
7167 return;
7168 }
7169
John McCalldadc5752010-08-24 06:29:42 +00007170 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007171 /*isStmtExpr=*/false);
7172 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7173 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007174
7175 if (ASTMutationListener *L = getASTMutationListener()) {
7176 L->CompletedImplicitDefinition(CopyAssignOperator);
7177 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007178}
7179
Alexis Hunt913820d2011-05-13 06:10:58 +00007180std::pair<Sema::ImplicitExceptionSpecification, bool>
7181Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007182 // C++ [class.copy]p5:
7183 // The implicitly-declared copy constructor for a class X will
7184 // have the form
7185 //
7186 // X::X(const X&)
7187 //
7188 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00007189 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00007190 bool HasConstCopyConstructor = true;
7191
7192 // -- each direct or virtual base class B of X has a copy
7193 // constructor whose first parameter is of type const B& or
7194 // const volatile B&, and
7195 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7196 BaseEnd = ClassDecl->bases_end();
7197 HasConstCopyConstructor && Base != BaseEnd;
7198 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007199 // Virtual bases are handled below.
7200 if (Base->isVirtual())
7201 continue;
7202
Douglas Gregora6d69502010-07-02 23:41:54 +00007203 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007204 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Huntb1b368f2011-06-10 12:07:09 +00007205 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7206 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00007207 }
7208
7209 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7210 BaseEnd = ClassDecl->vbases_end();
7211 HasConstCopyConstructor && Base != BaseEnd;
7212 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007213 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007214 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Huntb1b368f2011-06-10 12:07:09 +00007215 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7216 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007217 }
7218
7219 // -- for all the nonstatic data members of X that are of a
7220 // class type M (or array thereof), each such class type
7221 // has a copy constructor whose first parameter is of type
7222 // const M& or const volatile M&.
7223 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7224 FieldEnd = ClassDecl->field_end();
7225 HasConstCopyConstructor && Field != FieldEnd;
7226 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007227 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007228 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Huntb1b368f2011-06-10 12:07:09 +00007229 LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7230 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007231 }
7232 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007233 // Otherwise, the implicitly declared copy constructor will have
7234 // the form
7235 //
7236 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007237
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007238 // C++ [except.spec]p14:
7239 // An implicitly declared special member function (Clause 12) shall have an
7240 // exception-specification. [...]
7241 ImplicitExceptionSpecification ExceptSpec(Context);
7242 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7243 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7244 BaseEnd = ClassDecl->bases_end();
7245 Base != BaseEnd;
7246 ++Base) {
7247 // Virtual bases are handled below.
7248 if (Base->isVirtual())
7249 continue;
7250
Douglas Gregora6d69502010-07-02 23:41:54 +00007251 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007252 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007253 if (CXXConstructorDecl *CopyConstructor =
Alexis Huntb1b368f2011-06-10 12:07:09 +00007254 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007255 ExceptSpec.CalledDecl(CopyConstructor);
7256 }
7257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7258 BaseEnd = ClassDecl->vbases_end();
7259 Base != BaseEnd;
7260 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007261 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007262 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007263 if (CXXConstructorDecl *CopyConstructor =
Alexis Huntb1b368f2011-06-10 12:07:09 +00007264 LookupCopyConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007265 ExceptSpec.CalledDecl(CopyConstructor);
7266 }
7267 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7268 FieldEnd = ClassDecl->field_end();
7269 Field != FieldEnd;
7270 ++Field) {
7271 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007272 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7273 if (CXXConstructorDecl *CopyConstructor =
Alexis Huntb1b368f2011-06-10 12:07:09 +00007274 LookupCopyConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00007275 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007276 }
7277 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007278
Alexis Hunt913820d2011-05-13 06:10:58 +00007279 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7280}
7281
7282CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7283 CXXRecordDecl *ClassDecl) {
7284 // C++ [class.copy]p4:
7285 // If the class definition does not explicitly declare a copy
7286 // constructor, one is declared implicitly.
7287
7288 ImplicitExceptionSpecification Spec(Context);
7289 bool Const;
7290 llvm::tie(Spec, Const) =
7291 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7292
7293 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7294 QualType ArgType = ClassType;
7295 if (Const)
7296 ArgType = ArgType.withConst();
7297 ArgType = Context.getLValueReferenceType(ArgType);
7298
7299 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7300
Douglas Gregor54be3392010-07-01 17:57:27 +00007301 DeclarationName Name
7302 = Context.DeclarationNames.getCXXConstructorName(
7303 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007304 SourceLocation ClassLoc = ClassDecl->getLocation();
7305 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007306
7307 // An implicitly-declared copy constructor is an inline public
7308 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007309 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007310 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007311 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007312 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007313 /*TInfo=*/0,
7314 /*isExplicit=*/false,
7315 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007316 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007317 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007318 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007319 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7320
Douglas Gregora6d69502010-07-02 23:41:54 +00007321 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007322 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7323
Douglas Gregor54be3392010-07-01 17:57:27 +00007324 // Add the parameter to the constructor.
7325 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007326 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007327 /*IdentifierInfo=*/0,
7328 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007329 SC_None,
7330 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007331 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007332
Douglas Gregor0be31a22010-07-02 17:43:08 +00007333 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007334 PushOnScopeChains(CopyConstructor, S, false);
7335 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007336
7337 if (ShouldDeleteCopyConstructor(CopyConstructor))
7338 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007339
7340 return CopyConstructor;
7341}
7342
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007343void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007344 CXXConstructorDecl *CopyConstructor) {
7345 assert((CopyConstructor->isDefaulted() &&
7346 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007347 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007348 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007349
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007350 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007351 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007352
Douglas Gregora57478e2010-05-01 15:04:51 +00007353 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007354 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007355
Alexis Hunt1d792652011-01-08 20:30:50 +00007356 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007357 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007358 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007359 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007360 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007361 } else {
7362 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7363 CopyConstructor->getLocation(),
7364 MultiStmtArg(*this, 0, 0),
7365 /*isStmtExpr=*/false)
7366 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007367 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007368
7369 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007370
7371 if (ASTMutationListener *L = getASTMutationListener()) {
7372 L->CompletedImplicitDefinition(CopyConstructor);
7373 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007374}
7375
John McCalldadc5752010-08-24 06:29:42 +00007376ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007377Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007378 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007379 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007380 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007381 unsigned ConstructKind,
7382 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007383 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007384
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007385 // C++0x [class.copy]p34:
7386 // When certain criteria are met, an implementation is allowed to
7387 // omit the copy/move construction of a class object, even if the
7388 // copy/move constructor and/or destructor for the object have
7389 // side effects. [...]
7390 // - when a temporary class object that has not been bound to a
7391 // reference (12.2) would be copied/moved to a class object
7392 // with the same cv-unqualified type, the copy/move operation
7393 // can be omitted by constructing the temporary object
7394 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007395 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007396 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007397 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007398 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007399 }
Mike Stump11289f42009-09-09 15:08:12 +00007400
7401 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007402 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007403 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007404}
7405
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007406/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7407/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007408ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007409Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7410 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007411 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007412 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007413 unsigned ConstructKind,
7414 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007415 unsigned NumExprs = ExprArgs.size();
7416 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007417
Nick Lewyckyd4693212011-03-25 01:44:32 +00007418 for (specific_attr_iterator<NonNullAttr>
7419 i = Constructor->specific_attr_begin<NonNullAttr>(),
7420 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7421 const NonNullAttr *NonNull = *i;
7422 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7423 }
7424
Douglas Gregor27381f32009-11-23 12:27:39 +00007425 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007426 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007427 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007428 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007429 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7430 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007431}
7432
Mike Stump11289f42009-09-09 15:08:12 +00007433bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007434 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007435 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007436 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007437 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007438 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007439 move(Exprs), false, CXXConstructExpr::CK_Complete,
7440 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007441 if (TempResult.isInvalid())
7442 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007443
Anders Carlsson6eb55572009-08-25 05:12:04 +00007444 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007445 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007446 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007447 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007448 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007449
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007450 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007451}
7452
John McCall03c48482010-02-02 09:10:11 +00007453void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007454 if (VD->isInvalidDecl()) return;
7455
John McCall03c48482010-02-02 09:10:11 +00007456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007457 if (ClassDecl->isInvalidDecl()) return;
7458 if (ClassDecl->hasTrivialDestructor()) return;
7459 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007460
Chandler Carruth86d17d32011-03-27 21:26:48 +00007461 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7462 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7463 CheckDestructorAccess(VD->getLocation(), Destructor,
7464 PDiag(diag::err_access_dtor_var)
7465 << VD->getDeclName()
7466 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007467
Chandler Carruth86d17d32011-03-27 21:26:48 +00007468 if (!VD->hasGlobalStorage()) return;
7469
7470 // Emit warning for non-trivial dtor in global scope (a real global,
7471 // class-static, function-static).
7472 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7473
7474 // TODO: this should be re-enabled for static locals by !CXAAtExit
7475 if (!VD->isStaticLocal())
7476 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007477}
7478
Mike Stump11289f42009-09-09 15:08:12 +00007479/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007480/// ActOnDeclarator, when a C++ direct initializer is present.
7481/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007482void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007483 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007484 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007485 SourceLocation RParenLoc,
7486 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007487 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007488
7489 // If there is no declaration, there was an error parsing it. Just ignore
7490 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007491 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007492 return;
Mike Stump11289f42009-09-09 15:08:12 +00007493
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007494 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7495 if (!VDecl) {
7496 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7497 RealDecl->setInvalidDecl();
7498 return;
7499 }
7500
Richard Smith30482bc2011-02-20 03:19:35 +00007501 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7502 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007503 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7504 if (Exprs.size() > 1) {
7505 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7506 diag::err_auto_var_init_multiple_expressions)
7507 << VDecl->getDeclName() << VDecl->getType()
7508 << VDecl->getSourceRange();
7509 RealDecl->setInvalidDecl();
7510 return;
7511 }
7512
7513 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007514 TypeSourceInfo *DeducedType = 0;
7515 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007516 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7517 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7518 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007519 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007520 RealDecl->setInvalidDecl();
7521 return;
7522 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007523 VDecl->setTypeSourceInfo(DeducedType);
7524 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007525
7526 // If this is a redeclaration, check that the type we just deduced matches
7527 // the previously declared type.
7528 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7529 MergeVarDeclTypes(VDecl, Old);
7530 }
7531
Douglas Gregor402250f2009-08-26 21:14:46 +00007532 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007533 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007534 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7535 //
7536 // Clients that want to distinguish between the two forms, can check for
7537 // direct initializer using VarDecl::hasCXXDirectInitializer().
7538 // A major benefit is that clients that don't particularly care about which
7539 // exactly form was it (like the CodeGen) can handle both cases without
7540 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007541
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007542 // C++ 8.5p11:
7543 // The form of initialization (using parentheses or '=') is generally
7544 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007545 // class type.
7546
Douglas Gregor50dc2192010-02-11 22:55:30 +00007547 if (!VDecl->getType()->isDependentType() &&
7548 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007549 diag::err_typecheck_decl_incomplete_type)) {
7550 VDecl->setInvalidDecl();
7551 return;
7552 }
7553
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007554 // The variable can not have an abstract class type.
7555 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7556 diag::err_abstract_type_in_decl,
7557 AbstractVariableType))
7558 VDecl->setInvalidDecl();
7559
Sebastian Redl5ca79842010-02-01 20:16:42 +00007560 const VarDecl *Def;
7561 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007562 Diag(VDecl->getLocation(), diag::err_redefinition)
7563 << VDecl->getDeclName();
7564 Diag(Def->getLocation(), diag::note_previous_definition);
7565 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007566 return;
7567 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007568
Douglas Gregorf0f83692010-08-24 05:27:49 +00007569 // C++ [class.static.data]p4
7570 // If a static data member is of const integral or const
7571 // enumeration type, its declaration in the class definition can
7572 // specify a constant-initializer which shall be an integral
7573 // constant expression (5.19). In that case, the member can appear
7574 // in integral constant expressions. The member shall still be
7575 // defined in a namespace scope if it is used in the program and the
7576 // namespace scope definition shall not contain an initializer.
7577 //
7578 // We already performed a redefinition check above, but for static
7579 // data members we also need to check whether there was an in-class
7580 // declaration with an initializer.
7581 const VarDecl* PrevInit = 0;
7582 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7583 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7584 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7585 return;
7586 }
7587
Douglas Gregor71f39c92010-12-16 01:31:22 +00007588 bool IsDependent = false;
7589 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7590 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7591 VDecl->setInvalidDecl();
7592 return;
7593 }
7594
7595 if (Exprs.get()[I]->isTypeDependent())
7596 IsDependent = true;
7597 }
7598
Douglas Gregor50dc2192010-02-11 22:55:30 +00007599 // If either the declaration has a dependent type or if any of the
7600 // expressions is type-dependent, we represent the initialization
7601 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007602 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007603 // Let clients know that initialization was done with a direct initializer.
7604 VDecl->setCXXDirectInitializer(true);
7605
7606 // Store the initialization expressions as a ParenListExpr.
7607 unsigned NumExprs = Exprs.size();
7608 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7609 (Expr **)Exprs.release(),
7610 NumExprs, RParenLoc));
7611 return;
7612 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007613
7614 // Capture the variable that is being initialized and the style of
7615 // initialization.
7616 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7617
7618 // FIXME: Poor source location information.
7619 InitializationKind Kind
7620 = InitializationKind::CreateDirect(VDecl->getLocation(),
7621 LParenLoc, RParenLoc);
7622
7623 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007624 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007625 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007626 if (Result.isInvalid()) {
7627 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007628 return;
7629 }
John McCallacf0ee52010-10-08 02:01:28 +00007630
7631 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007632
Douglas Gregora40433a2010-12-07 00:41:46 +00007633 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007634 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007635 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007636
John McCall8b7fd8f12011-01-19 11:48:09 +00007637 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007638}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007639
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007640/// \brief Given a constructor and the set of arguments provided for the
7641/// constructor, convert the arguments and add any required default arguments
7642/// to form a proper call to this constructor.
7643///
7644/// \returns true if an error occurred, false otherwise.
7645bool
7646Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7647 MultiExprArg ArgsPtr,
7648 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007649 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007650 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7651 unsigned NumArgs = ArgsPtr.size();
7652 Expr **Args = (Expr **)ArgsPtr.get();
7653
7654 const FunctionProtoType *Proto
7655 = Constructor->getType()->getAs<FunctionProtoType>();
7656 assert(Proto && "Constructor without a prototype?");
7657 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007658
7659 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007660 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007661 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007662 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007663 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007664
7665 VariadicCallType CallType =
7666 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7667 llvm::SmallVector<Expr *, 8> AllArgs;
7668 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7669 Proto, 0, Args, NumArgs, AllArgs,
7670 CallType);
7671 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7672 ConvertedArgs.push_back(AllArgs[i]);
7673 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007674}
7675
Anders Carlssone363c8e2009-12-12 00:32:00 +00007676static inline bool
7677CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7678 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007679 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007680 if (isa<NamespaceDecl>(DC)) {
7681 return SemaRef.Diag(FnDecl->getLocation(),
7682 diag::err_operator_new_delete_declared_in_namespace)
7683 << FnDecl->getDeclName();
7684 }
7685
7686 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007687 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007688 return SemaRef.Diag(FnDecl->getLocation(),
7689 diag::err_operator_new_delete_declared_static)
7690 << FnDecl->getDeclName();
7691 }
7692
Anders Carlsson60659a82009-12-12 02:43:16 +00007693 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007694}
7695
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007696static inline bool
7697CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7698 CanQualType ExpectedResultType,
7699 CanQualType ExpectedFirstParamType,
7700 unsigned DependentParamTypeDiag,
7701 unsigned InvalidParamTypeDiag) {
7702 QualType ResultType =
7703 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7704
7705 // Check that the result type is not dependent.
7706 if (ResultType->isDependentType())
7707 return SemaRef.Diag(FnDecl->getLocation(),
7708 diag::err_operator_new_delete_dependent_result_type)
7709 << FnDecl->getDeclName() << ExpectedResultType;
7710
7711 // Check that the result type is what we expect.
7712 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7713 return SemaRef.Diag(FnDecl->getLocation(),
7714 diag::err_operator_new_delete_invalid_result_type)
7715 << FnDecl->getDeclName() << ExpectedResultType;
7716
7717 // A function template must have at least 2 parameters.
7718 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7719 return SemaRef.Diag(FnDecl->getLocation(),
7720 diag::err_operator_new_delete_template_too_few_parameters)
7721 << FnDecl->getDeclName();
7722
7723 // The function decl must have at least 1 parameter.
7724 if (FnDecl->getNumParams() == 0)
7725 return SemaRef.Diag(FnDecl->getLocation(),
7726 diag::err_operator_new_delete_too_few_parameters)
7727 << FnDecl->getDeclName();
7728
7729 // Check the the first parameter type is not dependent.
7730 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7731 if (FirstParamType->isDependentType())
7732 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7733 << FnDecl->getDeclName() << ExpectedFirstParamType;
7734
7735 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007736 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007737 ExpectedFirstParamType)
7738 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7739 << FnDecl->getDeclName() << ExpectedFirstParamType;
7740
7741 return false;
7742}
7743
Anders Carlsson12308f42009-12-11 23:23:22 +00007744static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007745CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007746 // C++ [basic.stc.dynamic.allocation]p1:
7747 // A program is ill-formed if an allocation function is declared in a
7748 // namespace scope other than global scope or declared static in global
7749 // scope.
7750 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7751 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007752
7753 CanQualType SizeTy =
7754 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7755
7756 // C++ [basic.stc.dynamic.allocation]p1:
7757 // The return type shall be void*. The first parameter shall have type
7758 // std::size_t.
7759 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7760 SizeTy,
7761 diag::err_operator_new_dependent_param_type,
7762 diag::err_operator_new_param_type))
7763 return true;
7764
7765 // C++ [basic.stc.dynamic.allocation]p1:
7766 // The first parameter shall not have an associated default argument.
7767 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007768 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007769 diag::err_operator_new_default_arg)
7770 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7771
7772 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007773}
7774
7775static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007776CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7777 // C++ [basic.stc.dynamic.deallocation]p1:
7778 // A program is ill-formed if deallocation functions are declared in a
7779 // namespace scope other than global scope or declared static in global
7780 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007781 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7782 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007783
7784 // C++ [basic.stc.dynamic.deallocation]p2:
7785 // Each deallocation function shall return void and its first parameter
7786 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007787 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7788 SemaRef.Context.VoidPtrTy,
7789 diag::err_operator_delete_dependent_param_type,
7790 diag::err_operator_delete_param_type))
7791 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007792
Anders Carlsson12308f42009-12-11 23:23:22 +00007793 return false;
7794}
7795
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007796/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7797/// of this overloaded operator is well-formed. If so, returns false;
7798/// otherwise, emits appropriate diagnostics and returns true.
7799bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007800 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007801 "Expected an overloaded operator declaration");
7802
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007803 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7804
Mike Stump11289f42009-09-09 15:08:12 +00007805 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007806 // The allocation and deallocation functions, operator new,
7807 // operator new[], operator delete and operator delete[], are
7808 // described completely in 3.7.3. The attributes and restrictions
7809 // found in the rest of this subclause do not apply to them unless
7810 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007811 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007812 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007813
Anders Carlsson22f443f2009-12-12 00:26:23 +00007814 if (Op == OO_New || Op == OO_Array_New)
7815 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007816
7817 // C++ [over.oper]p6:
7818 // An operator function shall either be a non-static member
7819 // function or be a non-member function and have at least one
7820 // parameter whose type is a class, a reference to a class, an
7821 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007822 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7823 if (MethodDecl->isStatic())
7824 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007825 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007826 } else {
7827 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007828 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7829 ParamEnd = FnDecl->param_end();
7830 Param != ParamEnd; ++Param) {
7831 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007832 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7833 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007834 ClassOrEnumParam = true;
7835 break;
7836 }
7837 }
7838
Douglas Gregord69246b2008-11-17 16:14:12 +00007839 if (!ClassOrEnumParam)
7840 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007841 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007842 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007843 }
7844
7845 // C++ [over.oper]p8:
7846 // An operator function cannot have default arguments (8.3.6),
7847 // except where explicitly stated below.
7848 //
Mike Stump11289f42009-09-09 15:08:12 +00007849 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007850 // (C++ [over.call]p1).
7851 if (Op != OO_Call) {
7852 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7853 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007854 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007855 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007856 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007857 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007858 }
7859 }
7860
Douglas Gregor6cf08062008-11-10 13:38:07 +00007861 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7862 { false, false, false }
7863#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7864 , { Unary, Binary, MemberOnly }
7865#include "clang/Basic/OperatorKinds.def"
7866 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007867
Douglas Gregor6cf08062008-11-10 13:38:07 +00007868 bool CanBeUnaryOperator = OperatorUses[Op][0];
7869 bool CanBeBinaryOperator = OperatorUses[Op][1];
7870 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007871
7872 // C++ [over.oper]p8:
7873 // [...] Operator functions cannot have more or fewer parameters
7874 // than the number required for the corresponding operator, as
7875 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007876 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007877 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007878 if (Op != OO_Call &&
7879 ((NumParams == 1 && !CanBeUnaryOperator) ||
7880 (NumParams == 2 && !CanBeBinaryOperator) ||
7881 (NumParams < 1) || (NumParams > 2))) {
7882 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007883 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007884 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007885 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007886 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007887 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007888 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007889 assert(CanBeBinaryOperator &&
7890 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007891 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007892 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007893
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007895 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007896 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007897
Douglas Gregord69246b2008-11-17 16:14:12 +00007898 // Overloaded operators other than operator() cannot be variadic.
7899 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007900 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007901 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007902 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007903 }
7904
7905 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007906 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7907 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007908 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007909 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007910 }
7911
7912 // C++ [over.inc]p1:
7913 // The user-defined function called operator++ implements the
7914 // prefix and postfix ++ operator. If this function is a member
7915 // function with no parameters, or a non-member function with one
7916 // parameter of class or enumeration type, it defines the prefix
7917 // increment operator ++ for objects of that type. If the function
7918 // is a member function with one parameter (which shall be of type
7919 // int) or a non-member function with two parameters (the second
7920 // of which shall be of type int), it defines the postfix
7921 // increment operator ++ for objects of that type.
7922 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7923 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7924 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007925 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007926 ParamIsInt = BT->getKind() == BuiltinType::Int;
7927
Chris Lattner2b786902008-11-21 07:50:02 +00007928 if (!ParamIsInt)
7929 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007930 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007931 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007932 }
7933
Douglas Gregord69246b2008-11-17 16:14:12 +00007934 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007935}
Chris Lattner3b024a32008-12-17 07:09:26 +00007936
Alexis Huntc88db062010-01-13 09:01:02 +00007937/// CheckLiteralOperatorDeclaration - Check whether the declaration
7938/// of this literal operator function is well-formed. If so, returns
7939/// false; otherwise, emits appropriate diagnostics and returns true.
7940bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7941 DeclContext *DC = FnDecl->getDeclContext();
7942 Decl::Kind Kind = DC->getDeclKind();
7943 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7944 Kind != Decl::LinkageSpec) {
7945 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7946 << FnDecl->getDeclName();
7947 return true;
7948 }
7949
7950 bool Valid = false;
7951
Alexis Hunt7dd26172010-04-07 23:11:06 +00007952 // template <char...> type operator "" name() is the only valid template
7953 // signature, and the only valid signature with no parameters.
7954 if (FnDecl->param_size() == 0) {
7955 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7956 // Must have only one template parameter
7957 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7958 if (Params->size() == 1) {
7959 NonTypeTemplateParmDecl *PmDecl =
7960 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007961
Alexis Hunt7dd26172010-04-07 23:11:06 +00007962 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007963 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7964 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7965 Valid = true;
7966 }
7967 }
7968 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007969 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007970 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7971
Alexis Huntc88db062010-01-13 09:01:02 +00007972 QualType T = (*Param)->getType();
7973
Alexis Hunt079a6f72010-04-07 22:57:35 +00007974 // unsigned long long int, long double, and any character type are allowed
7975 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007976 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7977 Context.hasSameType(T, Context.LongDoubleTy) ||
7978 Context.hasSameType(T, Context.CharTy) ||
7979 Context.hasSameType(T, Context.WCharTy) ||
7980 Context.hasSameType(T, Context.Char16Ty) ||
7981 Context.hasSameType(T, Context.Char32Ty)) {
7982 if (++Param == FnDecl->param_end())
7983 Valid = true;
7984 goto FinishedParams;
7985 }
7986
Alexis Hunt079a6f72010-04-07 22:57:35 +00007987 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007988 const PointerType *PT = T->getAs<PointerType>();
7989 if (!PT)
7990 goto FinishedParams;
7991 T = PT->getPointeeType();
7992 if (!T.isConstQualified())
7993 goto FinishedParams;
7994 T = T.getUnqualifiedType();
7995
7996 // Move on to the second parameter;
7997 ++Param;
7998
7999 // If there is no second parameter, the first must be a const char *
8000 if (Param == FnDecl->param_end()) {
8001 if (Context.hasSameType(T, Context.CharTy))
8002 Valid = true;
8003 goto FinishedParams;
8004 }
8005
8006 // const char *, const wchar_t*, const char16_t*, and const char32_t*
8007 // are allowed as the first parameter to a two-parameter function
8008 if (!(Context.hasSameType(T, Context.CharTy) ||
8009 Context.hasSameType(T, Context.WCharTy) ||
8010 Context.hasSameType(T, Context.Char16Ty) ||
8011 Context.hasSameType(T, Context.Char32Ty)))
8012 goto FinishedParams;
8013
8014 // The second and final parameter must be an std::size_t
8015 T = (*Param)->getType().getUnqualifiedType();
8016 if (Context.hasSameType(T, Context.getSizeType()) &&
8017 ++Param == FnDecl->param_end())
8018 Valid = true;
8019 }
8020
8021 // FIXME: This diagnostic is absolutely terrible.
8022FinishedParams:
8023 if (!Valid) {
8024 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8025 << FnDecl->getDeclName();
8026 return true;
8027 }
8028
8029 return false;
8030}
8031
Douglas Gregor07665a62009-01-05 19:45:36 +00008032/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8033/// linkage specification, including the language and (if present)
8034/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8035/// the location of the language string literal, which is provided
8036/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8037/// the '{' brace. Otherwise, this linkage specification does not
8038/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00008039Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8040 SourceLocation LangLoc,
8041 llvm::StringRef Lang,
8042 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00008043 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00008044 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00008045 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00008046 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00008047 Language = LinkageSpecDecl::lang_cxx;
8048 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00008049 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00008050 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00008051 }
Mike Stump11289f42009-09-09 15:08:12 +00008052
Chris Lattner438e5012008-12-17 07:13:27 +00008053 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00008054
Douglas Gregor07665a62009-01-05 19:45:36 +00008055 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008056 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008057 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00008058 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00008059 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00008060}
8061
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00008062/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00008063/// the C++ linkage specification LinkageSpec. If RBraceLoc is
8064/// valid, it's the position of the closing '}' brace in a linkage
8065/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00008066Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00008067 Decl *LinkageSpec,
8068 SourceLocation RBraceLoc) {
8069 if (LinkageSpec) {
8070 if (RBraceLoc.isValid()) {
8071 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8072 LSDecl->setRBraceLoc(RBraceLoc);
8073 }
Douglas Gregor07665a62009-01-05 19:45:36 +00008074 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00008075 }
Douglas Gregor07665a62009-01-05 19:45:36 +00008076 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00008077}
8078
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008079/// \brief Perform semantic analysis for the variable declaration that
8080/// occurs within a C++ catch clause, returning the newly-created
8081/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00008082VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00008083 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008084 SourceLocation StartLoc,
8085 SourceLocation Loc,
8086 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008087 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008088 QualType ExDeclType = TInfo->getType();
8089
Sebastian Redl54c04d42008-12-22 19:15:10 +00008090 // Arrays and functions decay.
8091 if (ExDeclType->isArrayType())
8092 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8093 else if (ExDeclType->isFunctionType())
8094 ExDeclType = Context.getPointerType(ExDeclType);
8095
8096 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8097 // The exception-declaration shall not denote a pointer or reference to an
8098 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00008099 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00008100 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008101 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00008102 Invalid = true;
8103 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008104
Douglas Gregor104ee002010-03-08 01:47:36 +00008105 // GCC allows catching pointers and references to incomplete types
8106 // as an extension; so do we, but we warn by default.
8107
Sebastian Redl54c04d42008-12-22 19:15:10 +00008108 QualType BaseType = ExDeclType;
8109 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00008110 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00008111 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008112 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008113 BaseType = Ptr->getPointeeType();
8114 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00008115 DK = diag::ext_catch_incomplete_ptr;
8116 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00008117 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00008118 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008119 BaseType = Ref->getPointeeType();
8120 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00008121 DK = diag::ext_catch_incomplete_ref;
8122 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008123 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00008124 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008125 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8126 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008127 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008128
Mike Stump11289f42009-09-09 15:08:12 +00008129 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008130 RequireNonAbstractType(Loc, ExDeclType,
8131 diag::err_abstract_type_in_decl,
8132 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008133 Invalid = true;
8134
John McCall2ca705e2010-07-24 00:37:23 +00008135 // Only the non-fragile NeXT runtime currently supports C++ catches
8136 // of ObjC types, and no runtime supports catching ObjC types by value.
8137 if (!Invalid && getLangOptions().ObjC1) {
8138 QualType T = ExDeclType;
8139 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8140 T = RT->getPointeeType();
8141
8142 if (T->isObjCObjectType()) {
8143 Diag(Loc, diag::err_objc_object_catch);
8144 Invalid = true;
8145 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00008146 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00008147 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8148 Invalid = true;
8149 }
8150 }
8151 }
8152
Abramo Bagnaradff19302011-03-08 08:55:46 +00008153 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8154 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008155 ExDecl->setExceptionVariable(true);
8156
Douglas Gregor6de584c2010-03-05 23:38:39 +00008157 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008158 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008159 // C++ [except.handle]p16:
8160 // The object declared in an exception-declaration or, if the
8161 // exception-declaration does not specify a name, a temporary (12.2) is
8162 // copy-initialized (8.5) from the exception object. [...]
8163 // The object is destroyed when the handler exits, after the destruction
8164 // of any automatic objects initialized within the handler.
8165 //
8166 // We just pretend to initialize the object with itself, then make sure
8167 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008168 QualType initType = ExDeclType;
8169
8170 InitializedEntity entity =
8171 InitializedEntity::InitializeVariable(ExDecl);
8172 InitializationKind initKind =
8173 InitializationKind::CreateCopy(Loc, SourceLocation());
8174
8175 Expr *opaqueValue =
8176 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8177 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8178 ExprResult result = sequence.Perform(*this, entity, initKind,
8179 MultiExprArg(&opaqueValue, 1));
8180 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008181 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008182 else {
8183 // If the constructor used was non-trivial, set this as the
8184 // "initializer".
8185 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8186 if (!construct->getConstructor()->isTrivial()) {
8187 Expr *init = MaybeCreateExprWithCleanups(construct);
8188 ExDecl->setInit(init);
8189 }
8190
8191 // And make sure it's destructable.
8192 FinalizeVarWithDestructor(ExDecl, recordType);
8193 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008194 }
8195 }
8196
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008197 if (Invalid)
8198 ExDecl->setInvalidDecl();
8199
8200 return ExDecl;
8201}
8202
8203/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8204/// handler.
John McCall48871652010-08-21 09:40:31 +00008205Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008207 bool Invalid = D.isInvalidType();
8208
8209 // Check for unexpanded parameter packs.
8210 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8211 UPPC_ExceptionType)) {
8212 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8213 D.getIdentifierLoc());
8214 Invalid = true;
8215 }
8216
Sebastian Redl54c04d42008-12-22 19:15:10 +00008217 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008218 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008219 LookupOrdinaryName,
8220 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008221 // The scope should be freshly made just for us. There is just no way
8222 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008223 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008224 if (PrevDecl->isTemplateParameter()) {
8225 // Maybe we will complain about the shadowed template parameter.
8226 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008227 }
8228 }
8229
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008230 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008231 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8232 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008233 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008234 }
8235
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008236 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008237 D.getSourceRange().getBegin(),
8238 D.getIdentifierLoc(),
8239 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008240 if (Invalid)
8241 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008242
Sebastian Redl54c04d42008-12-22 19:15:10 +00008243 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008244 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008245 PushOnScopeChains(ExDecl, S);
8246 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008247 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008248
Douglas Gregor758a8692009-06-17 21:51:59 +00008249 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008250 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008251}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008252
Abramo Bagnaraea947882011-03-08 16:41:52 +00008253Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008254 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008255 Expr *AssertMessageExpr_,
8256 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008257 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008258
Anders Carlsson54b26982009-03-14 00:33:21 +00008259 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8260 llvm::APSInt Value(32);
8261 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008262 Diag(StaticAssertLoc,
8263 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008264 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008265 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008266 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008267
Anders Carlsson54b26982009-03-14 00:33:21 +00008268 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008269 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008270 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008271 }
8272 }
Mike Stump11289f42009-09-09 15:08:12 +00008273
Douglas Gregoref68fee2010-12-15 23:55:21 +00008274 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8275 return 0;
8276
Abramo Bagnaraea947882011-03-08 16:41:52 +00008277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8278 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008279
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008280 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008281 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008282}
Sebastian Redlf769df52009-03-24 22:27:57 +00008283
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008284/// \brief Perform semantic analysis of the given friend type declaration.
8285///
8286/// \returns A friend declaration that.
8287FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8288 TypeSourceInfo *TSInfo) {
8289 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8290
8291 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008292 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008293
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008294 if (!getLangOptions().CPlusPlus0x) {
8295 // C++03 [class.friend]p2:
8296 // An elaborated-type-specifier shall be used in a friend declaration
8297 // for a class.*
8298 //
8299 // * The class-key of the elaborated-type-specifier is required.
8300 if (!ActiveTemplateInstantiations.empty()) {
8301 // Do not complain about the form of friend template types during
8302 // template instantiation; we will already have complained when the
8303 // template was declared.
8304 } else if (!T->isElaboratedTypeSpecifier()) {
8305 // If we evaluated the type to a record type, suggest putting
8306 // a tag in front.
8307 if (const RecordType *RT = T->getAs<RecordType>()) {
8308 RecordDecl *RD = RT->getDecl();
8309
8310 std::string InsertionText = std::string(" ") + RD->getKindName();
8311
8312 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8313 << (unsigned) RD->getTagKind()
8314 << T
8315 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8316 InsertionText);
8317 } else {
8318 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8319 << T
8320 << SourceRange(FriendLoc, TypeRange.getEnd());
8321 }
8322 } else if (T->getAs<EnumType>()) {
8323 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008324 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008325 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008326 }
8327 }
8328
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008329 // C++0x [class.friend]p3:
8330 // If the type specifier in a friend declaration designates a (possibly
8331 // cv-qualified) class type, that class is declared as a friend; otherwise,
8332 // the friend declaration is ignored.
8333
8334 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8335 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008336
8337 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8338}
8339
John McCallace48cd2010-10-19 01:40:49 +00008340/// Handle a friend tag declaration where the scope specifier was
8341/// templated.
8342Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8343 unsigned TagSpec, SourceLocation TagLoc,
8344 CXXScopeSpec &SS,
8345 IdentifierInfo *Name, SourceLocation NameLoc,
8346 AttributeList *Attr,
8347 MultiTemplateParamsArg TempParamLists) {
8348 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8349
8350 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008351 bool Invalid = false;
8352
8353 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008354 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008355 TempParamLists.get(),
8356 TempParamLists.size(),
8357 /*friend*/ true,
8358 isExplicitSpecialization,
8359 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008360 if (TemplateParams->size() > 0) {
8361 // This is a declaration of a class template.
8362 if (Invalid)
8363 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008364
John McCallace48cd2010-10-19 01:40:49 +00008365 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8366 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008367 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008368 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008369 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008370 } else {
8371 // The "template<>" header is extraneous.
8372 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8373 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8374 isExplicitSpecialization = true;
8375 }
8376 }
8377
8378 if (Invalid) return 0;
8379
8380 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8381
8382 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008383 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008384 if (TempParamLists.get()[I]->size()) {
8385 isAllExplicitSpecializations = false;
8386 break;
8387 }
8388 }
8389
8390 // FIXME: don't ignore attributes.
8391
8392 // If it's explicit specializations all the way down, just forget
8393 // about the template header and build an appropriate non-templated
8394 // friend. TODO: for source fidelity, remember the headers.
8395 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008396 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008397 ElaboratedTypeKeyword Keyword
8398 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008399 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008400 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008401 if (T.isNull())
8402 return 0;
8403
8404 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8405 if (isa<DependentNameType>(T)) {
8406 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8407 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008408 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008409 TL.setNameLoc(NameLoc);
8410 } else {
8411 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8412 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008413 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008414 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8415 }
8416
8417 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8418 TSI, FriendLoc);
8419 Friend->setAccess(AS_public);
8420 CurContext->addDecl(Friend);
8421 return Friend;
8422 }
8423
8424 // Handle the case of a templated-scope friend class. e.g.
8425 // template <class T> class A<T>::B;
8426 // FIXME: we don't support these right now.
8427 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8428 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8429 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8430 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8431 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008432 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008433 TL.setNameLoc(NameLoc);
8434
8435 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8436 TSI, FriendLoc);
8437 Friend->setAccess(AS_public);
8438 Friend->setUnsupportedFriend(true);
8439 CurContext->addDecl(Friend);
8440 return Friend;
8441}
8442
8443
John McCall11083da2009-09-16 22:47:08 +00008444/// Handle a friend type declaration. This works in tandem with
8445/// ActOnTag.
8446///
8447/// Notes on friend class templates:
8448///
8449/// We generally treat friend class declarations as if they were
8450/// declaring a class. So, for example, the elaborated type specifier
8451/// in a friend declaration is required to obey the restrictions of a
8452/// class-head (i.e. no typedefs in the scope chain), template
8453/// parameters are required to match up with simple template-ids, &c.
8454/// However, unlike when declaring a template specialization, it's
8455/// okay to refer to a template specialization without an empty
8456/// template parameter declaration, e.g.
8457/// friend class A<T>::B<unsigned>;
8458/// We permit this as a special case; if there are any template
8459/// parameters present at all, require proper matching, i.e.
8460/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008461Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008462 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008463 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008464
8465 assert(DS.isFriendSpecified());
8466 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8467
John McCall11083da2009-09-16 22:47:08 +00008468 // Try to convert the decl specifier to a type. This works for
8469 // friend templates because ActOnTag never produces a ClassTemplateDecl
8470 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008471 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008472 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8473 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008474 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008475 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008476
Douglas Gregor6c110f32010-12-16 01:14:37 +00008477 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8478 return 0;
8479
John McCall11083da2009-09-16 22:47:08 +00008480 // This is definitely an error in C++98. It's probably meant to
8481 // be forbidden in C++0x, too, but the specification is just
8482 // poorly written.
8483 //
8484 // The problem is with declarations like the following:
8485 // template <T> friend A<T>::foo;
8486 // where deciding whether a class C is a friend or not now hinges
8487 // on whether there exists an instantiation of A that causes
8488 // 'foo' to equal C. There are restrictions on class-heads
8489 // (which we declare (by fiat) elaborated friend declarations to
8490 // be) that makes this tractable.
8491 //
8492 // FIXME: handle "template <> friend class A<T>;", which
8493 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008494 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008495 Diag(Loc, diag::err_tagless_friend_type_template)
8496 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008497 return 0;
John McCall11083da2009-09-16 22:47:08 +00008498 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008499
John McCallaa74a0c2009-08-28 07:59:38 +00008500 // C++98 [class.friend]p1: A friend of a class is a function
8501 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008502 // This is fixed in DR77, which just barely didn't make the C++03
8503 // deadline. It's also a very silly restriction that seriously
8504 // affects inner classes and which nobody else seems to implement;
8505 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008506 //
8507 // But note that we could warn about it: it's always useless to
8508 // friend one of your own members (it's not, however, worthless to
8509 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008510
John McCall11083da2009-09-16 22:47:08 +00008511 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008512 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008513 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008514 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008515 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008516 TSI,
John McCall11083da2009-09-16 22:47:08 +00008517 DS.getFriendSpecLoc());
8518 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008519 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8520
8521 if (!D)
John McCall48871652010-08-21 09:40:31 +00008522 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008523
John McCall11083da2009-09-16 22:47:08 +00008524 D->setAccess(AS_public);
8525 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008526
John McCall48871652010-08-21 09:40:31 +00008527 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008528}
8529
John McCallde3fd222010-10-12 23:13:28 +00008530Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8531 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008532 const DeclSpec &DS = D.getDeclSpec();
8533
8534 assert(DS.isFriendSpecified());
8535 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8536
8537 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008538 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8539 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008540
8541 // C++ [class.friend]p1
8542 // A friend of a class is a function or class....
8543 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008544 // It *doesn't* see through dependent types, which is correct
8545 // according to [temp.arg.type]p3:
8546 // If a declaration acquires a function type through a
8547 // type dependent on a template-parameter and this causes
8548 // a declaration that does not use the syntactic form of a
8549 // function declarator to have a function type, the program
8550 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008551 if (!T->isFunctionType()) {
8552 Diag(Loc, diag::err_unexpected_friend);
8553
8554 // It might be worthwhile to try to recover by creating an
8555 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008556 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008557 }
8558
8559 // C++ [namespace.memdef]p3
8560 // - If a friend declaration in a non-local class first declares a
8561 // class or function, the friend class or function is a member
8562 // of the innermost enclosing namespace.
8563 // - The name of the friend is not found by simple name lookup
8564 // until a matching declaration is provided in that namespace
8565 // scope (either before or after the class declaration granting
8566 // friendship).
8567 // - If a friend function is called, its name may be found by the
8568 // name lookup that considers functions from namespaces and
8569 // classes associated with the types of the function arguments.
8570 // - When looking for a prior declaration of a class or a function
8571 // declared as a friend, scopes outside the innermost enclosing
8572 // namespace scope are not considered.
8573
John McCallde3fd222010-10-12 23:13:28 +00008574 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008575 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8576 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008577 assert(Name);
8578
Douglas Gregor6c110f32010-12-16 01:14:37 +00008579 // Check for unexpanded parameter packs.
8580 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8581 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8582 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8583 return 0;
8584
John McCall07e91c02009-08-06 02:15:43 +00008585 // The context we found the declaration in, or in which we should
8586 // create the declaration.
8587 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008588 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008589 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008590 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008591
John McCallde3fd222010-10-12 23:13:28 +00008592 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008593
John McCallde3fd222010-10-12 23:13:28 +00008594 // There are four cases here.
8595 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008596 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008597 // there as appropriate.
8598 // Recover from invalid scope qualifiers as if they just weren't there.
8599 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008600 // C++0x [namespace.memdef]p3:
8601 // If the name in a friend declaration is neither qualified nor
8602 // a template-id and the declaration is a function or an
8603 // elaborated-type-specifier, the lookup to determine whether
8604 // the entity has been previously declared shall not consider
8605 // any scopes outside the innermost enclosing namespace.
8606 // C++0x [class.friend]p11:
8607 // If a friend declaration appears in a local class and the name
8608 // specified is an unqualified name, a prior declaration is
8609 // looked up without considering scopes that are outside the
8610 // innermost enclosing non-class scope. For a friend function
8611 // declaration, if there is no prior declaration, the program is
8612 // ill-formed.
8613 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008614 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008615
John McCallf7cfb222010-10-13 05:45:15 +00008616 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008617 DC = CurContext;
8618 while (true) {
8619 // Skip class contexts. If someone can cite chapter and verse
8620 // for this behavior, that would be nice --- it's what GCC and
8621 // EDG do, and it seems like a reasonable intent, but the spec
8622 // really only says that checks for unqualified existing
8623 // declarations should stop at the nearest enclosing namespace,
8624 // not that they should only consider the nearest enclosing
8625 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008626 while (DC->isRecord())
8627 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008628
John McCall1f82f242009-11-18 22:49:29 +00008629 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008630
8631 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008632 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008633 break;
John McCallf7cfb222010-10-13 05:45:15 +00008634
John McCallf4776592010-10-14 22:22:28 +00008635 if (isTemplateId) {
8636 if (isa<TranslationUnitDecl>(DC)) break;
8637 } else {
8638 if (DC->isFileContext()) break;
8639 }
John McCall07e91c02009-08-06 02:15:43 +00008640 DC = DC->getParent();
8641 }
8642
8643 // C++ [class.friend]p1: A friend of a class is a function or
8644 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008645 // C++0x changes this for both friend types and functions.
8646 // Most C++ 98 compilers do seem to give an error here, so
8647 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008648 if (!Previous.empty() && DC->Equals(CurContext)
8649 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008650 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008651
John McCallccbc0322010-10-13 06:22:15 +00008652 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008653
John McCallde3fd222010-10-12 23:13:28 +00008654 // - There's a non-dependent scope specifier, in which case we
8655 // compute it and do a previous lookup there for a function
8656 // or function template.
8657 } else if (!SS.getScopeRep()->isDependent()) {
8658 DC = computeDeclContext(SS);
8659 if (!DC) return 0;
8660
8661 if (RequireCompleteDeclContext(SS, DC)) return 0;
8662
8663 LookupQualifiedName(Previous, DC);
8664
8665 // Ignore things found implicitly in the wrong scope.
8666 // TODO: better diagnostics for this case. Suggesting the right
8667 // qualified scope would be nice...
8668 LookupResult::Filter F = Previous.makeFilter();
8669 while (F.hasNext()) {
8670 NamedDecl *D = F.next();
8671 if (!DC->InEnclosingNamespaceSetOf(
8672 D->getDeclContext()->getRedeclContext()))
8673 F.erase();
8674 }
8675 F.done();
8676
8677 if (Previous.empty()) {
8678 D.setInvalidType();
8679 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8680 return 0;
8681 }
8682
8683 // C++ [class.friend]p1: A friend of a class is a function or
8684 // class that is not a member of the class . . .
8685 if (DC->Equals(CurContext))
8686 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8687
8688 // - There's a scope specifier that does not match any template
8689 // parameter lists, in which case we use some arbitrary context,
8690 // create a method or method template, and wait for instantiation.
8691 // - There's a scope specifier that does match some template
8692 // parameter lists, which we don't handle right now.
8693 } else {
8694 DC = CurContext;
8695 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008696 }
8697
John McCallf7cfb222010-10-13 05:45:15 +00008698 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008699 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008700 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8701 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8702 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008703 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008704 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8705 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008706 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008707 }
John McCall07e91c02009-08-06 02:15:43 +00008708 }
8709
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008710 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008711 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008712 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008713 IsDefinition,
8714 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008715 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008716
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008717 assert(ND->getDeclContext() == DC);
8718 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008719
John McCall759e32b2009-08-31 22:39:49 +00008720 // Add the function declaration to the appropriate lookup tables,
8721 // adjusting the redeclarations list as necessary. We don't
8722 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008723 //
John McCall759e32b2009-08-31 22:39:49 +00008724 // Also update the scope-based lookup if the target context's
8725 // lookup context is in lexical scope.
8726 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008727 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008728 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008729 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008730 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008731 }
John McCallaa74a0c2009-08-28 07:59:38 +00008732
8733 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008734 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008735 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008736 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008737 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008738
John McCallde3fd222010-10-12 23:13:28 +00008739 if (ND->isInvalidDecl())
8740 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008741 else {
8742 FunctionDecl *FD;
8743 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8744 FD = FTD->getTemplatedDecl();
8745 else
8746 FD = cast<FunctionDecl>(ND);
8747
8748 // Mark templated-scope function declarations as unsupported.
8749 if (FD->getNumTemplateParameterLists())
8750 FrD->setUnsupportedFriend(true);
8751 }
John McCallde3fd222010-10-12 23:13:28 +00008752
John McCall48871652010-08-21 09:40:31 +00008753 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008754}
8755
John McCall48871652010-08-21 09:40:31 +00008756void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8757 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008758
Sebastian Redlf769df52009-03-24 22:27:57 +00008759 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8760 if (!Fn) {
8761 Diag(DelLoc, diag::err_deleted_non_function);
8762 return;
8763 }
8764 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8765 Diag(DelLoc, diag::err_deleted_decl_not_first);
8766 Diag(Prev->getLocation(), diag::note_previous_declaration);
8767 // If the declaration wasn't the first, we delete the function anyway for
8768 // recovery.
8769 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008770 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008771}
Sebastian Redl4c018662009-04-27 21:33:24 +00008772
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008773void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8774 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8775
8776 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00008777 if (MD->getParent()->isDependentType()) {
8778 MD->setDefaulted();
8779 MD->setExplicitlyDefaulted();
8780 return;
8781 }
8782
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008783 CXXSpecialMember Member = getSpecialMember(MD);
8784 if (Member == CXXInvalid) {
8785 Diag(DefaultLoc, diag::err_default_special_members);
8786 return;
8787 }
8788
8789 MD->setDefaulted();
8790 MD->setExplicitlyDefaulted();
8791
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008792 // If this definition appears within the record, do the checking when
8793 // the record is complete.
8794 const FunctionDecl *Primary = MD;
8795 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8796 // Find the uninstantiated declaration that actually had the '= default'
8797 // on it.
8798 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8799
8800 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008801 return;
8802
8803 switch (Member) {
8804 case CXXDefaultConstructor: {
8805 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8806 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008807 if (!CD->isInvalidDecl())
8808 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8809 break;
8810 }
8811
8812 case CXXCopyConstructor: {
8813 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8814 CheckExplicitlyDefaultedCopyConstructor(CD);
8815 if (!CD->isInvalidDecl())
8816 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008817 break;
8818 }
Alexis Huntf91729462011-05-12 22:46:25 +00008819
Alexis Huntc9a55732011-05-14 05:23:28 +00008820 case CXXCopyAssignment: {
8821 CheckExplicitlyDefaultedCopyAssignment(MD);
8822 if (!MD->isInvalidDecl())
8823 DefineImplicitCopyAssignment(DefaultLoc, MD);
8824 break;
8825 }
8826
Alexis Huntf91729462011-05-12 22:46:25 +00008827 case CXXDestructor: {
8828 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8829 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008830 if (!DD->isInvalidDecl())
8831 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008832 break;
8833 }
8834
Alexis Hunt119c10e2011-05-25 23:16:36 +00008835 case CXXMoveConstructor:
8836 case CXXMoveAssignment:
8837 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8838 break;
8839
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008840 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008841 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008842 break;
8843 }
8844 } else {
8845 Diag(DefaultLoc, diag::err_default_special_members);
8846 }
8847}
8848
Sebastian Redl4c018662009-04-27 21:33:24 +00008849static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008850 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008851 Stmt *SubStmt = *CI;
8852 if (!SubStmt)
8853 continue;
8854 if (isa<ReturnStmt>(SubStmt))
8855 Self.Diag(SubStmt->getSourceRange().getBegin(),
8856 diag::err_return_in_constructor_handler);
8857 if (!isa<Expr>(SubStmt))
8858 SearchForReturnInStmt(Self, SubStmt);
8859 }
8860}
8861
8862void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8863 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8864 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8865 SearchForReturnInStmt(*this, Handler);
8866 }
8867}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008868
Mike Stump11289f42009-09-09 15:08:12 +00008869bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008870 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008871 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8872 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008873
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008874 if (Context.hasSameType(NewTy, OldTy) ||
8875 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008876 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008877
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008878 // Check if the return types are covariant
8879 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008880
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008881 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008882 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8883 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008884 NewClassTy = NewPT->getPointeeType();
8885 OldClassTy = OldPT->getPointeeType();
8886 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008887 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8888 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8889 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8890 NewClassTy = NewRT->getPointeeType();
8891 OldClassTy = OldRT->getPointeeType();
8892 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008893 }
8894 }
Mike Stump11289f42009-09-09 15:08:12 +00008895
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008896 // The return types aren't either both pointers or references to a class type.
8897 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008898 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008899 diag::err_different_return_type_for_overriding_virtual_function)
8900 << New->getDeclName() << NewTy << OldTy;
8901 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008902
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008903 return true;
8904 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008905
Anders Carlssone60365b2009-12-31 18:34:24 +00008906 // C++ [class.virtual]p6:
8907 // If the return type of D::f differs from the return type of B::f, the
8908 // class type in the return type of D::f shall be complete at the point of
8909 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008910 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8911 if (!RT->isBeingDefined() &&
8912 RequireCompleteType(New->getLocation(), NewClassTy,
8913 PDiag(diag::err_covariant_return_incomplete)
8914 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008915 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008916 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008917
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008918 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008919 // Check if the new class derives from the old class.
8920 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8921 Diag(New->getLocation(),
8922 diag::err_covariant_return_not_derived)
8923 << New->getDeclName() << NewTy << OldTy;
8924 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8925 return true;
8926 }
Mike Stump11289f42009-09-09 15:08:12 +00008927
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008928 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008929 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008930 diag::err_covariant_return_inaccessible_base,
8931 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8932 // FIXME: Should this point to the return type?
8933 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008934 // FIXME: this note won't trigger for delayed access control
8935 // diagnostics, and it's impossible to get an undelayed error
8936 // here from access control during the original parse because
8937 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008938 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8939 return true;
8940 }
8941 }
Mike Stump11289f42009-09-09 15:08:12 +00008942
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008943 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008944 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008945 Diag(New->getLocation(),
8946 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008947 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008948 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8949 return true;
8950 };
Mike Stump11289f42009-09-09 15:08:12 +00008951
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008952
8953 // The new class type must have the same or less qualifiers as the old type.
8954 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8955 Diag(New->getLocation(),
8956 diag::err_covariant_return_type_class_type_more_qualified)
8957 << New->getDeclName() << NewTy << OldTy;
8958 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8959 return true;
8960 };
Mike Stump11289f42009-09-09 15:08:12 +00008961
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008962 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008963}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008964
Douglas Gregor21920e372009-12-01 17:24:26 +00008965/// \brief Mark the given method pure.
8966///
8967/// \param Method the method to be marked pure.
8968///
8969/// \param InitRange the source range that covers the "0" initializer.
8970bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008971 SourceLocation EndLoc = InitRange.getEnd();
8972 if (EndLoc.isValid())
8973 Method->setRangeEnd(EndLoc);
8974
Douglas Gregor21920e372009-12-01 17:24:26 +00008975 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8976 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008977 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008978 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008979
8980 if (!Method->isInvalidDecl())
8981 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8982 << Method->getDeclName() << InitRange;
8983 return true;
8984}
8985
John McCall1f4ee7b2009-12-19 09:28:58 +00008986/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8987/// an initializer for the out-of-line declaration 'Dcl'. The scope
8988/// is a fresh scope pushed for just this purpose.
8989///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008990/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8991/// static data member of class X, names should be looked up in the scope of
8992/// class X.
John McCall48871652010-08-21 09:40:31 +00008993void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008994 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008995 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008996
John McCall1f4ee7b2009-12-19 09:28:58 +00008997 // We should only get called for declarations with scope specifiers, like:
8998 // int foo::bar;
8999 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00009000 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00009001}
9002
9003/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00009004/// initializer for the out-of-line declaration 'D'.
9005void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00009006 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00009007 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00009008
John McCall1f4ee7b2009-12-19 09:28:58 +00009009 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00009010 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00009011}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009012
9013/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9014/// C++ if/switch/while/for statement.
9015/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00009016DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009017 // C++ 6.4p2:
9018 // The declarator shall not specify a function or an array.
9019 // The type-specifier-seq shall not contain typedef and shall not declare a
9020 // new class or enumeration.
9021 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9022 "Parser allowed 'typedef' as storage class of condition decl.");
9023
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009024 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00009025 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9026 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009027
9028 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9029 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9030 // would be created and CXXConditionDeclExpr wants a VarDecl.
9031 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9032 << D.getSourceRange();
9033 return DeclResult();
9034 } else if (OwnedTag && OwnedTag->isDefinition()) {
9035 // The type-specifier-seq shall not declare a new class or enumeration.
9036 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9037 }
9038
John McCall48871652010-08-21 09:40:31 +00009039 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009040 if (!Dcl)
9041 return DeclResult();
9042
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00009043 return Dcl;
9044}
Anders Carlssonf98849e2009-12-02 17:15:43 +00009045
Douglas Gregor88d292c2010-05-13 16:44:06 +00009046void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9047 bool DefinitionRequired) {
9048 // Ignore any vtable uses in unevaluated operands or for classes that do
9049 // not have a vtable.
9050 if (!Class->isDynamicClass() || Class->isDependentContext() ||
9051 CurContext->isDependentContext() ||
9052 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00009053 return;
9054
Douglas Gregor88d292c2010-05-13 16:44:06 +00009055 // Try to insert this class into the map.
9056 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9057 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9058 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9059 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00009060 // If we already had an entry, check to see if we are promoting this vtable
9061 // to required a definition. If so, we need to reappend to the VTableUses
9062 // list, since we may have already processed the first entry.
9063 if (DefinitionRequired && !Pos.first->second) {
9064 Pos.first->second = true;
9065 } else {
9066 // Otherwise, we can early exit.
9067 return;
9068 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009069 }
9070
9071 // Local classes need to have their virtual members marked
9072 // immediately. For all other classes, we mark their virtual members
9073 // at the end of the translation unit.
9074 if (Class->isLocalClass())
9075 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00009076 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00009077 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00009078}
9079
Douglas Gregor88d292c2010-05-13 16:44:06 +00009080bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009081 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00009082 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00009083
Douglas Gregor88d292c2010-05-13 16:44:06 +00009084 // Note: The VTableUses vector could grow as a result of marking
9085 // the members of a class as "used", so we check the size each
9086 // time through the loop and prefer indices (with are stable) to
9087 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00009088 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009089 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00009090 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00009091 if (!Class)
9092 continue;
9093
9094 SourceLocation Loc = VTableUses[I].second;
9095
9096 // If this class has a key function, but that key function is
9097 // defined in another translation unit, we don't need to emit the
9098 // vtable even though we're using it.
9099 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009100 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00009101 switch (KeyFunction->getTemplateSpecializationKind()) {
9102 case TSK_Undeclared:
9103 case TSK_ExplicitSpecialization:
9104 case TSK_ExplicitInstantiationDeclaration:
9105 // The key function is in another translation unit.
9106 continue;
9107
9108 case TSK_ExplicitInstantiationDefinition:
9109 case TSK_ImplicitInstantiation:
9110 // We will be instantiating the key function.
9111 break;
9112 }
9113 } else if (!KeyFunction) {
9114 // If we have a class with no key function that is the subject
9115 // of an explicit instantiation declaration, suppress the
9116 // vtable; it will live with the explicit instantiation
9117 // definition.
9118 bool IsExplicitInstantiationDeclaration
9119 = Class->getTemplateSpecializationKind()
9120 == TSK_ExplicitInstantiationDeclaration;
9121 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9122 REnd = Class->redecls_end();
9123 R != REnd; ++R) {
9124 TemplateSpecializationKind TSK
9125 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9126 if (TSK == TSK_ExplicitInstantiationDeclaration)
9127 IsExplicitInstantiationDeclaration = true;
9128 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9129 IsExplicitInstantiationDeclaration = false;
9130 break;
9131 }
9132 }
9133
9134 if (IsExplicitInstantiationDeclaration)
9135 continue;
9136 }
9137
9138 // Mark all of the virtual members of this class as referenced, so
9139 // that we can build a vtable. Then, tell the AST consumer that a
9140 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009141 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009142 MarkVirtualMembersReferenced(Loc, Class);
9143 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9144 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9145
9146 // Optionally warn if we're emitting a weak vtable.
9147 if (Class->getLinkage() == ExternalLinkage &&
9148 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009149 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009150 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9151 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009152 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009153 VTableUses.clear();
9154
Douglas Gregor97509692011-04-22 22:25:37 +00009155 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009156}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009157
Rafael Espindola5b334082010-03-26 00:36:59 +00009158void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9159 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009160 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9161 e = RD->method_end(); i != e; ++i) {
9162 CXXMethodDecl *MD = *i;
9163
9164 // C++ [basic.def.odr]p2:
9165 // [...] A virtual member function is used if it is not pure. [...]
9166 if (MD->isVirtual() && !MD->isPure())
9167 MarkDeclarationReferenced(Loc, MD);
9168 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009169
9170 // Only classes that have virtual bases need a VTT.
9171 if (RD->getNumVBases() == 0)
9172 return;
9173
9174 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9175 e = RD->bases_end(); i != e; ++i) {
9176 const CXXRecordDecl *Base =
9177 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009178 if (Base->getNumVBases() == 0)
9179 continue;
9180 MarkVirtualMembersReferenced(Loc, Base);
9181 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009182}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009183
9184/// SetIvarInitializers - This routine builds initialization ASTs for the
9185/// Objective-C implementation whose ivars need be initialized.
9186void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9187 if (!getLangOptions().CPlusPlus)
9188 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009189 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009190 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9191 CollectIvarsToConstructOrDestruct(OID, ivars);
9192 if (ivars.empty())
9193 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009194 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009195 for (unsigned i = 0; i < ivars.size(); i++) {
9196 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009197 if (Field->isInvalidDecl())
9198 continue;
9199
Alexis Hunt1d792652011-01-08 20:30:50 +00009200 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009201 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9202 InitializationKind InitKind =
9203 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9204
9205 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009206 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009207 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009208 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009209 // Note, MemberInit could actually come back empty if no initialization
9210 // is required (e.g., because it would call a trivial default constructor)
9211 if (!MemberInit.get() || MemberInit.isInvalid())
9212 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009213
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009214 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009215 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9216 SourceLocation(),
9217 MemberInit.takeAs<Expr>(),
9218 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009219 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009220
9221 // Be sure that the destructor is accessible and is marked as referenced.
9222 if (const RecordType *RecordTy
9223 = Context.getBaseElementType(Field->getType())
9224 ->getAs<RecordType>()) {
9225 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009226 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009227 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9228 CheckDestructorAccess(Field->getLocation(), Destructor,
9229 PDiag(diag::err_access_dtor_ivar)
9230 << Context.getBaseElementType(Field->getType()));
9231 }
9232 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009233 }
9234 ObjCImplementation->setIvarInitializers(Context,
9235 AllToInit.data(), AllToInit.size());
9236 }
9237}
Alexis Hunt6118d662011-05-04 05:57:24 +00009238
Alexis Hunt27a761d2011-05-04 23:29:54 +00009239static
9240void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9241 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9242 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9243 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9244 Sema &S) {
9245 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9246 CE = Current.end();
9247 if (Ctor->isInvalidDecl())
9248 return;
9249
9250 const FunctionDecl *FNTarget = 0;
9251 CXXConstructorDecl *Target;
9252
9253 // We ignore the result here since if we don't have a body, Target will be
9254 // null below.
9255 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9256 Target
9257= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9258
9259 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9260 // Avoid dereferencing a null pointer here.
9261 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9262
9263 if (!Current.insert(Canonical))
9264 return;
9265
9266 // We know that beyond here, we aren't chaining into a cycle.
9267 if (!Target || !Target->isDelegatingConstructor() ||
9268 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9269 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9270 Valid.insert(*CI);
9271 Current.clear();
9272 // We've hit a cycle.
9273 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9274 Current.count(TCanonical)) {
9275 // If we haven't diagnosed this cycle yet, do so now.
9276 if (!Invalid.count(TCanonical)) {
9277 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009278 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009279 << Ctor;
9280
9281 // Don't add a note for a function delegating directo to itself.
9282 if (TCanonical != Canonical)
9283 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9284
9285 CXXConstructorDecl *C = Target;
9286 while (C->getCanonicalDecl() != Canonical) {
9287 (void)C->getTargetConstructor()->hasBody(FNTarget);
9288 assert(FNTarget && "Ctor cycle through bodiless function");
9289
9290 C
9291 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9292 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9293 }
9294 }
9295
9296 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9297 Invalid.insert(*CI);
9298 Current.clear();
9299 } else {
9300 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9301 }
9302}
9303
9304
Alexis Hunt6118d662011-05-04 05:57:24 +00009305void Sema::CheckDelegatingCtorCycles() {
9306 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9307
Alexis Hunt27a761d2011-05-04 23:29:54 +00009308 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9309 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009310
9311 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009312 I = DelegatingCtorDecls.begin(),
9313 E = DelegatingCtorDecls.end();
9314 I != E; ++I) {
9315 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009316 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009317
9318 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9319 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009320}