blob: ac51138b91d44fb1d9b124a8988e6ca882d960cc [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:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
193 //
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
197 //
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
200 //
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
205
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
208}
209
Anders 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();
Douglas Gregor29a92472008-10-22 17:49:05 +0000765 if (KnownBaseTypes[NewBaseType]) {
766 // C++ [class.mi]p3:
767 // A class shall not be specified as a direct base class of a
768 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000769 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000770 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000771 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000772 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000773
774 // Delete the duplicate base class specifier; we're going to
775 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000776 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000777
778 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000779 } else {
780 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000781 KnownBaseTypes[NewBaseType] = Bases[idx];
782 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000783 }
784 }
785
786 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000787 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000788
789 // Delete the remaining (good) base class specifiers, since their
790 // data has been copied into the CXXRecordDecl.
791 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000792 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000793
794 return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
John McCall48871652010-08-21 09:40:31 +0000800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000801 unsigned NumBases) {
802 if (!ClassDecl || !Bases || !NumBases)
803 return;
804
805 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000807 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000808}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000809
John McCalle78aac42010-03-10 03:28:59 +0000810static CXXRecordDecl *GetClassForType(QualType T) {
811 if (const RecordType *RT = T->getAs<RecordType>())
812 return cast<CXXRecordDecl>(RT->getDecl());
813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814 return ICT->getDecl();
815 else
816 return 0;
817}
818
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822 if (!getLangOptions().CPlusPlus)
823 return false;
John McCalle78aac42010-03-10 03:28:59 +0000824
825 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000827 return false;
828
John McCalle78aac42010-03-10 03:28:59 +0000829 CXXRecordDecl *BaseRD = GetClassForType(Base);
830 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000831 return false;
832
John McCall67da35c2010-02-04 22:26:26 +0000833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840 if (!getLangOptions().CPlusPlus)
841 return false;
842
John McCalle78aac42010-03-10 03:28:59 +0000843 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000845 return false;
846
John McCalle78aac42010-03-10 03:28:59 +0000847 CXXRecordDecl *BaseRD = GetClassForType(Base);
848 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000849 return false;
850
Douglas Gregor36d1b142009-10-06 17:59:45 +0000851 return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
Anders Carlssona70cff62010-04-24 19:06:50 +0000854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000855 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000856 assert(BasePathArray.empty() && "Base path array must be empty!");
857 assert(Paths.isRecordingPaths() && "Must record paths!");
858
859 const CXXBasePath &Path = Paths.front();
860
861 // We first go backward and check if we have a virtual base.
862 // FIXME: It would be better if CXXBasePath had the base specifier for
863 // the nearest virtual base.
864 unsigned Start = 0;
865 for (unsigned I = Path.size(); I != 0; --I) {
866 if (Path[I - 1].Base->isVirtual()) {
867 Start = I - 1;
868 break;
869 }
870 }
871
872 // Now add all bases.
873 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000875}
876
Douglas Gregor88d292c2010-05-13 16:44:06 +0000877/// \brief Determine whether the given base path includes a virtual
878/// base class.
John McCallcf142162010-08-07 06:22:56 +0000879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880 for (CXXCastPath::const_iterator B = BasePath.begin(),
881 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000882 B != BEnd; ++B)
883 if ((*B)->isVirtual())
884 return true;
885
886 return false;
887}
888
Douglas Gregor36d1b142009-10-06 17:59:45 +0000889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000899 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000900 unsigned AmbigiousBaseConvID,
901 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000902 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000903 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000904 // First, determine whether the path from Derived to Base is
905 // ambiguous. This is slightly more expensive than checking whether
906 // the Derived to Base conversion exists, because here we need to
907 // explore multiple paths to determine if there is an ambiguity.
908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909 /*DetectVirtual=*/false);
910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911 assert(DerivationOkay &&
912 "Can only be used with a derived-to-base conversion");
913 (void)DerivationOkay;
914
915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000916 if (InaccessibleBaseID) {
917 // Check that the base class can be accessed.
918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919 InaccessibleBaseID)) {
920 case AR_inaccessible:
921 return true;
922 case AR_accessible:
923 case AR_dependent:
924 case AR_delayed:
925 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000926 }
John McCall5b0829a2010-02-10 09:31:12 +0000927 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000928
929 // Build a base path if necessary.
930 if (BasePath)
931 BuildBasePathArray(Paths, *BasePath);
932 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000933 }
934
935 // We know that the derived-to-base conversion is ambiguous, and
936 // we're going to produce a diagnostic. Perform the derived-to-base
937 // search just one more time to compute all of the possible paths so
938 // that we can print them out. This is more expensive than any of
939 // the previous derived-to-base checks we've done, but at this point
940 // performance isn't as much of an issue.
941 Paths.clear();
942 Paths.setRecordingPaths(true);
943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944 assert(StillOkay && "Can only be used with a derived-to-base conversion");
945 (void)StillOkay;
946
947 // Build up a textual representation of the ambiguous paths, e.g.,
948 // D -> B -> A, that will be used to illustrate the ambiguous
949 // conversions in the diagnostic. We only print one of the paths
950 // to each base class subobject.
951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953 Diag(Loc, AmbigiousBaseConvID)
954 << Derived << Base << PathDisplayStr << Range << Name;
955 return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000960 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000961 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000962 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000963 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000964 IgnoreAccess ? 0
965 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000966 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000967 Loc, Range, DeclarationName(),
968 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985 std::string PathDisplayStr;
986 std::set<unsigned> DisplayedPaths;
987 for (CXXBasePaths::paths_iterator Path = Paths.begin();
988 Path != Paths.end(); ++Path) {
989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990 // We haven't displayed a path to this particular base
991 // class subobject yet.
992 PathDisplayStr += "\n ";
993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994 for (CXXBasePath::const_iterator Element = Path->begin();
995 Element != Path->end(); ++Element)
996 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997 }
998 }
999
1000 return PathDisplayStr;
1001}
1002
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
Abramo Bagnarad7340582010-06-05 05:09:32 +00001007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +00001008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009 SourceLocation ASLoc,
1010 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001013 ASLoc, ColonLoc);
1014 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +00001015 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +00001016}
1017
Anders Carlssonfd835532011-01-20 05:57:14 +00001018/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001019void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +00001020 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1021 if (!MD || !MD->isVirtual())
1022 return;
1023
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001024 if (MD->isDependentContext())
1025 return;
1026
Anders Carlssonfd835532011-01-20 05:57:14 +00001027 // C++0x [class.virtual]p3:
1028 // If a virtual function is marked with the virt-specifier override and does
1029 // not override a member function of a base class,
1030 // the program is ill-formed.
1031 bool HasOverriddenMethods =
1032 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001034 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001035 diag::err_function_marked_override_not_overriding)
1036 << MD->getDeclName();
1037 return;
1038 }
1039}
1040
Anders Carlsson3f610c72011-01-20 16:25:36 +00001041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001046 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001047 return false;
1048
1049 Diag(New->getLocation(), diag::err_final_function_overridden)
1050 << New->getDeclName();
1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001053}
1054
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001060Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001062 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +00001063 ExprTy *BW, const VirtSpecifiers &VS,
Richard Smith938f40b2011-06-11 17:19:42 +00001064 ExprTy *InitExpr, bool HasDeferredInit,
1065 bool IsDefinition) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001066 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068 DeclarationName Name = NameInfo.getName();
1069 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001070
1071 // For anonymous bitfields, the location should point to the type.
1072 if (Loc.isInvalid())
1073 Loc = D.getSourceRange().getBegin();
1074
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001075 Expr *BitWidth = static_cast<Expr*>(BW);
1076 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001077
John McCallb1cd7da2010-06-04 08:34:12 +00001078 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001079 assert(!DS.isFriendSpecified());
Richard Smith938f40b2011-06-11 17:19:42 +00001080 assert(!Init || !HasDeferredInit);
John McCall07e91c02009-08-06 02:15:43 +00001081
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001082 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001083
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001084 // C++ 9.2p6: A member shall not be declared to have automatic storage
1085 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087 // data members and cannot be applied to names declared const or static,
1088 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001089 switch (DS.getStorageClassSpec()) {
1090 case DeclSpec::SCS_unspecified:
1091 case DeclSpec::SCS_typedef:
1092 case DeclSpec::SCS_static:
1093 // FALL THROUGH.
1094 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001095 case DeclSpec::SCS_mutable:
1096 if (isFunc) {
1097 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001099 else
Chris Lattner3b054132008-11-19 05:08:23 +00001100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001101
Sebastian Redl8071edb2008-11-17 23:24:37 +00001102 // FIXME: It would be nicer if the keyword was ignored only for this
1103 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001104 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001105 }
1106 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001107 default:
1108 if (DS.getStorageClassSpecLoc().isValid())
1109 Diag(DS.getStorageClassSpecLoc(),
1110 diag::err_storageclass_invalid_for_member);
1111 else
1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113 D.getMutableDeclSpec().ClearStorageClassSpecs();
1114 }
1115
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001118 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001119
1120 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001121 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001122 CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
Douglas Gregora007d362010-10-13 22:19:53 +00001124 if (SS.isSet() && !SS.isInvalid()) {
1125 // The user provided a superfluous scope specifier inside a class
1126 // definition:
1127 //
1128 // class X {
1129 // int X::member;
1130 // };
1131 DeclContext *DC = 0;
1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134 << Name << FixItHint::CreateRemoval(SS.getRange());
1135 else
1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137 << Name << SS.getRange();
1138
1139 SS.clear();
1140 }
1141
Douglas Gregor3447e762009-08-20 22:52:58 +00001142 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001143 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001145 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001146 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001147 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001148 assert(!HasDeferredInit);
1149
Alexis Hunt5a7fa252011-05-12 06:15:49 +00001150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001151 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001152 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001153 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001154
1155 // Non-instance-fields can't have a bitfield.
1156 if (BitWidth) {
1157 if (Member->isInvalidDecl()) {
1158 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001159 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001160 // C++ 9.6p3: A bit-field shall not be a static member.
1161 // "static member 'A' cannot be a bit-field"
1162 Diag(Loc, diag::err_static_not_bitfield)
1163 << Name << BitWidth->getSourceRange();
1164 } else if (isa<TypedefDecl>(Member)) {
1165 // "typedef member 'x' cannot be a bit-field"
1166 Diag(Loc, diag::err_typedef_not_bitfield)
1167 << Name << BitWidth->getSourceRange();
1168 } else {
1169 // A function typedef ("typedef int f(); f a;").
1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001172 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001173 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001174 }
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattnerd26760a2009-03-05 23:01:03 +00001176 BitWidth = 0;
1177 Member->setInvalidDecl();
1178 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001179
1180 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Douglas Gregor3447e762009-08-20 22:52:58 +00001182 // If we have declared a member function template, set the access of the
1183 // templated declaration as well.
1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001186 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001187
Anders Carlsson13a69102011-01-20 04:34:22 +00001188 if (VS.isOverrideSpecified()) {
1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190 if (!MD || !MD->isVirtual()) {
1191 Diag(Member->getLocStart(),
1192 diag::override_keyword_only_allowed_on_virtual_member_functions)
1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001194 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001196 }
1197 if (VS.isFinalSpecified()) {
1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199 if (!MD || !MD->isVirtual()) {
1200 Diag(Member->getLocStart(),
1201 diag::override_keyword_only_allowed_on_virtual_member_functions)
1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001203 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001205 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001206
Douglas Gregorf2f08062011-03-08 17:10:18 +00001207 if (VS.getLastLocation().isValid()) {
1208 // Update the end location of a method that has a virt-specifiers.
1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210 MD->setRangeEnd(VS.getLastLocation());
1211 }
1212
Anders Carlssonc87f8612011-01-20 06:29:02 +00001213 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001214
Douglas Gregor92751d42008-11-17 22:58:34 +00001215 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001216
Douglas Gregor0c880302009-03-11 23:00:04 +00001217 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001218 AddInitializerToDecl(Member, Init, false,
1219 DS.getTypeSpecType() == DeclSpec::TST_auto);
Richard Smith938f40b2011-06-11 17:19:42 +00001220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223 // data member if a brace-or-equal-initializer is provided.
1224 Diag(Loc, diag::err_auto_var_requires_init)
1225 << Name << cast<ValueDecl>(Member)->getType();
1226 Member->setInvalidDecl();
1227 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001228
Richard Smithb2bc2e62011-02-21 20:05:19 +00001229 FinalizeDeclaration(Member);
1230
John McCall25849ca2011-02-15 07:12:36 +00001231 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001232 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001233 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001234}
1235
Richard Smith938f40b2011-06-11 17:19:42 +00001236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237/// in-class initializer for a non-static C++ class member. Such parsing
1238/// is deferred until the class is complete.
1239void
1240Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1241 Expr *InitExpr) {
1242 FieldDecl *FD = cast<FieldDecl>(D);
1243
1244 if (!InitExpr) {
1245 FD->setInvalidDecl();
1246 FD->removeInClassInitializer();
1247 return;
1248 }
1249
1250 ExprResult Init = InitExpr;
1251 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1252 // FIXME: if there is no EqualLoc, this is list-initialization.
1253 Init = PerformCopyInitialization(
1254 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1255 if (Init.isInvalid()) {
1256 FD->setInvalidDecl();
1257 return;
1258 }
1259
1260 CheckImplicitConversions(Init.get(), EqualLoc);
1261 }
1262
1263 // C++0x [class.base.init]p7:
1264 // The initialization of each base and member constitutes a
1265 // full-expression.
1266 Init = MaybeCreateExprWithCleanups(Init);
1267 if (Init.isInvalid()) {
1268 FD->setInvalidDecl();
1269 return;
1270 }
1271
1272 InitExpr = Init.release();
1273
1274 FD->setInClassInitializer(InitExpr);
1275}
1276
Douglas Gregor15e77a22009-12-31 09:10:24 +00001277/// \brief Find the direct and/or virtual base specifiers that
1278/// correspond to the given base type, for use in base initialization
1279/// within a constructor.
1280static bool FindBaseInitializer(Sema &SemaRef,
1281 CXXRecordDecl *ClassDecl,
1282 QualType BaseType,
1283 const CXXBaseSpecifier *&DirectBaseSpec,
1284 const CXXBaseSpecifier *&VirtualBaseSpec) {
1285 // First, check for a direct base class.
1286 DirectBaseSpec = 0;
1287 for (CXXRecordDecl::base_class_const_iterator Base
1288 = ClassDecl->bases_begin();
1289 Base != ClassDecl->bases_end(); ++Base) {
1290 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1291 // We found a direct base of this type. That's what we're
1292 // initializing.
1293 DirectBaseSpec = &*Base;
1294 break;
1295 }
1296 }
1297
1298 // Check for a virtual base class.
1299 // FIXME: We might be able to short-circuit this if we know in advance that
1300 // there are no virtual bases.
1301 VirtualBaseSpec = 0;
1302 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1303 // We haven't found a base yet; search the class hierarchy for a
1304 // virtual base class.
1305 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1306 /*DetectVirtual=*/false);
1307 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1308 BaseType, Paths)) {
1309 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1310 Path != Paths.end(); ++Path) {
1311 if (Path->back().Base->isVirtual()) {
1312 VirtualBaseSpec = Path->back().Base;
1313 break;
1314 }
1315 }
1316 }
1317 }
1318
1319 return DirectBaseSpec || VirtualBaseSpec;
1320}
1321
Douglas Gregore8381c02008-11-05 04:29:56 +00001322/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001323MemInitResult
John McCall48871652010-08-21 09:40:31 +00001324Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001325 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001326 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001327 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001328 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001329 SourceLocation IdLoc,
1330 SourceLocation LParenLoc,
1331 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001332 SourceLocation RParenLoc,
1333 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001334 if (!ConstructorD)
1335 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001337 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001338
1339 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001340 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001341 if (!Constructor) {
1342 // The user wrote a constructor initializer on a function that is
1343 // not a C++ constructor. Ignore the error for now, because we may
1344 // have more member initializers coming; we'll diagnose it just
1345 // once in ActOnMemInitializers.
1346 return true;
1347 }
1348
1349 CXXRecordDecl *ClassDecl = Constructor->getParent();
1350
1351 // C++ [class.base.init]p2:
1352 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001353 // constructor's class and, if not found in that scope, are looked
1354 // up in the scope containing the constructor's definition.
1355 // [Note: if the constructor's class contains a member with the
1356 // same name as a direct or virtual base class of the class, a
1357 // mem-initializer-id naming the member or base class and composed
1358 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001359 // mem-initializer-id for the hidden base class may be specified
1360 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001361 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001362 // Look for a member, first.
1363 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001364 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001365 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001366 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001367 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001368
Douglas Gregor44e7df62011-01-04 00:32:56 +00001369 if (Member) {
1370 if (EllipsisLoc.isValid())
1371 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1372 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1373
Francois Pichetd583da02010-12-04 09:14:42 +00001374 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001375 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001376 }
1377
Francois Pichetd583da02010-12-04 09:14:42 +00001378 // Handle anonymous union case.
1379 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001380 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1381 if (EllipsisLoc.isValid())
1382 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1383 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1384
Francois Pichetd583da02010-12-04 09:14:42 +00001385 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1386 NumArgs, IdLoc,
1387 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001388 }
Francois Pichetd583da02010-12-04 09:14:42 +00001389 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001390 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001391 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001392 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001393 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001394
1395 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001396 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001397 } else {
1398 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1399 LookupParsedName(R, S, &SS);
1400
1401 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1402 if (!TyD) {
1403 if (R.isAmbiguous()) return true;
1404
John McCallda6841b2010-04-09 19:01:14 +00001405 // We don't want access-control diagnostics here.
1406 R.suppressDiagnostics();
1407
Douglas Gregora3b624a2010-01-19 06:46:48 +00001408 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1409 bool NotUnknownSpecialization = false;
1410 DeclContext *DC = computeDeclContext(SS, false);
1411 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1412 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1413
1414 if (!NotUnknownSpecialization) {
1415 // When the scope specifier can refer to a member of an unknown
1416 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001417 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1418 SS.getWithLocInContext(Context),
1419 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001420 if (BaseType.isNull())
1421 return true;
1422
Douglas Gregora3b624a2010-01-19 06:46:48 +00001423 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001424 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001425 }
1426 }
1427
Douglas Gregor15e77a22009-12-31 09:10:24 +00001428 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001429 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00001430 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001431 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1432 ClassDecl, false, CTC_NoKeywords))) {
1433 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1434 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1435 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001436 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001437 // We have found a non-static data member with a similar
1438 // name to what was typed; complain and initialize that
1439 // member.
1440 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001441 << MemberOrBase << true << CorrectedQuotedStr
1442 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor6da83622010-01-07 00:17:44 +00001443 Diag(Member->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001444 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001445
1446 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1447 LParenLoc, RParenLoc);
1448 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001449 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001450 const CXXBaseSpecifier *DirectBaseSpec;
1451 const CXXBaseSpecifier *VirtualBaseSpec;
1452 if (FindBaseInitializer(*this, ClassDecl,
1453 Context.getTypeDeclType(Type),
1454 DirectBaseSpec, VirtualBaseSpec)) {
1455 // We have found a direct or virtual base class with a
1456 // similar name to what was typed; complain and initialize
1457 // that base class.
1458 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001459 << MemberOrBase << false << CorrectedQuotedStr
1460 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001461
1462 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1463 : VirtualBaseSpec;
1464 Diag(BaseSpec->getSourceRange().getBegin(),
1465 diag::note_base_class_specified_here)
1466 << BaseSpec->getType()
1467 << BaseSpec->getSourceRange();
1468
Douglas Gregor15e77a22009-12-31 09:10:24 +00001469 TyD = Type;
1470 }
1471 }
1472 }
1473
Douglas Gregora3b624a2010-01-19 06:46:48 +00001474 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001475 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1476 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1477 return true;
1478 }
John McCallb5a0d312009-12-21 10:41:20 +00001479 }
1480
Douglas Gregora3b624a2010-01-19 06:46:48 +00001481 if (BaseType.isNull()) {
1482 BaseType = Context.getTypeDeclType(TyD);
1483 if (SS.isSet()) {
1484 NestedNameSpecifier *Qualifier =
1485 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001486
Douglas Gregora3b624a2010-01-19 06:46:48 +00001487 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001488 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001489 }
John McCallb5a0d312009-12-21 10:41:20 +00001490 }
1491 }
Mike Stump11289f42009-09-09 15:08:12 +00001492
John McCallbcd03502009-12-07 02:54:59 +00001493 if (!TInfo)
1494 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001495
John McCallbcd03502009-12-07 02:54:59 +00001496 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001497 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001498}
1499
John McCalle22a04a2009-11-04 23:02:40 +00001500/// Checks an initializer expression for use of uninitialized fields, such as
1501/// containing the field that is being initialized. Returns true if there is an
1502/// uninitialized field was used an updates the SourceLocation parameter; false
1503/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001504static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001505 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001506 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001507 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1508
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001509 if (isa<CallExpr>(S)) {
1510 // Do not descend into function calls or constructors, as the use
1511 // of an uninitialized field may be valid. One would have to inspect
1512 // the contents of the function/ctor to determine if it is safe or not.
1513 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1514 // may be safe, depending on what the function/ctor does.
1515 return false;
1516 }
1517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1518 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001519
1520 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1521 // The member expression points to a static data member.
1522 assert(VD->isStaticDataMember() &&
1523 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001524 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001525 return false;
1526 }
1527
1528 if (isa<EnumConstantDecl>(RhsField)) {
1529 // The member expression points to an enum.
1530 return false;
1531 }
1532
John McCalle22a04a2009-11-04 23:02:40 +00001533 if (RhsField == LhsField) {
1534 // Initializing a field with itself. Throw a warning.
1535 // But wait; there are exceptions!
1536 // Exception #1: The field may not belong to this record.
1537 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001538 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001539 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1540 // Even though the field matches, it does not belong to this record.
1541 return false;
1542 }
1543 // None of the exceptions triggered; return true to indicate an
1544 // uninitialized field was used.
1545 *L = ME->getMemberLoc();
1546 return true;
1547 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001548 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001549 // sizeof/alignof doesn't reference contents, do not warn.
1550 return false;
1551 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1552 // address-of doesn't reference contents (the pointer may be dereferenced
1553 // in the same expression but it would be rare; and weird).
1554 if (UOE->getOpcode() == UO_AddrOf)
1555 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001556 }
John McCall8322c3a2011-02-13 04:07:26 +00001557 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001558 if (!*it) {
1559 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001560 continue;
1561 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001562 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1563 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001564 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001565 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001566}
1567
John McCallfaf5fb42010-08-26 23:41:50 +00001568MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001569Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001570 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001571 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001572 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001573 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1574 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1575 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001576 "Member must be a FieldDecl or IndirectFieldDecl");
1577
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001578 if (Member->isInvalidDecl())
1579 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001580
John McCalle22a04a2009-11-04 23:02:40 +00001581 // Diagnose value-uses of fields to initialize themselves, e.g.
1582 // foo(foo)
1583 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001584 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001585 for (unsigned i = 0; i < NumArgs; ++i) {
1586 SourceLocation L;
1587 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1588 // FIXME: Return true in the case when other fields are used before being
1589 // uninitialized. For example, let this field be the i'th field. When
1590 // initializing the i'th field, throw a warning if any of the >= i'th
1591 // fields are used, as they are not yet initialized.
1592 // Right now we are only handling the case where the i'th field uses
1593 // itself in its initializer.
1594 Diag(L, diag::warn_field_is_uninit);
1595 }
1596 }
1597
Eli Friedman8e1433b2009-07-29 19:44:27 +00001598 bool HasDependentArg = false;
1599 for (unsigned i = 0; i < NumArgs; i++)
1600 HasDependentArg |= Args[i]->isTypeDependent();
1601
Chandler Carruthd44c3102010-12-06 09:23:57 +00001602 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001603 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001604 // Can't check initialization for a member of dependent type or when
1605 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001606 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001607 RParenLoc,
1608 Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001609
John McCall31168b02011-06-15 23:02:42 +00001610 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00001611 } else {
1612 // Initialize the member.
1613 InitializedEntity MemberEntity =
1614 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1615 : InitializedEntity::InitializeMember(IndirectMember, 0);
1616 InitializationKind Kind =
1617 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001618
Chandler Carruthd44c3102010-12-06 09:23:57 +00001619 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1620
1621 ExprResult MemberInit =
1622 InitSeq.Perform(*this, MemberEntity, Kind,
1623 MultiExprArg(*this, Args, NumArgs), 0);
1624 if (MemberInit.isInvalid())
1625 return true;
1626
1627 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1628
1629 // C++0x [class.base.init]p7:
1630 // The initialization of each base and member constitutes a
1631 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001632 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001633 if (MemberInit.isInvalid())
1634 return true;
1635
1636 // If we are in a dependent context, template instantiation will
1637 // perform this type-checking again. Just save the arguments that we
1638 // received in a ParenListExpr.
1639 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1640 // of the information that we have about the member
1641 // initializer. However, deconstructing the ASTs is a dicey process,
1642 // and this approach is far more likely to get the corner cases right.
1643 if (CurContext->isDependentContext())
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001644 Init = new (Context) ParenListExpr(
1645 Context, LParenLoc, Args, NumArgs, RParenLoc,
1646 Member->getType().getNonReferenceType());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001647 else
1648 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001649 }
1650
Chandler Carruthd44c3102010-12-06 09:23:57 +00001651 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001652 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001653 IdLoc, LParenLoc, Init,
1654 RParenLoc);
1655 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001656 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001657 IdLoc, LParenLoc, Init,
1658 RParenLoc);
1659 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001660}
1661
John McCallfaf5fb42010-08-26 23:41:50 +00001662MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001663Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1664 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001665 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001666 SourceLocation LParenLoc,
1667 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001668 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001669 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1670 if (!LangOpts.CPlusPlus0x)
1671 return Diag(Loc, diag::err_delegation_0x_only)
1672 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001673
Alexis Huntc5575cc2011-02-26 19:13:13 +00001674 // Initialize the object.
1675 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1676 QualType(ClassDecl->getTypeForDecl(), 0));
1677 InitializationKind Kind =
1678 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1679
1680 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1681
1682 ExprResult DelegationInit =
1683 InitSeq.Perform(*this, DelegationEntity, Kind,
1684 MultiExprArg(*this, Args, NumArgs), 0);
1685 if (DelegationInit.isInvalid())
1686 return true;
1687
1688 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
Alexis Hunt6118d662011-05-04 05:57:24 +00001689 CXXConstructorDecl *Constructor
1690 = ConExpr->getConstructor();
Alexis Huntc5575cc2011-02-26 19:13:13 +00001691 assert(Constructor && "Delegating constructor with no target?");
1692
1693 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1694
1695 // C++0x [class.base.init]p7:
1696 // The initialization of each base and member constitutes a
1697 // full-expression.
1698 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1699 if (DelegationInit.isInvalid())
1700 return true;
1701
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001702 assert(!CurContext->isDependentContext());
Alexis Huntc5575cc2011-02-26 19:13:13 +00001703 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1704 DelegationInit.takeAs<Expr>(),
1705 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001706}
1707
1708MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001709Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001710 Expr **Args, unsigned NumArgs,
1711 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001712 CXXRecordDecl *ClassDecl,
1713 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001714 bool HasDependentArg = false;
1715 for (unsigned i = 0; i < NumArgs; i++)
1716 HasDependentArg |= Args[i]->isTypeDependent();
1717
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001718 SourceLocation BaseLoc
1719 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1720
1721 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1722 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1723 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1724
1725 // C++ [class.base.init]p2:
1726 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001727 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001728 // of that class, the mem-initializer is ill-formed. A
1729 // mem-initializer-list can initialize a base class using any
1730 // name that denotes that base class type.
1731 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1732
Douglas Gregor44e7df62011-01-04 00:32:56 +00001733 if (EllipsisLoc.isValid()) {
1734 // This is a pack expansion.
1735 if (!BaseType->containsUnexpandedParameterPack()) {
1736 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1737 << SourceRange(BaseLoc, RParenLoc);
1738
1739 EllipsisLoc = SourceLocation();
1740 }
1741 } else {
1742 // Check for any unexpanded parameter packs.
1743 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1744 return true;
1745
1746 for (unsigned I = 0; I != NumArgs; ++I)
1747 if (DiagnoseUnexpandedParameterPack(Args[I]))
1748 return true;
1749 }
1750
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001751 // Check for direct and virtual base classes.
1752 const CXXBaseSpecifier *DirectBaseSpec = 0;
1753 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1754 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001755 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1756 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001757 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1758 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001759
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001760 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1761 VirtualBaseSpec);
1762
1763 // C++ [base.class.init]p2:
1764 // Unless the mem-initializer-id names a nonstatic data member of the
1765 // constructor's class or a direct or virtual base of that class, the
1766 // mem-initializer is ill-formed.
1767 if (!DirectBaseSpec && !VirtualBaseSpec) {
1768 // If the class has any dependent bases, then it's possible that
1769 // one of those types will resolve to the same type as
1770 // BaseType. Therefore, just treat this as a dependent base
1771 // class initialization. FIXME: Should we try to check the
1772 // initialization anyway? It seems odd.
1773 if (ClassDecl->hasAnyDependentBases())
1774 Dependent = true;
1775 else
1776 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1777 << BaseType << Context.getTypeDeclType(ClassDecl)
1778 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1779 }
1780 }
1781
1782 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001783 // Can't check initialization for a base of dependent type or when
1784 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001785 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001786 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001787 RParenLoc, BaseType));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001788
John McCall31168b02011-06-15 23:02:42 +00001789 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001790
Alexis Hunt1d792652011-01-08 20:30:50 +00001791 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001792 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001793 LParenLoc,
1794 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001795 RParenLoc,
1796 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001797 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001798
1799 // C++ [base.class.init]p2:
1800 // If a mem-initializer-id is ambiguous because it designates both
1801 // a direct non-virtual base class and an inherited virtual base
1802 // class, the mem-initializer is ill-formed.
1803 if (DirectBaseSpec && VirtualBaseSpec)
1804 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001805 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001806
1807 CXXBaseSpecifier *BaseSpec
1808 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1809 if (!BaseSpec)
1810 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1811
1812 // Initialize the base.
1813 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001814 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001815 InitializationKind Kind =
1816 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1817
1818 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1819
John McCalldadc5752010-08-24 06:29:42 +00001820 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001821 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001822 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001823 if (BaseInit.isInvalid())
1824 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001825
1826 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001827
1828 // C++0x [class.base.init]p7:
1829 // The initialization of each base and member constitutes a
1830 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001831 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001832 if (BaseInit.isInvalid())
1833 return true;
1834
1835 // If we are in a dependent context, template instantiation will
1836 // perform this type-checking again. Just save the arguments that we
1837 // received in a ParenListExpr.
1838 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1839 // of the information that we have about the base
1840 // initializer. However, deconstructing the ASTs is a dicey process,
1841 // and this approach is far more likely to get the corner cases right.
1842 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001843 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001844 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
Manuel Klimekf2b4b692011-06-22 20:02:16 +00001845 RParenLoc, BaseType));
Alexis Hunt1d792652011-01-08 20:30:50 +00001846 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001847 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001848 LParenLoc,
1849 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001850 RParenLoc,
1851 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001852 }
1853
Alexis Hunt1d792652011-01-08 20:30:50 +00001854 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001855 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001856 LParenLoc,
1857 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001858 RParenLoc,
1859 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001860}
1861
Anders Carlsson1b00e242010-04-23 03:10:23 +00001862/// ImplicitInitializerKind - How an implicit base or member initializer should
1863/// initialize its base or member.
1864enum ImplicitInitializerKind {
1865 IIK_Default,
1866 IIK_Copy,
1867 IIK_Move
1868};
1869
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001870static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001871BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001872 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001873 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001874 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001875 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001876 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001877 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1878 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001879
John McCalldadc5752010-08-24 06:29:42 +00001880 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001881
1882 switch (ImplicitInitKind) {
1883 case IIK_Default: {
1884 InitializationKind InitKind
1885 = InitializationKind::CreateDefault(Constructor->getLocation());
1886 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1887 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001888 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001889 break;
1890 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001891
Anders Carlsson1b00e242010-04-23 03:10:23 +00001892 case IIK_Copy: {
1893 ParmVarDecl *Param = Constructor->getParamDecl(0);
1894 QualType ParamType = Param->getType().getNonReferenceType();
1895
1896 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001897 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001898 Constructor->getLocation(), ParamType,
1899 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001900
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001901 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001902 QualType ArgTy =
1903 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1904 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001905
1906 CXXCastPath BasePath;
1907 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001908 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1909 CK_UncheckedDerivedToBase,
1910 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001911
Anders Carlsson1b00e242010-04-23 03:10:23 +00001912 InitializationKind InitKind
1913 = InitializationKind::CreateDirect(Constructor->getLocation(),
1914 SourceLocation(), SourceLocation());
1915 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1916 &CopyCtorArg, 1);
1917 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001918 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001919 break;
1920 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001921
Anders Carlsson1b00e242010-04-23 03:10:23 +00001922 case IIK_Move:
1923 assert(false && "Unhandled initializer kind!");
1924 }
John McCallb268a282010-08-23 23:25:46 +00001925
Douglas Gregora40433a2010-12-07 00:41:46 +00001926 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001927 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001928 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001929
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001930 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001931 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001932 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1933 SourceLocation()),
1934 BaseSpec->isVirtual(),
1935 SourceLocation(),
1936 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001937 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001938 SourceLocation());
1939
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001940 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001941}
1942
Anders Carlsson3c1db572010-04-23 02:15:47 +00001943static bool
1944BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001945 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001946 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001947 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001948 if (Field->isInvalidDecl())
1949 return true;
1950
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001951 SourceLocation Loc = Constructor->getLocation();
1952
Anders Carlsson423f5d82010-04-23 16:04:08 +00001953 if (ImplicitInitKind == IIK_Copy) {
1954 ParmVarDecl *Param = Constructor->getParamDecl(0);
1955 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00001956
1957 // Suppress copying zero-width bitfields.
1958 if (const Expr *Width = Field->getBitWidth())
1959 if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1960 return false;
Anders Carlsson423f5d82010-04-23 16:04:08 +00001961
1962 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001963 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001964 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001965
1966 // Build a reference to this field within the parameter.
1967 CXXScopeSpec SS;
1968 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1969 Sema::LookupMemberName);
1970 MemberLookup.addDecl(Field, AS_public);
1971 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001972 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001973 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001974 ParamType, Loc,
1975 /*IsArrow=*/false,
1976 SS,
1977 /*FirstQualifierInScope=*/0,
1978 MemberLookup,
1979 /*TemplateArgs=*/0);
1980 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001981 return true;
1982
Douglas Gregor94f9a482010-05-05 05:51:00 +00001983 // When the field we are copying is an array, create index variables for
1984 // each dimension of the array. We use these index variables to subscript
1985 // the source array, and other clients (e.g., CodeGen) will perform the
1986 // necessary iteration with these index variables.
1987 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1988 QualType BaseType = Field->getType();
1989 QualType SizeType = SemaRef.Context.getSizeType();
1990 while (const ConstantArrayType *Array
1991 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1992 // Create the iteration variable for this array index.
1993 IdentifierInfo *IterationVarName = 0;
1994 {
1995 llvm::SmallString<8> Str;
1996 llvm::raw_svector_ostream OS(Str);
1997 OS << "__i" << IndexVariables.size();
1998 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1999 }
2000 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002001 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002002 IterationVarName, SizeType,
2003 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002004 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002005 IndexVariables.push_back(IterationVar);
2006
2007 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002008 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00002009 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002010 assert(!IterationVarRef.isInvalid() &&
2011 "Reference to invented variable cannot fail!");
2012
2013 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00002014 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002015 Loc,
John McCallb268a282010-08-23 23:25:46 +00002016 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002017 Loc);
2018 if (CopyCtorArg.isInvalid())
2019 return true;
2020
2021 BaseType = Array->getElementType();
2022 }
2023
2024 // Construct the entity that we will be initializing. For an array, this
2025 // will be first element in the array, which may require several levels
2026 // of array-subscript entities.
2027 llvm::SmallVector<InitializedEntity, 4> Entities;
2028 Entities.reserve(1 + IndexVariables.size());
2029 Entities.push_back(InitializedEntity::InitializeMember(Field));
2030 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2031 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2032 0,
2033 Entities.back()));
2034
2035 // Direct-initialize to use the copy constructor.
2036 InitializationKind InitKind =
2037 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2038
2039 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2040 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2041 &CopyCtorArgE, 1);
2042
John McCalldadc5752010-08-24 06:29:42 +00002043 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002044 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002045 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002046 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002047 if (MemberInit.isInvalid())
2048 return true;
2049
2050 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00002051 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002052 MemberInit.takeAs<Expr>(), Loc,
2053 IndexVariables.data(),
2054 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002055 return false;
2056 }
2057
Anders Carlsson423f5d82010-04-23 16:04:08 +00002058 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2059
Anders Carlsson3c1db572010-04-23 02:15:47 +00002060 QualType FieldBaseElementType =
2061 SemaRef.Context.getBaseElementType(Field->getType());
2062
Anders Carlsson3c1db572010-04-23 02:15:47 +00002063 if (FieldBaseElementType->isRecordType()) {
2064 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002065 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002066 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002067
2068 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002069 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002070 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002071
Douglas Gregora40433a2010-12-07 00:41:46 +00002072 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002073 if (MemberInit.isInvalid())
2074 return true;
2075
2076 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002077 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002078 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00002079 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002080 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002081 return false;
2082 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002083
Alexis Hunt8b455182011-05-17 00:19:05 +00002084 if (!Field->getParent()->isUnion()) {
2085 if (FieldBaseElementType->isReferenceType()) {
2086 SemaRef.Diag(Constructor->getLocation(),
2087 diag::err_uninitialized_member_in_ctor)
2088 << (int)Constructor->isImplicit()
2089 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2090 << 0 << Field->getDeclName();
2091 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2092 return true;
2093 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002094
Alexis Hunt8b455182011-05-17 00:19:05 +00002095 if (FieldBaseElementType.isConstQualified()) {
2096 SemaRef.Diag(Constructor->getLocation(),
2097 diag::err_uninitialized_member_in_ctor)
2098 << (int)Constructor->isImplicit()
2099 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2100 << 1 << Field->getDeclName();
2101 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2102 return true;
2103 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002104 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002105
John McCall31168b02011-06-15 23:02:42 +00002106 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2107 FieldBaseElementType->isObjCRetainableType() &&
2108 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2109 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2110 // Instant objects:
2111 // Default-initialize Objective-C pointers to NULL.
2112 CXXMemberInit
2113 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2114 Loc, Loc,
2115 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2116 Loc);
2117 return false;
2118 }
2119
Anders Carlsson3c1db572010-04-23 02:15:47 +00002120 // Nothing to initialize.
2121 CXXMemberInit = 0;
2122 return false;
2123}
John McCallbc83b3f2010-05-20 23:23:51 +00002124
2125namespace {
2126struct BaseAndFieldInfo {
2127 Sema &S;
2128 CXXConstructorDecl *Ctor;
2129 bool AnyErrorsInInits;
2130 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002131 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2132 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002133
2134 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2135 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2136 // FIXME: Handle implicit move constructors.
2137 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2138 IIK = IIK_Copy;
2139 else
2140 IIK = IIK_Default;
2141 }
2142};
2143}
2144
Richard Smith938f40b2011-06-11 17:19:42 +00002145static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
John McCallbc83b3f2010-05-20 23:23:51 +00002146 FieldDecl *Top, FieldDecl *Field) {
2147
Chandler Carruth139e9622010-06-30 02:59:29 +00002148 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002149 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002150 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002151 return false;
2152 }
2153
Richard Smith938f40b2011-06-11 17:19:42 +00002154 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2155 // has a brace-or-equal-initializer, the entity is initialized as specified
2156 // in [dcl.init].
2157 if (Field->hasInClassInitializer()) {
2158 Info.AllToInit.push_back(
2159 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2160 SourceLocation(),
2161 SourceLocation(), 0,
2162 SourceLocation()));
2163 return false;
2164 }
2165
John McCallbc83b3f2010-05-20 23:23:51 +00002166 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2167 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2168 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002169 CXXRecordDecl *FieldClassDecl
2170 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002171
2172 // Even though union members never have non-trivial default
2173 // constructions in C++03, we still build member initializers for aggregate
2174 // record types which can be union members, and C++0x allows non-trivial
2175 // default constructors for union members, so we ensure that only one
2176 // member is initialized for these.
2177 if (FieldClassDecl->isUnion()) {
2178 // First check for an explicit initializer for one field.
2179 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2180 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002181 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002182 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002183
2184 // Once we've initialized a field of an anonymous union, the union
2185 // field in the class is also initialized, so exit immediately.
2186 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002187 } else if ((*FA)->isAnonymousStructOrUnion()) {
Richard Smith938f40b2011-06-11 17:19:42 +00002188 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002189 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002190 }
2191 }
2192
2193 // Fallthrough and construct a default initializer for the union as
2194 // a whole, which can call its default constructor if such a thing exists
2195 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2196 // behavior going forward with C++0x, when anonymous unions there are
2197 // finalized, we should revisit this.
2198 } else {
2199 // For structs, we simply descend through to initialize all members where
2200 // necessary.
2201 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2202 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Richard Smith938f40b2011-06-11 17:19:42 +00002203 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
Chandler Carruth139e9622010-06-30 02:59:29 +00002204 return true;
2205 }
2206 }
John McCallbc83b3f2010-05-20 23:23:51 +00002207 }
2208
2209 // Don't try to build an implicit initializer if there were semantic
2210 // errors in any of the initializers (and therefore we might be
2211 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002212 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002213 return false;
2214
Alexis Hunt1d792652011-01-08 20:30:50 +00002215 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002216 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2217 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002218
Francois Pichetd583da02010-12-04 09:14:42 +00002219 if (Init)
2220 Info.AllToInit.push_back(Init);
2221
John McCallbc83b3f2010-05-20 23:23:51 +00002222 return false;
2223}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002224
2225bool
2226Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2227 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002228 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002229 Constructor->setNumCtorInitializers(1);
2230 CXXCtorInitializer **initializer =
2231 new (Context) CXXCtorInitializer*[1];
2232 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2233 Constructor->setCtorInitializers(initializer);
2234
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002235 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2236 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2237 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2238 }
2239
Alexis Hunte2622992011-05-05 00:05:47 +00002240 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002241
Alexis Hunt61bc1732011-05-01 07:04:31 +00002242 return false;
2243}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002244
John McCall1b1a1db2011-06-17 00:18:42 +00002245bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2246 CXXCtorInitializer **Initializers,
2247 unsigned NumInitializers,
2248 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002249 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002250 // Just store the initializers as written, they will be checked during
2251 // instantiation.
2252 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002253 Constructor->setNumCtorInitializers(NumInitializers);
2254 CXXCtorInitializer **baseOrMemberInitializers =
2255 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002256 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002257 NumInitializers * sizeof(CXXCtorInitializer*));
2258 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002259 }
2260
2261 return false;
2262 }
2263
John McCallbc83b3f2010-05-20 23:23:51 +00002264 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002265
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002266 // We need to build the initializer AST according to order of construction
2267 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002268 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002269 if (!ClassDecl)
2270 return true;
2271
Eli Friedman9cf6b592009-11-09 19:20:36 +00002272 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002273
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002274 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002275 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002276
2277 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002278 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002279 else
Francois Pichetd583da02010-12-04 09:14:42 +00002280 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002281 }
2282
Anders Carlsson43c64af2010-04-21 19:52:01 +00002283 // Keep track of the direct virtual bases.
2284 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2285 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2286 E = ClassDecl->bases_end(); I != E; ++I) {
2287 if (I->isVirtual())
2288 DirectVBases.insert(I);
2289 }
2290
Anders Carlssondb0a9652010-04-02 06:26:44 +00002291 // Push virtual bases before others.
2292 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2293 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2294
Alexis Hunt1d792652011-01-08 20:30:50 +00002295 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002296 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2297 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002298 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002299 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002300 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002301 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002302 VBase, IsInheritedVirtualBase,
2303 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002304 HadError = true;
2305 continue;
2306 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002307
John McCallbc83b3f2010-05-20 23:23:51 +00002308 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002309 }
2310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
John McCallbc83b3f2010-05-20 23:23:51 +00002312 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002313 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2314 E = ClassDecl->bases_end(); Base != E; ++Base) {
2315 // Virtuals are in the virtual base list and already constructed.
2316 if (Base->isVirtual())
2317 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002318
Alexis Hunt1d792652011-01-08 20:30:50 +00002319 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002320 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2321 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002322 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002323 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002324 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002325 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002326 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002327 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002328 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002329 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002330
John McCallbc83b3f2010-05-20 23:23:51 +00002331 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002332 }
2333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
John McCallbc83b3f2010-05-20 23:23:51 +00002335 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002336 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002337 E = ClassDecl->field_end(); Field != E; ++Field) {
2338 if ((*Field)->getType()->isIncompleteArrayType()) {
2339 assert(ClassDecl->hasFlexibleArrayMember() &&
2340 "Incomplete array type is not valid");
2341 continue;
2342 }
Richard Smith938f40b2011-06-11 17:19:42 +00002343 if (CollectFieldInitializer(*this, Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002344 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
John McCallbc83b3f2010-05-20 23:23:51 +00002347 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002348 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002349 Constructor->setNumCtorInitializers(NumInitializers);
2350 CXXCtorInitializer **baseOrMemberInitializers =
2351 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002352 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002353 NumInitializers * sizeof(CXXCtorInitializer*));
2354 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002355
John McCalla6309952010-03-16 21:39:52 +00002356 // Constructors implicitly reference the base and member
2357 // destructors.
2358 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2359 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002360 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002361
2362 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002363}
2364
Eli Friedman952c15d2009-07-21 19:28:10 +00002365static void *GetKeyForTopLevelField(FieldDecl *Field) {
2366 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002367 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002368 if (RT->getDecl()->isAnonymousStructOrUnion())
2369 return static_cast<void *>(RT->getDecl());
2370 }
2371 return static_cast<void *>(Field);
2372}
2373
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002374static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002375 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002376}
2377
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002378static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002379 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002380 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002381 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002382
Eli Friedman952c15d2009-07-21 19:28:10 +00002383 // For fields injected into the class via declaration of an anonymous union,
2384 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002385 FieldDecl *Field = Member->getAnyMember();
2386
John McCall23eebd92010-04-10 09:28:51 +00002387 // If the field is a member of an anonymous struct or union, our key
2388 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002389 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002390 if (RD->isAnonymousStructOrUnion()) {
2391 while (true) {
2392 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2393 if (Parent->isAnonymousStructOrUnion())
2394 RD = Parent;
2395 else
2396 break;
2397 }
2398
Anders Carlsson83ac3122010-03-30 16:19:37 +00002399 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002400 }
Mike Stump11289f42009-09-09 15:08:12 +00002401
Anders Carlssona942dcd2010-03-30 15:39:27 +00002402 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002403}
2404
Anders Carlssone857b292010-04-02 03:37:03 +00002405static void
2406DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002407 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002408 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002409 unsigned NumInits) {
2410 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002411 return;
Mike Stump11289f42009-09-09 15:08:12 +00002412
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002413 // Don't check initializers order unless the warning is enabled at the
2414 // location of at least one initializer.
2415 bool ShouldCheckOrder = false;
2416 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002417 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002418 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2419 Init->getSourceLocation())
2420 != Diagnostic::Ignored) {
2421 ShouldCheckOrder = true;
2422 break;
2423 }
2424 }
2425 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002426 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002427
John McCallbb7b6582010-04-10 07:37:23 +00002428 // Build the list of bases and members in the order that they'll
2429 // actually be initialized. The explicit initializers should be in
2430 // this same order but may be missing things.
2431 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002432
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002433 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2434
John McCallbb7b6582010-04-10 07:37:23 +00002435 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002436 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002437 ClassDecl->vbases_begin(),
2438 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002439 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002440
John McCallbb7b6582010-04-10 07:37:23 +00002441 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002442 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002443 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002444 if (Base->isVirtual())
2445 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002446 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002447 }
Mike Stump11289f42009-09-09 15:08:12 +00002448
John McCallbb7b6582010-04-10 07:37:23 +00002449 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002450 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2451 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002452 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002453
John McCallbb7b6582010-04-10 07:37:23 +00002454 unsigned NumIdealInits = IdealInitKeys.size();
2455 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002456
Alexis Hunt1d792652011-01-08 20:30:50 +00002457 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002458 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002459 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002460 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002461
2462 // Scan forward to try to find this initializer in the idealized
2463 // initializers list.
2464 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2465 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002466 break;
John McCallbb7b6582010-04-10 07:37:23 +00002467
2468 // If we didn't find this initializer, it must be because we
2469 // scanned past it on a previous iteration. That can only
2470 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002471 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002472 Sema::SemaDiagnosticBuilder D =
2473 SemaRef.Diag(PrevInit->getSourceLocation(),
2474 diag::warn_initializer_out_of_order);
2475
Francois Pichetd583da02010-12-04 09:14:42 +00002476 if (PrevInit->isAnyMemberInitializer())
2477 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002478 else
2479 D << 1 << PrevInit->getBaseClassInfo()->getType();
2480
Francois Pichetd583da02010-12-04 09:14:42 +00002481 if (Init->isAnyMemberInitializer())
2482 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002483 else
2484 D << 1 << Init->getBaseClassInfo()->getType();
2485
2486 // Move back to the initializer's location in the ideal list.
2487 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2488 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002489 break;
John McCallbb7b6582010-04-10 07:37:23 +00002490
2491 assert(IdealIndex != NumIdealInits &&
2492 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002493 }
John McCallbb7b6582010-04-10 07:37:23 +00002494
2495 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002496 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002497}
2498
John McCall23eebd92010-04-10 09:28:51 +00002499namespace {
2500bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002501 CXXCtorInitializer *Init,
2502 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002503 if (!PrevInit) {
2504 PrevInit = Init;
2505 return false;
2506 }
2507
2508 if (FieldDecl *Field = Init->getMember())
2509 S.Diag(Init->getSourceLocation(),
2510 diag::err_multiple_mem_initialization)
2511 << Field->getDeclName()
2512 << Init->getSourceRange();
2513 else {
John McCall424cec92011-01-19 06:33:43 +00002514 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002515 assert(BaseClass && "neither field nor base");
2516 S.Diag(Init->getSourceLocation(),
2517 diag::err_multiple_base_initialization)
2518 << QualType(BaseClass, 0)
2519 << Init->getSourceRange();
2520 }
2521 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2522 << 0 << PrevInit->getSourceRange();
2523
2524 return true;
2525}
2526
Alexis Hunt1d792652011-01-08 20:30:50 +00002527typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002528typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2529
2530bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002531 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002532 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002533 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002534 RecordDecl *Parent = Field->getParent();
2535 if (!Parent->isAnonymousStructOrUnion())
2536 return false;
2537
2538 NamedDecl *Child = Field;
2539 do {
2540 if (Parent->isUnion()) {
2541 UnionEntry &En = Unions[Parent];
2542 if (En.first && En.first != Child) {
2543 S.Diag(Init->getSourceLocation(),
2544 diag::err_multiple_mem_union_initialization)
2545 << Field->getDeclName()
2546 << Init->getSourceRange();
2547 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2548 << 0 << En.second->getSourceRange();
2549 return true;
2550 } else if (!En.first) {
2551 En.first = Child;
2552 En.second = Init;
2553 }
2554 }
2555
2556 Child = Parent;
2557 Parent = cast<RecordDecl>(Parent->getDeclContext());
2558 } while (Parent->isAnonymousStructOrUnion());
2559
2560 return false;
2561}
2562}
2563
Anders Carlssone857b292010-04-02 03:37:03 +00002564/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002565void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002566 SourceLocation ColonLoc,
2567 MemInitTy **meminits, unsigned NumMemInits,
2568 bool AnyErrors) {
2569 if (!ConstructorDecl)
2570 return;
2571
2572 AdjustDeclIfTemplate(ConstructorDecl);
2573
2574 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002575 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002576
2577 if (!Constructor) {
2578 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2579 return;
2580 }
2581
Alexis Hunt1d792652011-01-08 20:30:50 +00002582 CXXCtorInitializer **MemInits =
2583 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002584
2585 // Mapping for the duplicate initializers check.
2586 // For member initializers, this is keyed with a FieldDecl*.
2587 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002588 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002589
2590 // Mapping for the inconsistent anonymous-union initializers check.
2591 RedundantUnionMap MemberUnions;
2592
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002593 bool HadError = false;
2594 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002595 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002596
Abramo Bagnara341d7832010-05-26 18:09:23 +00002597 // Set the source order index.
2598 Init->setSourceOrder(i);
2599
Francois Pichetd583da02010-12-04 09:14:42 +00002600 if (Init->isAnyMemberInitializer()) {
2601 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002602 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2603 CheckRedundantUnionInit(*this, Init, MemberUnions))
2604 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002605 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002606 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2607 if (CheckRedundantInit(*this, Init, Members[Key]))
2608 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002609 } else {
2610 assert(Init->isDelegatingInitializer());
2611 // This must be the only initializer
2612 if (i != 0 || NumMemInits > 1) {
2613 Diag(MemInits[0]->getSourceLocation(),
2614 diag::err_delegating_initializer_alone)
2615 << MemInits[0]->getSourceRange();
2616 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00002617 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00002618 }
Alexis Hunt6118d662011-05-04 05:57:24 +00002619 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002620 // Return immediately as the initializer is set.
2621 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002622 }
Anders Carlssone857b292010-04-02 03:37:03 +00002623 }
2624
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002625 if (HadError)
2626 return;
2627
Anders Carlssone857b292010-04-02 03:37:03 +00002628 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002629
Alexis Hunt1d792652011-01-08 20:30:50 +00002630 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002631}
2632
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002633void
John McCalla6309952010-03-16 21:39:52 +00002634Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2635 CXXRecordDecl *ClassDecl) {
2636 // Ignore dependent contexts.
2637 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002638 return;
John McCall1064d7e2010-03-16 05:22:47 +00002639
2640 // FIXME: all the access-control diagnostics are positioned on the
2641 // field/base declaration. That's probably good; that said, the
2642 // user might reasonably want to know why the destructor is being
2643 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002644
Anders Carlssondee9a302009-11-17 04:44:12 +00002645 // Non-static data members.
2646 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2647 E = ClassDecl->field_end(); I != E; ++I) {
2648 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002649 if (Field->isInvalidDecl())
2650 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002651 QualType FieldType = Context.getBaseElementType(Field->getType());
2652
2653 const RecordType* RT = FieldType->getAs<RecordType>();
2654 if (!RT)
2655 continue;
2656
2657 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002658 if (FieldClassDecl->isInvalidDecl())
2659 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002660 if (FieldClassDecl->hasTrivialDestructor())
2661 continue;
2662
Douglas Gregore71edda2010-07-01 22:47:18 +00002663 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002664 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002665 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002666 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002667 << Field->getDeclName()
2668 << FieldType);
2669
John McCalla6309952010-03-16 21:39:52 +00002670 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002671 }
2672
John McCall1064d7e2010-03-16 05:22:47 +00002673 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2674
Anders Carlssondee9a302009-11-17 04:44:12 +00002675 // Bases.
2676 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2677 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002678 // Bases are always records in a well-formed non-dependent class.
2679 const RecordType *RT = Base->getType()->getAs<RecordType>();
2680
2681 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002682 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002683 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002684
John McCall1064d7e2010-03-16 05:22:47 +00002685 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002686 // If our base class is invalid, we probably can't get its dtor anyway.
2687 if (BaseClassDecl->isInvalidDecl())
2688 continue;
2689 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002690 if (BaseClassDecl->hasTrivialDestructor())
2691 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002692
Douglas Gregore71edda2010-07-01 22:47:18 +00002693 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002694 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002695
2696 // FIXME: caret should be on the start of the class name
2697 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002698 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002699 << Base->getType()
2700 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002701
John McCalla6309952010-03-16 21:39:52 +00002702 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002703 }
2704
2705 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002706 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2707 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002708
2709 // Bases are always records in a well-formed non-dependent class.
2710 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2711
2712 // Ignore direct virtual bases.
2713 if (DirectVirtualBases.count(RT))
2714 continue;
2715
John McCall1064d7e2010-03-16 05:22:47 +00002716 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002717 // If our base class is invalid, we probably can't get its dtor anyway.
2718 if (BaseClassDecl->isInvalidDecl())
2719 continue;
2720 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002721 if (BaseClassDecl->hasTrivialDestructor())
2722 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002723
Douglas Gregore71edda2010-07-01 22:47:18 +00002724 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002725 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002726 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002727 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002728 << VBase->getType());
2729
John McCalla6309952010-03-16 21:39:52 +00002730 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002731 }
2732}
2733
John McCall48871652010-08-21 09:40:31 +00002734void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002735 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002736 return;
Mike Stump11289f42009-09-09 15:08:12 +00002737
Mike Stump11289f42009-09-09 15:08:12 +00002738 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002739 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002740 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002741}
2742
Mike Stump11289f42009-09-09 15:08:12 +00002743bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002744 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002745 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002746 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002747 else
John McCall02db245d2010-08-18 09:41:07 +00002748 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002749}
2750
Anders Carlssoneabf7702009-08-27 00:13:57 +00002751bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002752 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002753 if (!getLangOptions().CPlusPlus)
2754 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002755
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002756 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002757 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002758
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002759 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002760 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002761 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002762 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002763
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002764 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002765 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002766 }
Mike Stump11289f42009-09-09 15:08:12 +00002767
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002768 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002769 if (!RT)
2770 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002771
John McCall67da35c2010-02-04 22:26:26 +00002772 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002773
John McCall02db245d2010-08-18 09:41:07 +00002774 // We can't answer whether something is abstract until it has a
2775 // definition. If it's currently being defined, we'll walk back
2776 // over all the declarations when we have a full definition.
2777 const CXXRecordDecl *Def = RD->getDefinition();
2778 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002779 return false;
2780
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002781 if (!RD->isAbstract())
2782 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002783
Anders Carlssoneabf7702009-08-27 00:13:57 +00002784 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002785 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002786
John McCall02db245d2010-08-18 09:41:07 +00002787 return true;
2788}
2789
2790void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2791 // Check if we've already emitted the list of pure virtual functions
2792 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002793 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002794 return;
Mike Stump11289f42009-09-09 15:08:12 +00002795
Douglas Gregor4165bd62010-03-23 23:47:56 +00002796 CXXFinalOverriderMap FinalOverriders;
2797 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002798
Anders Carlssona2f74f32010-06-03 01:00:02 +00002799 // Keep a set of seen pure methods so we won't diagnose the same method
2800 // more than once.
2801 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2802
Douglas Gregor4165bd62010-03-23 23:47:56 +00002803 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2804 MEnd = FinalOverriders.end();
2805 M != MEnd;
2806 ++M) {
2807 for (OverridingMethods::iterator SO = M->second.begin(),
2808 SOEnd = M->second.end();
2809 SO != SOEnd; ++SO) {
2810 // C++ [class.abstract]p4:
2811 // A class is abstract if it contains or inherits at least one
2812 // pure virtual function for which the final overrider is pure
2813 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002814
Douglas Gregor4165bd62010-03-23 23:47:56 +00002815 //
2816 if (SO->second.size() != 1)
2817 continue;
2818
2819 if (!SO->second.front().Method->isPure())
2820 continue;
2821
Anders Carlssona2f74f32010-06-03 01:00:02 +00002822 if (!SeenPureMethods.insert(SO->second.front().Method))
2823 continue;
2824
Douglas Gregor4165bd62010-03-23 23:47:56 +00002825 Diag(SO->second.front().Method->getLocation(),
2826 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002827 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002828 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002829 }
2830
2831 if (!PureVirtualClassDiagSet)
2832 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2833 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002834}
2835
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002836namespace {
John McCall02db245d2010-08-18 09:41:07 +00002837struct AbstractUsageInfo {
2838 Sema &S;
2839 CXXRecordDecl *Record;
2840 CanQualType AbstractType;
2841 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002842
John McCall02db245d2010-08-18 09:41:07 +00002843 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2844 : S(S), Record(Record),
2845 AbstractType(S.Context.getCanonicalType(
2846 S.Context.getTypeDeclType(Record))),
2847 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002848
John McCall02db245d2010-08-18 09:41:07 +00002849 void DiagnoseAbstractType() {
2850 if (Invalid) return;
2851 S.DiagnoseAbstractType(Record);
2852 Invalid = true;
2853 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002854
John McCall02db245d2010-08-18 09:41:07 +00002855 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2856};
2857
2858struct CheckAbstractUsage {
2859 AbstractUsageInfo &Info;
2860 const NamedDecl *Ctx;
2861
2862 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2863 : Info(Info), Ctx(Ctx) {}
2864
2865 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2866 switch (TL.getTypeLocClass()) {
2867#define ABSTRACT_TYPELOC(CLASS, PARENT)
2868#define TYPELOC(CLASS, PARENT) \
2869 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2870#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002871 }
John McCall02db245d2010-08-18 09:41:07 +00002872 }
Mike Stump11289f42009-09-09 15:08:12 +00002873
John McCall02db245d2010-08-18 09:41:07 +00002874 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2875 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2876 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002877 if (!TL.getArg(I))
2878 continue;
2879
John McCall02db245d2010-08-18 09:41:07 +00002880 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2881 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002882 }
John McCall02db245d2010-08-18 09:41:07 +00002883 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002884
John McCall02db245d2010-08-18 09:41:07 +00002885 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2886 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
John McCall02db245d2010-08-18 09:41:07 +00002889 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2890 // Visit the type parameters from a permissive context.
2891 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2892 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2893 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2894 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2895 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2896 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002897 }
John McCall02db245d2010-08-18 09:41:07 +00002898 }
Mike Stump11289f42009-09-09 15:08:12 +00002899
John McCall02db245d2010-08-18 09:41:07 +00002900 // Visit pointee types from a permissive context.
2901#define CheckPolymorphic(Type) \
2902 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2903 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2904 }
2905 CheckPolymorphic(PointerTypeLoc)
2906 CheckPolymorphic(ReferenceTypeLoc)
2907 CheckPolymorphic(MemberPointerTypeLoc)
2908 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002909
John McCall02db245d2010-08-18 09:41:07 +00002910 /// Handle all the types we haven't given a more specific
2911 /// implementation for above.
2912 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2913 // Every other kind of type that we haven't called out already
2914 // that has an inner type is either (1) sugar or (2) contains that
2915 // inner type in some way as a subobject.
2916 if (TypeLoc Next = TL.getNextTypeLoc())
2917 return Visit(Next, Sel);
2918
2919 // If there's no inner type and we're in a permissive context,
2920 // don't diagnose.
2921 if (Sel == Sema::AbstractNone) return;
2922
2923 // Check whether the type matches the abstract type.
2924 QualType T = TL.getType();
2925 if (T->isArrayType()) {
2926 Sel = Sema::AbstractArrayType;
2927 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002928 }
John McCall02db245d2010-08-18 09:41:07 +00002929 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2930 if (CT != Info.AbstractType) return;
2931
2932 // It matched; do some magic.
2933 if (Sel == Sema::AbstractArrayType) {
2934 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2935 << T << TL.getSourceRange();
2936 } else {
2937 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2938 << Sel << T << TL.getSourceRange();
2939 }
2940 Info.DiagnoseAbstractType();
2941 }
2942};
2943
2944void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2945 Sema::AbstractDiagSelID Sel) {
2946 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2947}
2948
2949}
2950
2951/// Check for invalid uses of an abstract type in a method declaration.
2952static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2953 CXXMethodDecl *MD) {
2954 // No need to do the check on definitions, which require that
2955 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002956 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00002957 return;
2958
2959 // For safety's sake, just ignore it if we don't have type source
2960 // information. This should never happen for non-implicit methods,
2961 // but...
2962 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2963 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2964}
2965
2966/// Check for invalid uses of an abstract type within a class definition.
2967static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2968 CXXRecordDecl *RD) {
2969 for (CXXRecordDecl::decl_iterator
2970 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2971 Decl *D = *I;
2972 if (D->isImplicit()) continue;
2973
2974 // Methods and method templates.
2975 if (isa<CXXMethodDecl>(D)) {
2976 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2977 } else if (isa<FunctionTemplateDecl>(D)) {
2978 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2979 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2980
2981 // Fields and static variables.
2982 } else if (isa<FieldDecl>(D)) {
2983 FieldDecl *FD = cast<FieldDecl>(D);
2984 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2985 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2986 } else if (isa<VarDecl>(D)) {
2987 VarDecl *VD = cast<VarDecl>(D);
2988 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2989 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2990
2991 // Nested classes and class templates.
2992 } else if (isa<CXXRecordDecl>(D)) {
2993 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2994 } else if (isa<ClassTemplateDecl>(D)) {
2995 CheckAbstractClassUsage(Info,
2996 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2997 }
2998 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002999}
3000
Douglas Gregorc99f1552009-12-03 18:33:45 +00003001/// \brief Perform semantic checks on a class definition that has been
3002/// completing, introducing implicitly-declared members, checking for
3003/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003004void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003005 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003006 return;
3007
John McCall02db245d2010-08-18 09:41:07 +00003008 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3009 AbstractUsageInfo Info(*this, Record);
3010 CheckAbstractClassUsage(Info, Record);
3011 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003012
3013 // If this is not an aggregate type and has no user-declared constructor,
3014 // complain about any non-static data members of reference or const scalar
3015 // type, since they will never get initializers.
3016 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3017 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3018 bool Complained = false;
3019 for (RecordDecl::field_iterator F = Record->field_begin(),
3020 FEnd = Record->field_end();
3021 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00003022 if (F->hasInClassInitializer())
3023 continue;
3024
Douglas Gregor454a5b62010-04-15 00:00:53 +00003025 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003026 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003027 if (!Complained) {
3028 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3029 << Record->getTagKind() << Record;
3030 Complained = true;
3031 }
3032
3033 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3034 << F->getType()->isReferenceType()
3035 << F->getDeclName();
3036 }
3037 }
3038 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003039
Anders Carlssone771e762011-01-25 18:08:22 +00003040 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003041 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003042
3043 if (Record->getIdentifier()) {
3044 // C++ [class.mem]p13:
3045 // If T is the name of a class, then each of the following shall have a
3046 // name different from T:
3047 // - every member of every anonymous union that is a member of class T.
3048 //
3049 // C++ [class.mem]p14:
3050 // In addition, if class T has a user-declared constructor (12.1), every
3051 // non-static data member of class T shall have a name different from T.
3052 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003053 R.first != R.second; ++R.first) {
3054 NamedDecl *D = *R.first;
3055 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3056 isa<IndirectFieldDecl>(D)) {
3057 Diag(D->getLocation(), diag::err_member_name_of_class)
3058 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003059 break;
3060 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003061 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003062 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003063
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003064 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003065 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003066 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003067 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003068 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3069 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3070 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003071
3072 // See if a method overloads virtual methods in a base
3073 /// class without overriding any.
3074 if (!Record->isDependentType()) {
3075 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3076 MEnd = Record->method_end();
3077 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003078 if (!(*M)->isStatic())
3079 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003080 }
3081 }
Sebastian Redl08905022011-02-05 19:23:19 +00003082
3083 // Declare inherited constructors. We do this eagerly here because:
3084 // - The standard requires an eager diagnostic for conflicting inherited
3085 // constructors from different classes.
3086 // - The lazy declaration of the other implicit constructors is so as to not
3087 // waste space and performance on classes that are not meant to be
3088 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3089 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003090 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003091
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003092 if (!Record->isDependentType())
3093 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003094}
3095
3096void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003097 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3098 ME = Record->method_end();
3099 MI != ME; ++MI) {
3100 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3101 switch (getSpecialMember(*MI)) {
3102 case CXXDefaultConstructor:
3103 CheckExplicitlyDefaultedDefaultConstructor(
3104 cast<CXXConstructorDecl>(*MI));
3105 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003106
Alexis Huntf91729462011-05-12 22:46:25 +00003107 case CXXDestructor:
3108 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3109 break;
3110
3111 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003112 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3113 break;
3114
Alexis Huntf91729462011-05-12 22:46:25 +00003115 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003116 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003117 break;
3118
Alexis Hunt119c10e2011-05-25 23:16:36 +00003119 case CXXMoveConstructor:
3120 case CXXMoveAssignment:
3121 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3122 break;
3123
Alexis Huntf91729462011-05-12 22:46:25 +00003124 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00003125 // FIXME: Do moves once they exist
Alexis Huntf91729462011-05-12 22:46:25 +00003126 llvm_unreachable("non-special member explicitly defaulted!");
3127 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003128 }
3129 }
3130
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003131}
3132
3133void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3134 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3135
3136 // Whether this was the first-declared instance of the constructor.
3137 // This affects whether we implicitly add an exception spec (and, eventually,
3138 // constexpr). It is also ill-formed to explicitly default a constructor such
3139 // that it would be deleted. (C++0x [decl.fct.def.default])
3140 bool First = CD == CD->getCanonicalDecl();
3141
Alexis Hunt913820d2011-05-13 06:10:58 +00003142 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003143 if (CD->getNumParams() != 0) {
3144 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3145 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003146 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003147 }
3148
3149 ImplicitExceptionSpecification Spec
3150 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3151 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003152 if (EPI.ExceptionSpecType == EST_Delayed) {
3153 // Exception specification depends on some deferred part of the class. We'll
3154 // try again when the class's definition has been fully processed.
3155 return;
3156 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003157 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3158 *ExceptionType = Context.getFunctionType(
3159 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3160
3161 if (CtorType->hasExceptionSpec()) {
3162 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003163 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003164 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003165 PDiag(),
3166 ExceptionType, SourceLocation(),
3167 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003168 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003169 }
3170 } else if (First) {
3171 // We set the declaration to have the computed exception spec here.
3172 // We know there are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003173 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003174 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3175 }
Alexis Huntb3153022011-05-12 03:51:48 +00003176
Alexis Hunt913820d2011-05-13 06:10:58 +00003177 if (HadError) {
3178 CD->setInvalidDecl();
3179 return;
3180 }
3181
Alexis Huntb3153022011-05-12 03:51:48 +00003182 if (ShouldDeleteDefaultConstructor(CD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003183 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003184 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003185 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003186 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003187 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003188 CD->setInvalidDecl();
3189 }
3190 }
3191}
3192
3193void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3194 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3195
3196 // Whether this was the first-declared instance of the constructor.
3197 bool First = CD == CD->getCanonicalDecl();
3198
3199 bool HadError = false;
3200 if (CD->getNumParams() != 1) {
3201 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3202 << CD->getSourceRange();
3203 HadError = true;
3204 }
3205
3206 ImplicitExceptionSpecification Spec(Context);
3207 bool Const;
3208 llvm::tie(Spec, Const) =
3209 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3210
3211 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3212 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3213 *ExceptionType = Context.getFunctionType(
3214 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3215
3216 // Check for parameter type matching.
3217 // This is a copy ctor so we know it's a cv-qualified reference to T.
3218 QualType ArgType = CtorType->getArgType(0);
3219 if (ArgType->getPointeeType().isVolatileQualified()) {
3220 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3221 HadError = true;
3222 }
3223 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3224 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3225 HadError = true;
3226 }
3227
3228 if (CtorType->hasExceptionSpec()) {
3229 if (CheckEquivalentExceptionSpec(
3230 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003231 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003232 PDiag(),
3233 ExceptionType, SourceLocation(),
3234 CtorType, CD->getLocation())) {
3235 HadError = true;
3236 }
3237 } else if (First) {
3238 // We set the declaration to have the computed exception spec here.
3239 // We duplicate the one parameter type.
Alexis Huntc9a55732011-05-14 05:23:28 +00003240 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt913820d2011-05-13 06:10:58 +00003241 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3242 }
3243
3244 if (HadError) {
3245 CD->setInvalidDecl();
3246 return;
3247 }
3248
3249 if (ShouldDeleteCopyConstructor(CD)) {
3250 if (First) {
3251 CD->setDeletedAsWritten();
3252 } else {
3253 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003254 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003255 CD->setInvalidDecl();
3256 }
Alexis Huntb3153022011-05-12 03:51:48 +00003257 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003258}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003259
Alexis Huntc9a55732011-05-14 05:23:28 +00003260void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3261 assert(MD->isExplicitlyDefaulted());
3262
3263 // Whether this was the first-declared instance of the operator
3264 bool First = MD == MD->getCanonicalDecl();
3265
3266 bool HadError = false;
3267 if (MD->getNumParams() != 1) {
3268 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3269 << MD->getSourceRange();
3270 HadError = true;
3271 }
3272
3273 QualType ReturnType =
3274 MD->getType()->getAs<FunctionType>()->getResultType();
3275 if (!ReturnType->isLValueReferenceType() ||
3276 !Context.hasSameType(
3277 Context.getCanonicalType(ReturnType->getPointeeType()),
3278 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3279 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3280 HadError = true;
3281 }
3282
3283 ImplicitExceptionSpecification Spec(Context);
3284 bool Const;
3285 llvm::tie(Spec, Const) =
3286 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3287
3288 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3289 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3290 *ExceptionType = Context.getFunctionType(
3291 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3292
Alexis Huntc9a55732011-05-14 05:23:28 +00003293 QualType ArgType = OperType->getArgType(0);
Alexis Hunt604aeb32011-05-17 20:44:43 +00003294 if (!ArgType->isReferenceType()) {
3295 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00003296 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00003297 } else {
3298 if (ArgType->getPointeeType().isVolatileQualified()) {
3299 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3300 HadError = true;
3301 }
3302 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3303 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3304 HadError = true;
3305 }
Alexis Huntc9a55732011-05-14 05:23:28 +00003306 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00003307
Alexis Huntc9a55732011-05-14 05:23:28 +00003308 if (OperType->getTypeQuals()) {
3309 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3310 HadError = true;
3311 }
3312
3313 if (OperType->hasExceptionSpec()) {
3314 if (CheckEquivalentExceptionSpec(
3315 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003316 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00003317 PDiag(),
3318 ExceptionType, SourceLocation(),
3319 OperType, MD->getLocation())) {
3320 HadError = true;
3321 }
3322 } else if (First) {
3323 // We set the declaration to have the computed exception spec here.
3324 // We duplicate the one parameter type.
3325 EPI.RefQualifier = OperType->getRefQualifier();
3326 EPI.ExtInfo = OperType->getExtInfo();
3327 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3328 }
3329
3330 if (HadError) {
3331 MD->setInvalidDecl();
3332 return;
3333 }
3334
3335 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3336 if (First) {
3337 MD->setDeletedAsWritten();
3338 } else {
3339 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003340 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00003341 MD->setInvalidDecl();
3342 }
3343 }
3344}
3345
Alexis Huntf91729462011-05-12 22:46:25 +00003346void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3347 assert(DD->isExplicitlyDefaulted());
3348
3349 // Whether this was the first-declared instance of the destructor.
3350 bool First = DD == DD->getCanonicalDecl();
3351
3352 ImplicitExceptionSpecification Spec
3353 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3354 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3355 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3356 *ExceptionType = Context.getFunctionType(
3357 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3358
3359 if (DtorType->hasExceptionSpec()) {
3360 if (CheckEquivalentExceptionSpec(
3361 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003362 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00003363 PDiag(),
3364 ExceptionType, SourceLocation(),
3365 DtorType, DD->getLocation())) {
3366 DD->setInvalidDecl();
3367 return;
3368 }
3369 } else if (First) {
3370 // We set the declaration to have the computed exception spec here.
3371 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00003372 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00003373 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3374 }
3375
3376 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003377 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00003378 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003379 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00003380 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003381 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003382 DD->setInvalidDecl();
3383 }
Alexis Huntf91729462011-05-12 22:46:25 +00003384 }
Alexis Huntf91729462011-05-12 22:46:25 +00003385}
3386
Alexis Huntea6f0322011-05-11 22:34:38 +00003387bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3388 CXXRecordDecl *RD = CD->getParent();
3389 assert(!RD->isDependentType() && "do deletion after instantiation");
3390 if (!LangOpts.CPlusPlus0x)
3391 return false;
3392
Alexis Hunte77a28f2011-05-18 03:41:58 +00003393 SourceLocation Loc = CD->getLocation();
3394
Alexis Huntea6f0322011-05-11 22:34:38 +00003395 // Do access control from the constructor
3396 ContextRAII CtorContext(*this, CD);
3397
3398 bool Union = RD->isUnion();
3399 bool AllConst = true;
3400
Alexis Huntea6f0322011-05-11 22:34:38 +00003401 // We do this because we should never actually use an anonymous
3402 // union's constructor.
3403 if (Union && RD->isAnonymousStructOrUnion())
3404 return false;
3405
3406 // FIXME: We should put some diagnostic logic right into this function.
3407
3408 // C++0x [class.ctor]/5
Alexis Hunteef8ee02011-06-10 03:50:41 +00003409 // A defaulted default constructor for class X is defined as deleted if:
Alexis Huntea6f0322011-05-11 22:34:38 +00003410
3411 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3412 BE = RD->bases_end();
3413 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00003414 // We'll handle this one later
3415 if (BI->isVirtual())
3416 continue;
3417
Alexis Huntea6f0322011-05-11 22:34:38 +00003418 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3419 assert(BaseDecl && "base isn't a CXXRecordDecl");
3420
3421 // -- any [direct base class] has a type with a destructor that is
Alexis Hunteef8ee02011-06-10 03:50:41 +00003422 // deleted or inaccessible from the defaulted default constructor
Alexis Huntea6f0322011-05-11 22:34:38 +00003423 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3424 if (BaseDtor->isDeleted())
3425 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003426 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003427 AR_accessible)
3428 return true;
3429
Alexis Huntea6f0322011-05-11 22:34:38 +00003430 // -- any [direct base class either] has no default constructor or
3431 // overload resolution as applied to [its] default constructor
3432 // results in an ambiguity or in a function that is deleted or
3433 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003434 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3435 if (!BaseDefault || BaseDefault->isDeleted())
3436 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003437
Alexis Hunteef8ee02011-06-10 03:50:41 +00003438 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3439 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003440 return true;
3441 }
3442
3443 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3444 BE = RD->vbases_end();
3445 BI != BE; ++BI) {
3446 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3447 assert(BaseDecl && "base isn't a CXXRecordDecl");
3448
3449 // -- any [virtual base class] has a type with a destructor that is
3450 // delete or inaccessible from the defaulted default constructor
3451 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3452 if (BaseDtor->isDeleted())
3453 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003454 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003455 AR_accessible)
3456 return true;
3457
3458 // -- any [virtual base class either] has no default constructor or
3459 // overload resolution as applied to [its] default constructor
3460 // results in an ambiguity or in a function that is deleted or
3461 // inaccessible from the defaulted default constructor
Alexis Hunteef8ee02011-06-10 03:50:41 +00003462 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3463 if (!BaseDefault || BaseDefault->isDeleted())
3464 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003465
Alexis Hunteef8ee02011-06-10 03:50:41 +00003466 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3467 PDiag()) != AR_accessible)
Alexis Huntea6f0322011-05-11 22:34:38 +00003468 return true;
3469 }
3470
3471 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3472 FE = RD->field_end();
3473 FI != FE; ++FI) {
Richard Smith938f40b2011-06-11 17:19:42 +00003474 if (FI->isInvalidDecl())
3475 continue;
3476
Alexis Huntea6f0322011-05-11 22:34:38 +00003477 QualType FieldType = Context.getBaseElementType(FI->getType());
3478 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00003479
Alexis Huntea6f0322011-05-11 22:34:38 +00003480 // -- any non-static data member with no brace-or-equal-initializer is of
3481 // reference type
Richard Smith938f40b2011-06-11 17:19:42 +00003482 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
Alexis Huntea6f0322011-05-11 22:34:38 +00003483 return true;
3484
3485 // -- X is a union and all its variant members are of const-qualified type
3486 // (or array thereof)
3487 if (Union && !FieldType.isConstQualified())
3488 AllConst = false;
3489
3490 if (FieldRecord) {
3491 // -- X is a union-like class that has a variant member with a non-trivial
3492 // default constructor
3493 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3494 return true;
3495
3496 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3497 if (FieldDtor->isDeleted())
3498 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003499 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntea6f0322011-05-11 22:34:38 +00003500 AR_accessible)
3501 return true;
3502
3503 // -- any non-variant non-static data member of const-qualified type (or
3504 // array thereof) with no brace-or-equal-initializer does not have a
3505 // user-provided default constructor
3506 if (FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003507 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00003508 !FieldRecord->hasUserProvidedDefaultConstructor())
3509 return true;
3510
3511 if (!Union && FieldRecord->isUnion() &&
3512 FieldRecord->isAnonymousStructOrUnion()) {
3513 // We're okay to reuse AllConst here since we only care about the
3514 // value otherwise if we're in a union.
3515 AllConst = true;
3516
3517 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3518 UE = FieldRecord->field_end();
3519 UI != UE; ++UI) {
3520 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3521 CXXRecordDecl *UnionFieldRecord =
3522 UnionFieldType->getAsCXXRecordDecl();
3523
3524 if (!UnionFieldType.isConstQualified())
3525 AllConst = false;
3526
3527 if (UnionFieldRecord &&
3528 !UnionFieldRecord->hasTrivialDefaultConstructor())
3529 return true;
3530 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00003531
Alexis Huntea6f0322011-05-11 22:34:38 +00003532 if (AllConst)
3533 return true;
3534
3535 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00003536 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00003537 continue;
3538 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00003539
Richard Smith938f40b2011-06-11 17:19:42 +00003540 // -- any non-static data member with no brace-or-equal-initializer has
3541 // class type M (or array thereof) and either M has no default
3542 // constructor or overload resolution as applied to M's default
3543 // constructor results in an ambiguity or in a function that is deleted
3544 // or inaccessible from the defaulted default constructor.
3545 if (!FI->hasInClassInitializer()) {
3546 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3547 if (!FieldDefault || FieldDefault->isDeleted())
3548 return true;
3549 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3550 PDiag()) != AR_accessible)
3551 return true;
3552 }
3553 } else if (!Union && FieldType.isConstQualified() &&
3554 !FI->hasInClassInitializer()) {
Alexis Hunta671bca2011-05-20 21:43:47 +00003555 // -- any non-variant non-static data member of const-qualified type (or
3556 // array thereof) with no brace-or-equal-initializer does not have a
3557 // user-provided default constructor
3558 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00003559 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003560 }
3561
3562 if (Union && AllConst)
3563 return true;
3564
3565 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003566}
3567
Alexis Hunt913820d2011-05-13 06:10:58 +00003568bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
Alexis Hunt16473542011-05-18 20:57:13 +00003569 CXXRecordDecl *RD = CD->getParent();
Alexis Hunt913820d2011-05-13 06:10:58 +00003570 assert(!RD->isDependentType() && "do deletion after instantiation");
3571 if (!LangOpts.CPlusPlus0x)
3572 return false;
3573
Alexis Hunte77a28f2011-05-18 03:41:58 +00003574 SourceLocation Loc = CD->getLocation();
3575
Alexis Hunt913820d2011-05-13 06:10:58 +00003576 // Do access control from the constructor
3577 ContextRAII CtorContext(*this, CD);
3578
Alexis Hunt899bd442011-06-10 04:44:37 +00003579 bool Union = RD->isUnion();
Alexis Hunt913820d2011-05-13 06:10:58 +00003580
Alexis Huntc9a55732011-05-14 05:23:28 +00003581 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3582 "copy assignment arg has no pointee type");
Alexis Hunt899bd442011-06-10 04:44:37 +00003583 unsigned ArgQuals =
3584 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3585 Qualifiers::Const : 0;
Alexis Hunt913820d2011-05-13 06:10:58 +00003586
3587 // We do this because we should never actually use an anonymous
3588 // union's constructor.
3589 if (Union && RD->isAnonymousStructOrUnion())
3590 return false;
3591
3592 // FIXME: We should put some diagnostic logic right into this function.
3593
3594 // C++0x [class.copy]/11
3595 // A defaulted [copy] constructor for class X is defined as delete if X has:
3596
3597 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3598 BE = RD->bases_end();
3599 BI != BE; ++BI) {
3600 // We'll handle this one later
3601 if (BI->isVirtual())
3602 continue;
3603
3604 QualType BaseType = BI->getType();
3605 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3606 assert(BaseDecl && "base isn't a CXXRecordDecl");
3607
3608 // -- any [direct base class] of a type with a destructor that is deleted or
3609 // inaccessible from the defaulted constructor
3610 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3611 if (BaseDtor->isDeleted())
3612 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003613 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003614 AR_accessible)
3615 return true;
3616
3617 // -- a [direct base class] B that cannot be [copied] because overload
3618 // resolution, as applied to B's [copy] constructor, results in an
3619 // ambiguity or a function that is deleted or inaccessible from the
3620 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003621 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003622 if (!BaseCtor || BaseCtor->isDeleted())
3623 return true;
3624 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3625 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003626 return true;
3627 }
3628
3629 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3630 BE = RD->vbases_end();
3631 BI != BE; ++BI) {
3632 QualType BaseType = BI->getType();
3633 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3634 assert(BaseDecl && "base isn't a CXXRecordDecl");
3635
Alexis Hunteef8ee02011-06-10 03:50:41 +00003636 // -- any [virtual base class] of a type with a destructor that is deleted or
Alexis Hunt913820d2011-05-13 06:10:58 +00003637 // inaccessible from the defaulted constructor
3638 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3639 if (BaseDtor->isDeleted())
3640 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003641 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003642 AR_accessible)
3643 return true;
3644
3645 // -- a [virtual base class] B that cannot be [copied] because overload
3646 // resolution, as applied to B's [copy] constructor, results in an
3647 // ambiguity or a function that is deleted or inaccessible from the
3648 // defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003649 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003650 if (!BaseCtor || BaseCtor->isDeleted())
3651 return true;
3652 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3653 AR_accessible)
Alexis Hunt913820d2011-05-13 06:10:58 +00003654 return true;
3655 }
3656
3657 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3658 FE = RD->field_end();
3659 FI != FE; ++FI) {
3660 QualType FieldType = Context.getBaseElementType(FI->getType());
3661
3662 // -- for a copy constructor, a non-static data member of rvalue reference
3663 // type
3664 if (FieldType->isRValueReferenceType())
3665 return true;
3666
3667 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3668
3669 if (FieldRecord) {
3670 // This is an anonymous union
3671 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3672 // Anonymous unions inside unions do not variant members create
3673 if (!Union) {
3674 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3675 UE = FieldRecord->field_end();
3676 UI != UE; ++UI) {
3677 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3678 CXXRecordDecl *UnionFieldRecord =
3679 UnionFieldType->getAsCXXRecordDecl();
3680
3681 // -- a variant member with a non-trivial [copy] constructor and X
3682 // is a union-like class
3683 if (UnionFieldRecord &&
3684 !UnionFieldRecord->hasTrivialCopyConstructor())
3685 return true;
3686 }
3687 }
3688
3689 // Don't try to initalize an anonymous union
3690 continue;
3691 } else {
3692 // -- a variant member with a non-trivial [copy] constructor and X is a
3693 // union-like class
3694 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3695 return true;
3696
3697 // -- any [non-static data member] of a type with a destructor that is
3698 // deleted or inaccessible from the defaulted constructor
3699 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3700 if (FieldDtor->isDeleted())
3701 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003702 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Hunt913820d2011-05-13 06:10:58 +00003703 AR_accessible)
3704 return true;
3705 }
Alexis Hunt899bd442011-06-10 04:44:37 +00003706
3707 // -- a [non-static data member of class type (or array thereof)] B that
3708 // cannot be [copied] because overload resolution, as applied to B's
3709 // [copy] constructor, results in an ambiguity or a function that is
3710 // deleted or inaccessible from the defaulted constructor
Alexis Hunt491ec602011-06-21 23:42:56 +00003711 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3712 ArgQuals);
Alexis Hunt899bd442011-06-10 04:44:37 +00003713 if (!FieldCtor || FieldCtor->isDeleted())
3714 return true;
3715 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3716 PDiag()) != AR_accessible)
3717 return true;
Alexis Hunt913820d2011-05-13 06:10:58 +00003718 }
Alexis Hunt913820d2011-05-13 06:10:58 +00003719 }
3720
3721 return false;
3722}
3723
Alexis Huntb2f27802011-05-14 05:23:24 +00003724bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3725 CXXRecordDecl *RD = MD->getParent();
3726 assert(!RD->isDependentType() && "do deletion after instantiation");
3727 if (!LangOpts.CPlusPlus0x)
3728 return false;
3729
Alexis Hunte77a28f2011-05-18 03:41:58 +00003730 SourceLocation Loc = MD->getLocation();
3731
Alexis Huntb2f27802011-05-14 05:23:24 +00003732 // Do access control from the constructor
3733 ContextRAII MethodContext(*this, MD);
3734
3735 bool Union = RD->isUnion();
3736
Alexis Hunt491ec602011-06-21 23:42:56 +00003737 unsigned ArgQuals =
3738 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3739 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00003740
3741 // We do this because we should never actually use an anonymous
3742 // union's constructor.
3743 if (Union && RD->isAnonymousStructOrUnion())
3744 return false;
3745
Alexis Huntb2f27802011-05-14 05:23:24 +00003746 // FIXME: We should put some diagnostic logic right into this function.
3747
3748 // C++0x [class.copy]/11
3749 // A defaulted [copy] assignment operator for class X is defined as deleted
3750 // if X has:
3751
3752 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3753 BE = RD->bases_end();
3754 BI != BE; ++BI) {
3755 // We'll handle this one later
3756 if (BI->isVirtual())
3757 continue;
3758
3759 QualType BaseType = BI->getType();
3760 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3761 assert(BaseDecl && "base isn't a CXXRecordDecl");
3762
3763 // -- a [direct base class] B that cannot be [copied] because overload
3764 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00003765 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00003766 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003767 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3768 0);
3769 if (!CopyOper || CopyOper->isDeleted())
3770 return true;
3771 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003772 return true;
3773 }
3774
3775 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3776 BE = RD->vbases_end();
3777 BI != BE; ++BI) {
3778 QualType BaseType = BI->getType();
3779 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3780 assert(BaseDecl && "base isn't a CXXRecordDecl");
3781
Alexis Huntb2f27802011-05-14 05:23:24 +00003782 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00003783 // resolution, as applied to B's [copy] assignment operator, results in
3784 // an ambiguity or a function that is deleted or inaccessible from the
3785 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00003786 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3787 0);
3788 if (!CopyOper || CopyOper->isDeleted())
3789 return true;
3790 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00003791 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00003792 }
3793
3794 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3795 FE = RD->field_end();
3796 FI != FE; ++FI) {
3797 QualType FieldType = Context.getBaseElementType(FI->getType());
3798
3799 // -- a non-static data member of reference type
3800 if (FieldType->isReferenceType())
3801 return true;
3802
3803 // -- a non-static data member of const non-class type (or array thereof)
3804 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3805 return true;
3806
3807 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3808
3809 if (FieldRecord) {
3810 // This is an anonymous union
3811 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3812 // Anonymous unions inside unions do not variant members create
3813 if (!Union) {
3814 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3815 UE = FieldRecord->field_end();
3816 UI != UE; ++UI) {
3817 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3818 CXXRecordDecl *UnionFieldRecord =
3819 UnionFieldType->getAsCXXRecordDecl();
3820
3821 // -- a variant member with a non-trivial [copy] assignment operator
3822 // and X is a union-like class
3823 if (UnionFieldRecord &&
3824 !UnionFieldRecord->hasTrivialCopyAssignment())
3825 return true;
3826 }
3827 }
3828
3829 // Don't try to initalize an anonymous union
3830 continue;
3831 // -- a variant member with a non-trivial [copy] assignment operator
3832 // and X is a union-like class
3833 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3834 return true;
3835 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003836
Alexis Hunt491ec602011-06-21 23:42:56 +00003837 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3838 false, 0);
3839 if (!CopyOper || CopyOper->isDeleted())
3840 return false;
3841 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3842 return false;
Alexis Huntc9a55732011-05-14 05:23:28 +00003843 }
Alexis Huntb2f27802011-05-14 05:23:24 +00003844 }
3845
3846 return false;
3847}
3848
Alexis Huntf91729462011-05-12 22:46:25 +00003849bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3850 CXXRecordDecl *RD = DD->getParent();
3851 assert(!RD->isDependentType() && "do deletion after instantiation");
3852 if (!LangOpts.CPlusPlus0x)
3853 return false;
3854
Alexis Hunte77a28f2011-05-18 03:41:58 +00003855 SourceLocation Loc = DD->getLocation();
3856
Alexis Huntf91729462011-05-12 22:46:25 +00003857 // Do access control from the destructor
3858 ContextRAII CtorContext(*this, DD);
3859
3860 bool Union = RD->isUnion();
3861
Alexis Hunt913820d2011-05-13 06:10:58 +00003862 // We do this because we should never actually use an anonymous
3863 // union's destructor.
3864 if (Union && RD->isAnonymousStructOrUnion())
3865 return false;
3866
Alexis Huntf91729462011-05-12 22:46:25 +00003867 // C++0x [class.dtor]p5
3868 // A defaulted destructor for a class X is defined as deleted if:
3869 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3870 BE = RD->bases_end();
3871 BI != BE; ++BI) {
3872 // We'll handle this one later
3873 if (BI->isVirtual())
3874 continue;
3875
3876 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3877 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3878 assert(BaseDtor && "base has no destructor");
3879
3880 // -- any direct or virtual base class has a deleted destructor or
3881 // a destructor that is inaccessible from the defaulted destructor
3882 if (BaseDtor->isDeleted())
3883 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003884 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003885 AR_accessible)
3886 return true;
3887 }
3888
3889 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3890 BE = RD->vbases_end();
3891 BI != BE; ++BI) {
3892 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3893 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3894 assert(BaseDtor && "base has no destructor");
3895
3896 // -- any direct or virtual base class has a deleted destructor or
3897 // a destructor that is inaccessible from the defaulted destructor
3898 if (BaseDtor->isDeleted())
3899 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003900 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003901 AR_accessible)
3902 return true;
3903 }
3904
3905 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3906 FE = RD->field_end();
3907 FI != FE; ++FI) {
3908 QualType FieldType = Context.getBaseElementType(FI->getType());
3909 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3910 if (FieldRecord) {
3911 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3912 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3913 UE = FieldRecord->field_end();
3914 UI != UE; ++UI) {
3915 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3916 CXXRecordDecl *UnionFieldRecord =
3917 UnionFieldType->getAsCXXRecordDecl();
3918
3919 // -- X is a union-like class that has a variant member with a non-
3920 // trivial destructor.
3921 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3922 return true;
3923 }
3924 // Technically we are supposed to do this next check unconditionally.
3925 // But that makes absolutely no sense.
3926 } else {
3927 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3928
3929 // -- any of the non-static data members has class type M (or array
3930 // thereof) and M has a deleted destructor or a destructor that is
3931 // inaccessible from the defaulted destructor
3932 if (FieldDtor->isDeleted())
3933 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00003934 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00003935 AR_accessible)
3936 return true;
3937
3938 // -- X is a union-like class that has a variant member with a non-
3939 // trivial destructor.
3940 if (Union && !FieldDtor->isTrivial())
3941 return true;
3942 }
3943 }
3944 }
3945
3946 if (DD->isVirtual()) {
3947 FunctionDecl *OperatorDelete = 0;
3948 DeclarationName Name =
3949 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00003950 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00003951 false))
3952 return true;
3953 }
3954
3955
3956 return false;
3957}
3958
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003959/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00003960namespace {
3961 struct FindHiddenVirtualMethodData {
3962 Sema *S;
3963 CXXMethodDecl *Method;
3964 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3965 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3966 };
3967}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003968
3969/// \brief Member lookup function that determines whether a given C++
3970/// method overloads virtual methods in a base class without overriding any,
3971/// to be used with CXXRecordDecl::lookupInBases().
3972static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3973 CXXBasePath &Path,
3974 void *UserData) {
3975 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3976
3977 FindHiddenVirtualMethodData &Data
3978 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3979
3980 DeclarationName Name = Data.Method->getDeclName();
3981 assert(Name.getNameKind() == DeclarationName::Identifier);
3982
3983 bool foundSameNameMethod = false;
3984 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3985 for (Path.Decls = BaseRecord->lookup(Name);
3986 Path.Decls.first != Path.Decls.second;
3987 ++Path.Decls.first) {
3988 NamedDecl *D = *Path.Decls.first;
3989 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00003990 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003991 foundSameNameMethod = true;
3992 // Interested only in hidden virtual methods.
3993 if (!MD->isVirtual())
3994 continue;
3995 // If the method we are checking overrides a method from its base
3996 // don't warn about the other overloaded methods.
3997 if (!Data.S->IsOverload(Data.Method, MD, false))
3998 return true;
3999 // Collect the overload only if its hidden.
4000 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4001 overloadedMethods.push_back(MD);
4002 }
4003 }
4004
4005 if (foundSameNameMethod)
4006 Data.OverloadedMethods.append(overloadedMethods.begin(),
4007 overloadedMethods.end());
4008 return foundSameNameMethod;
4009}
4010
4011/// \brief See if a method overloads virtual methods in a base class without
4012/// overriding any.
4013void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4014 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4015 MD->getLocation()) == Diagnostic::Ignored)
4016 return;
4017 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4018 return;
4019
4020 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4021 /*bool RecordPaths=*/false,
4022 /*bool DetectVirtual=*/false);
4023 FindHiddenVirtualMethodData Data;
4024 Data.Method = MD;
4025 Data.S = this;
4026
4027 // Keep the base methods that were overriden or introduced in the subclass
4028 // by 'using' in a set. A base method not in this set is hidden.
4029 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4030 res.first != res.second; ++res.first) {
4031 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4032 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4033 E = MD->end_overridden_methods();
4034 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004035 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004036 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4037 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004038 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004039 }
4040
4041 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4042 !Data.OverloadedMethods.empty()) {
4043 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4044 << MD << (Data.OverloadedMethods.size() > 1);
4045
4046 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4047 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4048 Diag(overloadedMD->getLocation(),
4049 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4050 }
4051 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00004052}
4053
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004054void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00004055 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004056 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004057 SourceLocation RBrac,
4058 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004059 if (!TagDecl)
4060 return;
Mike Stump11289f42009-09-09 15:08:12 +00004061
Douglas Gregorc9f9b862009-05-11 19:58:34 +00004062 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00004063
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004064 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00004065 // strict aliasing violation!
4066 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00004067 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00004068
Douglas Gregor0be31a22010-07-02 17:43:08 +00004069 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00004070 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00004071}
4072
Douglas Gregor05379422008-11-03 17:51:48 +00004073/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4074/// special functions, such as the default constructor, copy
4075/// constructor, or destructor, to the given C++ class (C++
4076/// [special]p1). This routine can only be executed just before the
4077/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004078void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004079 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00004080 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004081
Douglas Gregor54be3392010-07-01 17:57:27 +00004082 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00004083 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00004084
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004085 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4086 ++ASTContext::NumImplicitCopyAssignmentOperators;
4087
4088 // If we have a dynamic class, then the copy assignment operator may be
4089 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4090 // it shows up in the right place in the vtable and that we diagnose
4091 // problems with the implicit exception specification.
4092 if (ClassDecl->isDynamicClass())
4093 DeclareImplicitCopyAssignment(ClassDecl);
4094 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004095
Douglas Gregor7454c562010-07-02 20:37:36 +00004096 if (!ClassDecl->hasUserDeclaredDestructor()) {
4097 ++ASTContext::NumImplicitDestructors;
4098
4099 // If we have a dynamic class, then the destructor may be virtual, so we
4100 // have to declare the destructor immediately. This ensures that, e.g., it
4101 // shows up in the right place in the vtable and that we diagnose problems
4102 // with the implicit exception specification.
4103 if (ClassDecl->isDynamicClass())
4104 DeclareImplicitDestructor(ClassDecl);
4105 }
Douglas Gregor05379422008-11-03 17:51:48 +00004106}
4107
Francois Pichet1c229c02011-04-22 22:18:13 +00004108void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4109 if (!D)
4110 return;
4111
4112 int NumParamList = D->getNumTemplateParameterLists();
4113 for (int i = 0; i < NumParamList; i++) {
4114 TemplateParameterList* Params = D->getTemplateParameterList(i);
4115 for (TemplateParameterList::iterator Param = Params->begin(),
4116 ParamEnd = Params->end();
4117 Param != ParamEnd; ++Param) {
4118 NamedDecl *Named = cast<NamedDecl>(*Param);
4119 if (Named->getDeclName()) {
4120 S->AddDecl(Named);
4121 IdResolver.AddDecl(Named);
4122 }
4123 }
4124 }
4125}
4126
John McCall48871652010-08-21 09:40:31 +00004127void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00004128 if (!D)
4129 return;
4130
4131 TemplateParameterList *Params = 0;
4132 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4133 Params = Template->getTemplateParameters();
4134 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4135 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4136 Params = PartialSpec->getTemplateParameters();
4137 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004138 return;
4139
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004140 for (TemplateParameterList::iterator Param = Params->begin(),
4141 ParamEnd = Params->end();
4142 Param != ParamEnd; ++Param) {
4143 NamedDecl *Named = cast<NamedDecl>(*Param);
4144 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00004145 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00004146 IdResolver.AddDecl(Named);
4147 }
4148 }
4149}
4150
John McCall48871652010-08-21 09:40:31 +00004151void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004152 if (!RecordD) return;
4153 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00004154 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00004155 PushDeclContext(S, Record);
4156}
4157
John McCall48871652010-08-21 09:40:31 +00004158void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00004159 if (!RecordD) return;
4160 PopDeclContext();
4161}
4162
Douglas Gregor4d87df52008-12-16 21:30:33 +00004163/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4164/// parsing a top-level (non-nested) C++ class, and we are now
4165/// parsing those parts of the given Method declaration that could
4166/// not be parsed earlier (C++ [class.mem]p2), such as default
4167/// arguments. This action should enter the scope of the given
4168/// Method declaration as if we had just parsed the qualified method
4169/// name. However, it should not bring the parameters into scope;
4170/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00004171void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004172}
4173
4174/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4175/// C++ method declaration. We're (re-)introducing the given
4176/// function parameter into scope for use in parsing later parts of
4177/// the method declaration. For example, we could see an
4178/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00004179void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004180 if (!ParamD)
4181 return;
Mike Stump11289f42009-09-09 15:08:12 +00004182
John McCall48871652010-08-21 09:40:31 +00004183 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00004184
4185 // If this parameter has an unparsed default argument, clear it out
4186 // to make way for the parsed default argument.
4187 if (Param->hasUnparsedDefaultArg())
4188 Param->setDefaultArg(0);
4189
John McCall48871652010-08-21 09:40:31 +00004190 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004191 if (Param->getDeclName())
4192 IdResolver.AddDecl(Param);
4193}
4194
4195/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4196/// processing the delayed method declaration for Method. The method
4197/// declaration is now considered finished. There may be a separate
4198/// ActOnStartOfFunctionDef action later (not necessarily
4199/// immediately!) for this method, if it was also defined inside the
4200/// class body.
John McCall48871652010-08-21 09:40:31 +00004201void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00004202 if (!MethodD)
4203 return;
Mike Stump11289f42009-09-09 15:08:12 +00004204
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004205 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00004206
John McCall48871652010-08-21 09:40:31 +00004207 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004208
4209 // Now that we have our default arguments, check the constructor
4210 // again. It could produce additional diagnostics or affect whether
4211 // the class has implicitly-declared destructors, among other
4212 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004213 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4214 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00004215
4216 // Check the default arguments, which we may have added.
4217 if (!Method->isInvalidDecl())
4218 CheckCXXDefaultArguments(Method);
4219}
4220
Douglas Gregor831c93f2008-11-05 20:51:48 +00004221/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00004222/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00004223/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004224/// emit diagnostics and set the invalid bit to true. In any case, the type
4225/// will be updated to reflect a well-formed type for the constructor and
4226/// returned.
4227QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004228 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004229 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004230
4231 // C++ [class.ctor]p3:
4232 // A constructor shall not be virtual (10.3) or static (9.4). A
4233 // constructor can be invoked for a const, volatile or const
4234 // volatile object. A constructor shall not be declared const,
4235 // volatile, or const volatile (9.3.2).
4236 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004237 if (!D.isInvalidType())
4238 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4239 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4240 << SourceRange(D.getIdentifierLoc());
4241 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004242 }
John McCall8e7d6562010-08-26 03:08:43 +00004243 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004244 if (!D.isInvalidType())
4245 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4246 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4247 << SourceRange(D.getIdentifierLoc());
4248 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004249 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004250 }
Mike Stump11289f42009-09-09 15:08:12 +00004251
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004252 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004253 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00004254 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004255 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4256 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004257 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004258 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4259 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004260 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004261 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4262 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00004263 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004264 }
Mike Stump11289f42009-09-09 15:08:12 +00004265
Douglas Gregordb9d6642011-01-26 05:01:58 +00004266 // C++0x [class.ctor]p4:
4267 // A constructor shall not be declared with a ref-qualifier.
4268 if (FTI.hasRefQualifier()) {
4269 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4270 << FTI.RefQualifierIsLValueRef
4271 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4272 D.setInvalidType();
4273 }
4274
Douglas Gregor831c93f2008-11-05 20:51:48 +00004275 // Rebuild the function type "R" without any type qualifiers (in
4276 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00004277 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00004278 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004279 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4280 return R;
4281
4282 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4283 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004284 EPI.RefQualifier = RQ_None;
4285
Chris Lattner38378bf2009-04-25 08:28:21 +00004286 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00004287 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004288}
4289
Douglas Gregor4d87df52008-12-16 21:30:33 +00004290/// CheckConstructor - Checks a fully-formed constructor for
4291/// well-formedness, issuing any diagnostics required. Returns true if
4292/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004293void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00004294 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004295 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4296 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004297 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004298
4299 // C++ [class.copy]p3:
4300 // A declaration of a constructor for a class X is ill-formed if
4301 // its first parameter is of type (optionally cv-qualified) X and
4302 // either there are no other parameters or else all other
4303 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00004304 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00004305 ((Constructor->getNumParams() == 1) ||
4306 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00004307 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4308 Constructor->getTemplateSpecializationKind()
4309 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00004310 QualType ParamType = Constructor->getParamDecl(0)->getType();
4311 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4312 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00004313 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00004314 const char *ConstRef
4315 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4316 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00004317 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00004318 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00004319
4320 // FIXME: Rather that making the constructor invalid, we should endeavor
4321 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004322 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00004323 }
4324 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00004325}
4326
John McCalldeb646e2010-08-04 01:04:25 +00004327/// CheckDestructor - Checks a fully-formed destructor definition for
4328/// well-formedness, issuing any diagnostics required. Returns true
4329/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00004330bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00004331 CXXRecordDecl *RD = Destructor->getParent();
4332
4333 if (Destructor->isVirtual()) {
4334 SourceLocation Loc;
4335
4336 if (!Destructor->isImplicit())
4337 Loc = Destructor->getLocation();
4338 else
4339 Loc = RD->getLocation();
4340
4341 // If we have a virtual destructor, look up the deallocation function
4342 FunctionDecl *OperatorDelete = 0;
4343 DeclarationName Name =
4344 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00004345 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00004346 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00004347
4348 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00004349
4350 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004351 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00004352
4353 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00004354}
4355
Mike Stump11289f42009-09-09 15:08:12 +00004356static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00004357FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4358 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4359 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004360 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00004361}
4362
Douglas Gregor831c93f2008-11-05 20:51:48 +00004363/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4364/// the well-formednes of the destructor declarator @p D with type @p
4365/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00004366/// emit diagnostics and set the declarator to invalid. Even if this happens,
4367/// will be updated to reflect a well-formed type for the destructor and
4368/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00004369QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00004370 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004371 // C++ [class.dtor]p1:
4372 // [...] A typedef-name that names a class is a class-name
4373 // (7.1.3); however, a typedef-name that names a class shall not
4374 // be used as the identifier in the declarator for a destructor
4375 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00004376 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00004377 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00004378 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00004379 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004380 else if (const TemplateSpecializationType *TST =
4381 DeclaratorType->getAs<TemplateSpecializationType>())
4382 if (TST->isTypeAlias())
4383 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4384 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004385
4386 // C++ [class.dtor]p2:
4387 // A destructor is used to destroy objects of its class type. A
4388 // destructor takes no parameters, and no return type can be
4389 // specified for it (not even void). The address of a destructor
4390 // shall not be taken. A destructor shall not be static. A
4391 // destructor can be invoked for a const, volatile or const
4392 // volatile object. A destructor shall not be declared const,
4393 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00004394 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00004395 if (!D.isInvalidType())
4396 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4397 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00004398 << SourceRange(D.getIdentifierLoc())
4399 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4400
John McCall8e7d6562010-08-26 03:08:43 +00004401 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00004402 }
Chris Lattner38378bf2009-04-25 08:28:21 +00004403 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004404 // Destructors don't have return types, but the parser will
4405 // happily parse something like:
4406 //
4407 // class X {
4408 // float ~X();
4409 // };
4410 //
4411 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00004412 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4413 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4414 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00004415 }
Mike Stump11289f42009-09-09 15:08:12 +00004416
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004417 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00004418 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004419 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00004420 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4421 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004422 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00004423 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4424 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00004425 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00004426 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4427 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00004428 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004429 }
4430
Douglas Gregordb9d6642011-01-26 05:01:58 +00004431 // C++0x [class.dtor]p2:
4432 // A destructor shall not be declared with a ref-qualifier.
4433 if (FTI.hasRefQualifier()) {
4434 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4435 << FTI.RefQualifierIsLValueRef
4436 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4437 D.setInvalidType();
4438 }
4439
Douglas Gregor831c93f2008-11-05 20:51:48 +00004440 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00004441 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004442 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4443
4444 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00004445 FTI.freeArgs();
4446 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00004447 }
4448
Mike Stump11289f42009-09-09 15:08:12 +00004449 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00004450 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00004451 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00004452 D.setInvalidType();
4453 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00004454
4455 // Rebuild the function type "R" without any type qualifiers or
4456 // parameters (in case any of the errors above fired) and with
4457 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00004458 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00004459 if (!D.isInvalidType())
4460 return R;
4461
Douglas Gregor95755162010-07-01 05:10:53 +00004462 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004463 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4464 EPI.Variadic = false;
4465 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00004466 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00004467 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00004468}
4469
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004470/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4471/// well-formednes of the conversion function declarator @p D with
4472/// type @p R. If there are any errors in the declarator, this routine
4473/// will emit diagnostics and return true. Otherwise, it will return
4474/// false. Either way, the type @p R will be updated to reflect a
4475/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004476void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00004477 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004478 // C++ [class.conv.fct]p1:
4479 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00004480 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00004481 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00004482 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004483 if (!D.isInvalidType())
4484 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4485 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4486 << SourceRange(D.getIdentifierLoc());
4487 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00004488 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004489 }
John McCall212fa2e2010-04-13 00:04:31 +00004490
4491 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4492
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004493 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004494 // Conversion functions don't have return types, but the parser will
4495 // happily parse something like:
4496 //
4497 // class X {
4498 // float operator bool();
4499 // };
4500 //
4501 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00004502 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4503 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4504 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00004505 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004506 }
4507
John McCall212fa2e2010-04-13 00:04:31 +00004508 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4509
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004510 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00004511 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004512 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4513
4514 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004515 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004516 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00004517 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004518 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004519 D.setInvalidType();
4520 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004521
John McCall212fa2e2010-04-13 00:04:31 +00004522 // Diagnose "&operator bool()" and other such nonsense. This
4523 // is actually a gcc extension which we don't support.
4524 if (Proto->getResultType() != ConvType) {
4525 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4526 << Proto->getResultType();
4527 D.setInvalidType();
4528 ConvType = Proto->getResultType();
4529 }
4530
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004531 // C++ [class.conv.fct]p4:
4532 // The conversion-type-id shall not represent a function type nor
4533 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004534 if (ConvType->isArrayType()) {
4535 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4536 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004537 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004538 } else if (ConvType->isFunctionType()) {
4539 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4540 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00004541 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004542 }
4543
4544 // Rebuild the function type "R" without any parameters (in case any
4545 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00004546 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00004547 if (D.isInvalidType())
4548 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004549
Douglas Gregor5fb53972009-01-14 15:45:31 +00004550 // C++0x explicit conversion operators.
4551 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00004552 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00004553 diag::warn_explicit_conversion_functions)
4554 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004555}
4556
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004557/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4558/// the declaration of the given C++ conversion function. This routine
4559/// is responsible for recording the conversion function in the C++
4560/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00004561Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004562 assert(Conversion && "Expected to receive a conversion function declaration");
4563
Douglas Gregor4287b372008-12-12 08:25:50 +00004564 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004565
4566 // Make sure we aren't redeclaring the conversion function.
4567 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004568
4569 // C++ [class.conv.fct]p1:
4570 // [...] A conversion function is never used to convert a
4571 // (possibly cv-qualified) object to the (possibly cv-qualified)
4572 // same object type (or a reference to it), to a (possibly
4573 // cv-qualified) base class of that type (or a reference to it),
4574 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00004575 // FIXME: Suppress this warning if the conversion function ends up being a
4576 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00004577 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004578 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004579 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004580 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004581 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4582 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00004583 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00004584 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004585 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4586 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004587 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004588 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004589 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004590 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004591 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004592 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00004593 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004594 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004595 }
4596
Douglas Gregor457104e2010-09-29 04:25:11 +00004597 if (FunctionTemplateDecl *ConversionTemplate
4598 = Conversion->getDescribedFunctionTemplate())
4599 return ConversionTemplate;
4600
John McCall48871652010-08-21 09:40:31 +00004601 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00004602}
4603
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004604//===----------------------------------------------------------------------===//
4605// Namespace Handling
4606//===----------------------------------------------------------------------===//
4607
John McCallb1be5232010-08-26 09:15:37 +00004608
4609
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004610/// ActOnStartNamespaceDef - This is called at the start of a namespace
4611/// definition.
John McCall48871652010-08-21 09:40:31 +00004612Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00004613 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004614 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00004615 SourceLocation IdentLoc,
4616 IdentifierInfo *II,
4617 SourceLocation LBrace,
4618 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004619 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4620 // For anonymous namespace, take the location of the left brace.
4621 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00004622 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004623 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004624 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004625
4626 Scope *DeclRegionScope = NamespcScope->getParent();
4627
Anders Carlssona7bcade2010-02-07 01:09:23 +00004628 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4629
John McCall2faf32c2010-12-10 02:59:44 +00004630 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4631 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00004632
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004633 if (II) {
4634 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00004635 // The identifier in an original-namespace-definition shall not
4636 // have been previously defined in the declarative region in
4637 // which the original-namespace-definition appears. The
4638 // identifier in an original-namespace-definition is the name of
4639 // the namespace. Subsequently in that declarative region, it is
4640 // treated as an original-namespace-name.
4641 //
4642 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00004643 // look through using directives, just look for any ordinary names.
4644
4645 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4646 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4647 Decl::IDNS_Namespace;
4648 NamedDecl *PrevDecl = 0;
4649 for (DeclContext::lookup_result R
4650 = CurContext->getRedeclContext()->lookup(II);
4651 R.first != R.second; ++R.first) {
4652 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4653 PrevDecl = *R.first;
4654 break;
4655 }
4656 }
4657
Douglas Gregor91f84212008-12-11 16:49:14 +00004658 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4659 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004660 if (Namespc->isInline() != OrigNS->isInline()) {
4661 // inline-ness must match
Douglas Gregora9121972011-05-20 15:48:31 +00004662 if (OrigNS->isInline()) {
4663 // The user probably just forgot the 'inline', so suggest that it
4664 // be added back.
4665 Diag(Namespc->getLocation(),
4666 diag::warn_inline_namespace_reopened_noninline)
4667 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4668 } else {
4669 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4670 << Namespc->isInline();
4671 }
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004672 Diag(OrigNS->getLocation(), diag::note_previous_definition);
Douglas Gregora9121972011-05-20 15:48:31 +00004673
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004674 // Recover by ignoring the new namespace's inline status.
4675 Namespc->setInline(OrigNS->isInline());
4676 }
4677
Douglas Gregor91f84212008-12-11 16:49:14 +00004678 // Attach this namespace decl to the chain of extended namespace
4679 // definitions.
4680 OrigNS->setNextNamespace(Namespc);
4681 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004682
Mike Stump11289f42009-09-09 15:08:12 +00004683 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00004684 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00004685 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00004686 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004687 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004688 } else if (PrevDecl) {
4689 // This is an invalid name redefinition.
4690 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4691 << Namespc->getDeclName();
4692 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4693 Namespc->setInvalidDecl();
4694 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00004695 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00004696 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004697 // This is the first "real" definition of the namespace "std", so update
4698 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004699 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00004700 // We had already defined a dummy namespace "std". Link this new
4701 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004702 StdNS->setNextNamespace(Namespc);
4703 StdNS->setLocation(IdentLoc);
4704 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00004705 }
4706
4707 // Make our StdNamespace cache point at the first real definition of the
4708 // "std" namespace.
4709 StdNamespace = Namespc;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004710
4711 // Add this instance of "std" to the set of known namespaces
4712 KnownNamespaces[Namespc] = false;
4713 } else if (!Namespc->isInline()) {
4714 // Since this is an "original" namespace, add it to the known set of
4715 // namespaces if it is not an inline namespace.
4716 KnownNamespaces[Namespc] = false;
Mike Stump11289f42009-09-09 15:08:12 +00004717 }
Douglas Gregor91f84212008-12-11 16:49:14 +00004718
4719 PushOnScopeChains(Namespc, DeclRegionScope);
4720 } else {
John McCall4fa53422009-10-01 00:25:31 +00004721 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00004722 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00004723
4724 // Link the anonymous namespace into its parent.
4725 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00004726 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00004727 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4728 PrevDecl = TU->getAnonymousNamespace();
4729 TU->setAnonymousNamespace(Namespc);
4730 } else {
4731 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4732 PrevDecl = ND->getAnonymousNamespace();
4733 ND->setAnonymousNamespace(Namespc);
4734 }
4735
4736 // Link the anonymous namespace with its previous declaration.
4737 if (PrevDecl) {
4738 assert(PrevDecl->isAnonymousNamespace());
4739 assert(!PrevDecl->getNextNamespace());
4740 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4741 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00004742
4743 if (Namespc->isInline() != PrevDecl->isInline()) {
4744 // inline-ness must match
4745 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4746 << Namespc->isInline();
4747 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4748 Namespc->setInvalidDecl();
4749 // Recover by ignoring the new namespace's inline status.
4750 Namespc->setInline(PrevDecl->isInline());
4751 }
John McCall0db42252009-12-16 02:06:49 +00004752 }
John McCall4fa53422009-10-01 00:25:31 +00004753
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00004754 CurContext->addDecl(Namespc);
4755
John McCall4fa53422009-10-01 00:25:31 +00004756 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4757 // behaves as if it were replaced by
4758 // namespace unique { /* empty body */ }
4759 // using namespace unique;
4760 // namespace unique { namespace-body }
4761 // where all occurrences of 'unique' in a translation unit are
4762 // replaced by the same identifier and this identifier differs
4763 // from all other identifiers in the entire program.
4764
4765 // We just create the namespace with an empty name and then add an
4766 // implicit using declaration, just like the standard suggests.
4767 //
4768 // CodeGen enforces the "universally unique" aspect by giving all
4769 // declarations semantically contained within an anonymous
4770 // namespace internal linkage.
4771
John McCall0db42252009-12-16 02:06:49 +00004772 if (!PrevDecl) {
4773 UsingDirectiveDecl* UD
4774 = UsingDirectiveDecl::Create(Context, CurContext,
4775 /* 'using' */ LBrace,
4776 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00004777 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00004778 /* identifier */ SourceLocation(),
4779 Namespc,
4780 /* Ancestor */ CurContext);
4781 UD->setImplicit();
4782 CurContext->addDecl(UD);
4783 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004784 }
4785
4786 // Although we could have an invalid decl (i.e. the namespace name is a
4787 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00004788 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4789 // for the namespace has the declarations that showed up in that particular
4790 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00004791 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00004792 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004793}
4794
Sebastian Redla6602e92009-11-23 15:34:23 +00004795/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4796/// is a namespace alias, returns the namespace it points to.
4797static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4798 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4799 return AD->getNamespace();
4800 return dyn_cast_or_null<NamespaceDecl>(D);
4801}
4802
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004803/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4804/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00004805void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004806 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4807 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004808 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004809 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00004810 if (Namespc->hasAttr<VisibilityAttr>())
4811 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00004812}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004813
John McCall28a0cf72010-08-25 07:42:41 +00004814CXXRecordDecl *Sema::getStdBadAlloc() const {
4815 return cast_or_null<CXXRecordDecl>(
4816 StdBadAlloc.get(Context.getExternalSource()));
4817}
4818
4819NamespaceDecl *Sema::getStdNamespace() const {
4820 return cast_or_null<NamespaceDecl>(
4821 StdNamespace.get(Context.getExternalSource()));
4822}
4823
Douglas Gregorcdf87022010-06-29 17:53:46 +00004824/// \brief Retrieve the special "std" namespace, which may require us to
4825/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004826NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00004827 if (!StdNamespace) {
4828 // The "std" namespace has not yet been defined, so build one implicitly.
4829 StdNamespace = NamespaceDecl::Create(Context,
4830 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00004831 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00004832 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004833 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004834 }
4835
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004836 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004837}
4838
Douglas Gregora172e082011-03-26 22:25:30 +00004839/// \brief Determine whether a using statement is in a context where it will be
4840/// apply in all contexts.
4841static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4842 switch (CurContext->getDeclKind()) {
4843 case Decl::TranslationUnit:
4844 return true;
4845 case Decl::LinkageSpec:
4846 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4847 default:
4848 return false;
4849 }
4850}
4851
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004852static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
4853 CXXScopeSpec &SS,
4854 SourceLocation IdentLoc,
4855 IdentifierInfo *Ident) {
4856 R.clear();
4857 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
4858 R.getLookupKind(), Sc, &SS, NULL,
4859 false, S.CTC_NoKeywords, NULL)) {
4860 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
4861 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
4862 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
4863 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
4864 if (DeclContext *DC = S.computeDeclContext(SS, false))
4865 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
4866 << Ident << DC << CorrectedQuotedStr << SS.getRange()
4867 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4868 else
4869 S.Diag(IdentLoc, diag::err_using_directive_suggest)
4870 << Ident << CorrectedQuotedStr
4871 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4872
4873 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
4874 diag::note_namespace_defined_here) << CorrectedQuotedStr;
4875
4876 Ident = Corrected.getCorrectionAsIdentifierInfo();
4877 R.addDecl(Corrected.getCorrectionDecl());
4878 return true;
4879 }
4880 R.setLookupName(Ident);
4881 }
4882 return false;
4883}
4884
John McCall48871652010-08-21 09:40:31 +00004885Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00004886 SourceLocation UsingLoc,
4887 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004888 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00004889 SourceLocation IdentLoc,
4890 IdentifierInfo *NamespcName,
4891 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00004892 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4893 assert(NamespcName && "Invalid NamespcName.");
4894 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00004895
4896 // This can only happen along a recovery path.
4897 while (S->getFlags() & Scope::TemplateParamScope)
4898 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00004899 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00004900
Douglas Gregor889ceb72009-02-03 19:21:40 +00004901 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00004902 NestedNameSpecifier *Qualifier = 0;
4903 if (SS.isSet())
4904 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4905
Douglas Gregor34074322009-01-14 22:20:51 +00004906 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004907 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4908 LookupParsedName(R, S, &SS);
4909 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004910 return 0;
John McCall27b18f82009-11-17 02:14:36 +00004911
Douglas Gregorcdf87022010-06-29 17:53:46 +00004912 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004913 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00004914 // Allow "using namespace std;" or "using namespace ::std;" even if
4915 // "std" hasn't been defined yet, for GCC compatibility.
4916 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4917 NamespcName->isStr("std")) {
4918 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00004919 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00004920 R.resolveKind();
4921 }
4922 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004923 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00004924 }
4925
John McCall9f3059a2009-10-09 21:13:30 +00004926 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00004927 NamedDecl *Named = R.getFoundDecl();
4928 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4929 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00004930 // C++ [namespace.udir]p1:
4931 // A using-directive specifies that the names in the nominated
4932 // namespace can be used in the scope in which the
4933 // using-directive appears after the using-directive. During
4934 // unqualified name lookup (3.4.1), the names appear as if they
4935 // were declared in the nearest enclosing namespace which
4936 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00004937 // namespace. [Note: in this context, "contains" means "contains
4938 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00004939
4940 // Find enclosing context containing both using-directive and
4941 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00004942 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004943 DeclContext *CommonAncestor = cast<DeclContext>(NS);
4944 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4945 CommonAncestor = CommonAncestor->getParent();
4946
Sebastian Redla6602e92009-11-23 15:34:23 +00004947 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00004948 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00004949 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004950
Douglas Gregora172e082011-03-26 22:25:30 +00004951 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00004952 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00004953 Diag(IdentLoc, diag::warn_using_directive_in_header);
4954 }
4955
Douglas Gregor889ceb72009-02-03 19:21:40 +00004956 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004957 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00004958 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00004959 }
4960
Douglas Gregor889ceb72009-02-03 19:21:40 +00004961 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00004962 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00004963}
4964
4965void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4966 // If scope has associated entity, then using directive is at namespace
4967 // or translation unit scope. We add UsingDirectiveDecls, into
4968 // it's lookup structure.
4969 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004970 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00004971 else
4972 // Otherwise it is block-sope. using-directives will affect lookup
4973 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00004974 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00004975}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004976
Douglas Gregorfec52632009-06-20 00:51:54 +00004977
John McCall48871652010-08-21 09:40:31 +00004978Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00004979 AccessSpecifier AS,
4980 bool HasUsingKeyword,
4981 SourceLocation UsingLoc,
4982 CXXScopeSpec &SS,
4983 UnqualifiedId &Name,
4984 AttributeList *AttrList,
4985 bool IsTypeName,
4986 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00004987 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00004988
Douglas Gregor220f4272009-11-04 16:30:06 +00004989 switch (Name.getKind()) {
4990 case UnqualifiedId::IK_Identifier:
4991 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00004992 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00004993 case UnqualifiedId::IK_ConversionFunctionId:
4994 break;
4995
4996 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00004997 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00004998 // C++0x inherited constructors.
4999 if (getLangOptions().CPlusPlus0x) break;
5000
Douglas Gregor220f4272009-11-04 16:30:06 +00005001 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5002 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005003 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005004
5005 case UnqualifiedId::IK_DestructorName:
5006 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5007 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005008 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005009
5010 case UnqualifiedId::IK_TemplateId:
5011 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5012 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00005013 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00005014 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005015
5016 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5017 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00005018 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00005019 return 0;
John McCall3969e302009-12-08 07:46:18 +00005020
John McCalla0097262009-12-11 02:10:03 +00005021 // Warn about using declarations.
5022 // TODO: store that the declaration was written without 'using' and
5023 // talk about access decls instead of using decls in the
5024 // diagnostics.
5025 if (!HasUsingKeyword) {
5026 UsingLoc = Name.getSourceRange().getBegin();
5027
5028 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00005029 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00005030 }
5031
Douglas Gregorc4356532010-12-16 00:46:58 +00005032 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5033 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5034 return 0;
5035
John McCall3f746822009-11-17 05:59:44 +00005036 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005037 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005038 /* IsInstantiation */ false,
5039 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00005040 if (UD)
5041 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00005042
John McCall48871652010-08-21 09:40:31 +00005043 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00005044}
5045
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005046/// \brief Determine whether a using declaration considers the given
5047/// declarations as "equivalent", e.g., if they are redeclarations of
5048/// the same entity or are both typedefs of the same type.
5049static bool
5050IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5051 bool &SuppressRedeclaration) {
5052 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5053 SuppressRedeclaration = false;
5054 return true;
5055 }
5056
Richard Smithdda56e42011-04-15 14:24:37 +00005057 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5058 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005059 SuppressRedeclaration = true;
5060 return Context.hasSameType(TD1->getUnderlyingType(),
5061 TD2->getUnderlyingType());
5062 }
5063
5064 return false;
5065}
5066
5067
John McCall84d87672009-12-10 09:41:52 +00005068/// Determines whether to create a using shadow decl for a particular
5069/// decl, given the set of decls existing prior to this using lookup.
5070bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5071 const LookupResult &Previous) {
5072 // Diagnose finding a decl which is not from a base class of the
5073 // current class. We do this now because there are cases where this
5074 // function will silently decide not to build a shadow decl, which
5075 // will pre-empt further diagnostics.
5076 //
5077 // We don't need to do this in C++0x because we do the check once on
5078 // the qualifier.
5079 //
5080 // FIXME: diagnose the following if we care enough:
5081 // struct A { int foo; };
5082 // struct B : A { using A::foo; };
5083 // template <class T> struct C : A {};
5084 // template <class T> struct D : C<T> { using B::foo; } // <---
5085 // This is invalid (during instantiation) in C++03 because B::foo
5086 // resolves to the using decl in B, which is not a base class of D<T>.
5087 // We can't diagnose it immediately because C<T> is an unknown
5088 // specialization. The UsingShadowDecl in D<T> then points directly
5089 // to A::foo, which will look well-formed when we instantiate.
5090 // The right solution is to not collapse the shadow-decl chain.
5091 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5092 DeclContext *OrigDC = Orig->getDeclContext();
5093
5094 // Handle enums and anonymous structs.
5095 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5096 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5097 while (OrigRec->isAnonymousStructOrUnion())
5098 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5099
5100 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5101 if (OrigDC == CurContext) {
5102 Diag(Using->getLocation(),
5103 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005104 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005105 Diag(Orig->getLocation(), diag::note_using_decl_target);
5106 return true;
5107 }
5108
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005109 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00005110 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005111 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00005112 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005113 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00005114 Diag(Orig->getLocation(), diag::note_using_decl_target);
5115 return true;
5116 }
5117 }
5118
5119 if (Previous.empty()) return false;
5120
5121 NamedDecl *Target = Orig;
5122 if (isa<UsingShadowDecl>(Target))
5123 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5124
John McCalla17e83e2009-12-11 02:33:26 +00005125 // If the target happens to be one of the previous declarations, we
5126 // don't have a conflict.
5127 //
5128 // FIXME: but we might be increasing its access, in which case we
5129 // should redeclare it.
5130 NamedDecl *NonTag = 0, *Tag = 0;
5131 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5132 I != E; ++I) {
5133 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00005134 bool Result;
5135 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5136 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00005137
5138 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5139 }
5140
John McCall84d87672009-12-10 09:41:52 +00005141 if (Target->isFunctionOrFunctionTemplate()) {
5142 FunctionDecl *FD;
5143 if (isa<FunctionTemplateDecl>(Target))
5144 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5145 else
5146 FD = cast<FunctionDecl>(Target);
5147
5148 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00005149 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00005150 case Ovl_Overload:
5151 return false;
5152
5153 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00005154 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005155 break;
5156
5157 // We found a decl with the exact signature.
5158 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00005159 // If we're in a record, we want to hide the target, so we
5160 // return true (without a diagnostic) to tell the caller not to
5161 // build a shadow decl.
5162 if (CurContext->isRecord())
5163 return true;
5164
5165 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00005166 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005167 break;
5168 }
5169
5170 Diag(Target->getLocation(), diag::note_using_decl_target);
5171 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5172 return true;
5173 }
5174
5175 // Target is not a function.
5176
John McCall84d87672009-12-10 09:41:52 +00005177 if (isa<TagDecl>(Target)) {
5178 // No conflict between a tag and a non-tag.
5179 if (!Tag) return false;
5180
John McCalle29c5cd2009-12-10 19:51:03 +00005181 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005182 Diag(Target->getLocation(), diag::note_using_decl_target);
5183 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5184 return true;
5185 }
5186
5187 // No conflict between a tag and a non-tag.
5188 if (!NonTag) return false;
5189
John McCalle29c5cd2009-12-10 19:51:03 +00005190 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00005191 Diag(Target->getLocation(), diag::note_using_decl_target);
5192 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5193 return true;
5194}
5195
John McCall3f746822009-11-17 05:59:44 +00005196/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00005197UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00005198 UsingDecl *UD,
5199 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00005200
5201 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00005202 NamedDecl *Target = Orig;
5203 if (isa<UsingShadowDecl>(Target)) {
5204 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5205 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00005206 }
5207
5208 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00005209 = UsingShadowDecl::Create(Context, CurContext,
5210 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00005211 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00005212
5213 Shadow->setAccess(UD->getAccess());
5214 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5215 Shadow->setInvalidDecl();
5216
John McCall3f746822009-11-17 05:59:44 +00005217 if (S)
John McCall3969e302009-12-08 07:46:18 +00005218 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00005219 else
John McCall3969e302009-12-08 07:46:18 +00005220 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00005221
John McCall3969e302009-12-08 07:46:18 +00005222
John McCall84d87672009-12-10 09:41:52 +00005223 return Shadow;
5224}
John McCall3969e302009-12-08 07:46:18 +00005225
John McCall84d87672009-12-10 09:41:52 +00005226/// Hides a using shadow declaration. This is required by the current
5227/// using-decl implementation when a resolvable using declaration in a
5228/// class is followed by a declaration which would hide or override
5229/// one or more of the using decl's targets; for example:
5230///
5231/// struct Base { void foo(int); };
5232/// struct Derived : Base {
5233/// using Base::foo;
5234/// void foo(int);
5235/// };
5236///
5237/// The governing language is C++03 [namespace.udecl]p12:
5238///
5239/// When a using-declaration brings names from a base class into a
5240/// derived class scope, member functions in the derived class
5241/// override and/or hide member functions with the same name and
5242/// parameter types in a base class (rather than conflicting).
5243///
5244/// There are two ways to implement this:
5245/// (1) optimistically create shadow decls when they're not hidden
5246/// by existing declarations, or
5247/// (2) don't create any shadow decls (or at least don't make them
5248/// visible) until we've fully parsed/instantiated the class.
5249/// The problem with (1) is that we might have to retroactively remove
5250/// a shadow decl, which requires several O(n) operations because the
5251/// decl structures are (very reasonably) not designed for removal.
5252/// (2) avoids this but is very fiddly and phase-dependent.
5253void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00005254 if (Shadow->getDeclName().getNameKind() ==
5255 DeclarationName::CXXConversionFunctionName)
5256 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5257
John McCall84d87672009-12-10 09:41:52 +00005258 // Remove it from the DeclContext...
5259 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005260
John McCall84d87672009-12-10 09:41:52 +00005261 // ...and the scope, if applicable...
5262 if (S) {
John McCall48871652010-08-21 09:40:31 +00005263 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00005264 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00005265 }
5266
John McCall84d87672009-12-10 09:41:52 +00005267 // ...and the using decl.
5268 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5269
5270 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00005271 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00005272}
5273
John McCalle61f2ba2009-11-18 02:36:19 +00005274/// Builds a using declaration.
5275///
5276/// \param IsInstantiation - Whether this call arises from an
5277/// instantiation of an unresolved using declaration. We treat
5278/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00005279NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5280 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005281 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005282 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00005283 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00005284 bool IsInstantiation,
5285 bool IsTypeName,
5286 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00005287 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005288 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00005289 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00005290
Anders Carlssonf038fc22009-08-28 05:49:21 +00005291 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00005292
Anders Carlsson59140b32009-08-28 03:16:11 +00005293 if (SS.isEmpty()) {
5294 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00005295 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00005296 }
Mike Stump11289f42009-09-09 15:08:12 +00005297
John McCall84d87672009-12-10 09:41:52 +00005298 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005299 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00005300 ForRedeclaration);
5301 Previous.setHideTags(false);
5302 if (S) {
5303 LookupName(Previous, S);
5304
5305 // It is really dumb that we have to do this.
5306 LookupResult::Filter F = Previous.makeFilter();
5307 while (F.hasNext()) {
5308 NamedDecl *D = F.next();
5309 if (!isDeclInScope(D, CurContext, S))
5310 F.erase();
5311 }
5312 F.done();
5313 } else {
5314 assert(IsInstantiation && "no scope in non-instantiation");
5315 assert(CurContext->isRecord() && "scope not record in instantiation");
5316 LookupQualifiedName(Previous, CurContext);
5317 }
5318
John McCall84d87672009-12-10 09:41:52 +00005319 // Check for invalid redeclarations.
5320 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5321 return 0;
5322
5323 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00005324 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5325 return 0;
5326
John McCall84c16cf2009-11-12 03:15:40 +00005327 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005328 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005329 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00005330 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00005331 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00005332 // FIXME: not all declaration name kinds are legal here
5333 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5334 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005335 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005336 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00005337 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005338 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5339 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00005340 }
John McCallb96ec562009-12-04 22:46:56 +00005341 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005342 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5343 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00005344 }
John McCallb96ec562009-12-04 22:46:56 +00005345 D->setAccess(AS);
5346 CurContext->addDecl(D);
5347
5348 if (!LookupContext) return D;
5349 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00005350
John McCall0b66eb32010-05-01 00:40:08 +00005351 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00005352 UD->setInvalidDecl();
5353 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00005354 }
5355
Sebastian Redl08905022011-02-05 19:23:19 +00005356 // Constructor inheriting using decls get special treatment.
5357 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00005358 if (CheckInheritedConstructorUsingDecl(UD))
5359 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00005360 return UD;
5361 }
5362
5363 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00005364
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005365 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Francois Pichetefb1af92011-05-23 03:43:44 +00005366 R.setUsingDeclaration(true);
John McCalle61f2ba2009-11-18 02:36:19 +00005367
John McCall3969e302009-12-08 07:46:18 +00005368 // Unlike most lookups, we don't always want to hide tag
5369 // declarations: tag names are visible through the using declaration
5370 // even if hidden by ordinary names, *except* in a dependent context
5371 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00005372 if (!IsInstantiation)
5373 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00005374
John McCall27b18f82009-11-17 02:14:36 +00005375 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00005376
John McCall9f3059a2009-10-09 21:13:30 +00005377 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00005378 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00005379 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005380 UD->setInvalidDecl();
5381 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005382 }
5383
John McCallb96ec562009-12-04 22:46:56 +00005384 if (R.isAmbiguous()) {
5385 UD->setInvalidDecl();
5386 return UD;
5387 }
Mike Stump11289f42009-09-09 15:08:12 +00005388
John McCalle61f2ba2009-11-18 02:36:19 +00005389 if (IsTypeName) {
5390 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00005391 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005392 Diag(IdentLoc, diag::err_using_typename_non_type);
5393 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5394 Diag((*I)->getUnderlyingDecl()->getLocation(),
5395 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005396 UD->setInvalidDecl();
5397 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005398 }
5399 } else {
5400 // If we asked for a non-typename and we got a type, error out,
5401 // but only if this is an instantiation of an unresolved using
5402 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00005403 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00005404 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5405 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00005406 UD->setInvalidDecl();
5407 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00005408 }
Anders Carlsson59140b32009-08-28 03:16:11 +00005409 }
5410
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005411 // C++0x N2914 [namespace.udecl]p6:
5412 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00005413 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005414 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5415 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00005416 UD->setInvalidDecl();
5417 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00005418 }
Mike Stump11289f42009-09-09 15:08:12 +00005419
John McCall84d87672009-12-10 09:41:52 +00005420 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5421 if (!CheckUsingShadowDecl(UD, *I, Previous))
5422 BuildUsingShadowDecl(S, UD, *I);
5423 }
John McCall3f746822009-11-17 05:59:44 +00005424
5425 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00005426}
5427
Sebastian Redl08905022011-02-05 19:23:19 +00005428/// Additional checks for a using declaration referring to a constructor name.
5429bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5430 if (UD->isTypeName()) {
5431 // FIXME: Cannot specify typename when specifying constructor
5432 return true;
5433 }
5434
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005435 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00005436 assert(SourceType &&
5437 "Using decl naming constructor doesn't have type in scope spec.");
5438 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5439
5440 // Check whether the named type is a direct base class.
5441 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5442 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5443 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5444 BaseIt != BaseE; ++BaseIt) {
5445 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5446 if (CanonicalSourceType == BaseType)
5447 break;
5448 }
5449
5450 if (BaseIt == BaseE) {
5451 // Did not find SourceType in the bases.
5452 Diag(UD->getUsingLocation(),
5453 diag::err_using_decl_constructor_not_in_direct_base)
5454 << UD->getNameInfo().getSourceRange()
5455 << QualType(SourceType, 0) << TargetClass;
5456 return true;
5457 }
5458
5459 BaseIt->setInheritConstructors();
5460
5461 return false;
5462}
5463
John McCall84d87672009-12-10 09:41:52 +00005464/// Checks that the given using declaration is not an invalid
5465/// redeclaration. Note that this is checking only for the using decl
5466/// itself, not for any ill-formedness among the UsingShadowDecls.
5467bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5468 bool isTypeName,
5469 const CXXScopeSpec &SS,
5470 SourceLocation NameLoc,
5471 const LookupResult &Prev) {
5472 // C++03 [namespace.udecl]p8:
5473 // C++0x [namespace.udecl]p10:
5474 // A using-declaration is a declaration and can therefore be used
5475 // repeatedly where (and only where) multiple declarations are
5476 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00005477 //
John McCall032092f2010-11-29 18:01:58 +00005478 // That's in non-member contexts.
5479 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00005480 return false;
5481
5482 NestedNameSpecifier *Qual
5483 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5484
5485 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5486 NamedDecl *D = *I;
5487
5488 bool DTypename;
5489 NestedNameSpecifier *DQual;
5490 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5491 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005492 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005493 } else if (UnresolvedUsingValueDecl *UD
5494 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5495 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005496 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005497 } else if (UnresolvedUsingTypenameDecl *UD
5498 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5499 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005500 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00005501 } else continue;
5502
5503 // using decls differ if one says 'typename' and the other doesn't.
5504 // FIXME: non-dependent using decls?
5505 if (isTypeName != DTypename) continue;
5506
5507 // using decls differ if they name different scopes (but note that
5508 // template instantiation can cause this check to trigger when it
5509 // didn't before instantiation).
5510 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5511 Context.getCanonicalNestedNameSpecifier(DQual))
5512 continue;
5513
5514 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00005515 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00005516 return true;
5517 }
5518
5519 return false;
5520}
5521
John McCall3969e302009-12-08 07:46:18 +00005522
John McCallb96ec562009-12-04 22:46:56 +00005523/// Checks that the given nested-name qualifier used in a using decl
5524/// in the current context is appropriately related to the current
5525/// scope. If an error is found, diagnoses it and returns true.
5526bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5527 const CXXScopeSpec &SS,
5528 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00005529 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00005530
John McCall3969e302009-12-08 07:46:18 +00005531 if (!CurContext->isRecord()) {
5532 // C++03 [namespace.udecl]p3:
5533 // C++0x [namespace.udecl]p8:
5534 // A using-declaration for a class member shall be a member-declaration.
5535
5536 // If we weren't able to compute a valid scope, it must be a
5537 // dependent class scope.
5538 if (!NamedContext || NamedContext->isRecord()) {
5539 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5540 << SS.getRange();
5541 return true;
5542 }
5543
5544 // Otherwise, everything is known to be fine.
5545 return false;
5546 }
5547
5548 // The current scope is a record.
5549
5550 // If the named context is dependent, we can't decide much.
5551 if (!NamedContext) {
5552 // FIXME: in C++0x, we can diagnose if we can prove that the
5553 // nested-name-specifier does not refer to a base class, which is
5554 // still possible in some cases.
5555
5556 // Otherwise we have to conservatively report that things might be
5557 // okay.
5558 return false;
5559 }
5560
5561 if (!NamedContext->isRecord()) {
5562 // Ideally this would point at the last name in the specifier,
5563 // but we don't have that level of source info.
5564 Diag(SS.getRange().getBegin(),
5565 diag::err_using_decl_nested_name_specifier_is_not_class)
5566 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5567 return true;
5568 }
5569
Douglas Gregor7c842292010-12-21 07:41:49 +00005570 if (!NamedContext->isDependentContext() &&
5571 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5572 return true;
5573
John McCall3969e302009-12-08 07:46:18 +00005574 if (getLangOptions().CPlusPlus0x) {
5575 // C++0x [namespace.udecl]p3:
5576 // In a using-declaration used as a member-declaration, the
5577 // nested-name-specifier shall name a base class of the class
5578 // being defined.
5579
5580 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5581 cast<CXXRecordDecl>(NamedContext))) {
5582 if (CurContext == NamedContext) {
5583 Diag(NameLoc,
5584 diag::err_using_decl_nested_name_specifier_is_current_class)
5585 << SS.getRange();
5586 return true;
5587 }
5588
5589 Diag(SS.getRange().getBegin(),
5590 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5591 << (NestedNameSpecifier*) SS.getScopeRep()
5592 << cast<CXXRecordDecl>(CurContext)
5593 << SS.getRange();
5594 return true;
5595 }
5596
5597 return false;
5598 }
5599
5600 // C++03 [namespace.udecl]p4:
5601 // A using-declaration used as a member-declaration shall refer
5602 // to a member of a base class of the class being defined [etc.].
5603
5604 // Salient point: SS doesn't have to name a base class as long as
5605 // lookup only finds members from base classes. Therefore we can
5606 // diagnose here only if we can prove that that can't happen,
5607 // i.e. if the class hierarchies provably don't intersect.
5608
5609 // TODO: it would be nice if "definitely valid" results were cached
5610 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5611 // need to be repeated.
5612
5613 struct UserData {
5614 llvm::DenseSet<const CXXRecordDecl*> Bases;
5615
5616 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5617 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5618 Data->Bases.insert(Base);
5619 return true;
5620 }
5621
5622 bool hasDependentBases(const CXXRecordDecl *Class) {
5623 return !Class->forallBases(collect, this);
5624 }
5625
5626 /// Returns true if the base is dependent or is one of the
5627 /// accumulated base classes.
5628 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5629 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5630 return !Data->Bases.count(Base);
5631 }
5632
5633 bool mightShareBases(const CXXRecordDecl *Class) {
5634 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5635 }
5636 };
5637
5638 UserData Data;
5639
5640 // Returns false if we find a dependent base.
5641 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5642 return false;
5643
5644 // Returns false if the class has a dependent base or if it or one
5645 // of its bases is present in the base set of the current context.
5646 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5647 return false;
5648
5649 Diag(SS.getRange().getBegin(),
5650 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5651 << (NestedNameSpecifier*) SS.getScopeRep()
5652 << cast<CXXRecordDecl>(CurContext)
5653 << SS.getRange();
5654
5655 return true;
John McCallb96ec562009-12-04 22:46:56 +00005656}
5657
Richard Smithdda56e42011-04-15 14:24:37 +00005658Decl *Sema::ActOnAliasDeclaration(Scope *S,
5659 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005660 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00005661 SourceLocation UsingLoc,
5662 UnqualifiedId &Name,
5663 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00005664 // Skip up to the relevant declaration scope.
5665 while (S->getFlags() & Scope::TemplateParamScope)
5666 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00005667 assert((S->getFlags() & Scope::DeclScope) &&
5668 "got alias-declaration outside of declaration scope");
5669
5670 if (Type.isInvalid())
5671 return 0;
5672
5673 bool Invalid = false;
5674 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5675 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00005676 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00005677
5678 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5679 return 0;
5680
5681 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00005682 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00005683 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005684 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5685 TInfo->getTypeLoc().getBeginLoc());
5686 }
Richard Smithdda56e42011-04-15 14:24:37 +00005687
5688 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5689 LookupName(Previous, S);
5690
5691 // Warn about shadowing the name of a template parameter.
5692 if (Previous.isSingleResult() &&
5693 Previous.getFoundDecl()->isTemplateParameter()) {
5694 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5695 Previous.getFoundDecl()))
5696 Invalid = true;
5697 Previous.clear();
5698 }
5699
5700 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5701 "name in alias declaration must be an identifier");
5702 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5703 Name.StartLocation,
5704 Name.Identifier, TInfo);
5705
5706 NewTD->setAccess(AS);
5707
5708 if (Invalid)
5709 NewTD->setInvalidDecl();
5710
Richard Smith3f1b5d02011-05-05 21:57:07 +00005711 CheckTypedefForVariablyModifiedType(S, NewTD);
5712 Invalid |= NewTD->isInvalidDecl();
5713
Richard Smithdda56e42011-04-15 14:24:37 +00005714 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00005715
5716 NamedDecl *NewND;
5717 if (TemplateParamLists.size()) {
5718 TypeAliasTemplateDecl *OldDecl = 0;
5719 TemplateParameterList *OldTemplateParams = 0;
5720
5721 if (TemplateParamLists.size() != 1) {
5722 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5723 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5724 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5725 }
5726 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5727
5728 // Only consider previous declarations in the same scope.
5729 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5730 /*ExplicitInstantiationOrSpecialization*/false);
5731 if (!Previous.empty()) {
5732 Redeclaration = true;
5733
5734 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5735 if (!OldDecl && !Invalid) {
5736 Diag(UsingLoc, diag::err_redefinition_different_kind)
5737 << Name.Identifier;
5738
5739 NamedDecl *OldD = Previous.getRepresentativeDecl();
5740 if (OldD->getLocation().isValid())
5741 Diag(OldD->getLocation(), diag::note_previous_definition);
5742
5743 Invalid = true;
5744 }
5745
5746 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5747 if (TemplateParameterListsAreEqual(TemplateParams,
5748 OldDecl->getTemplateParameters(),
5749 /*Complain=*/true,
5750 TPL_TemplateMatch))
5751 OldTemplateParams = OldDecl->getTemplateParameters();
5752 else
5753 Invalid = true;
5754
5755 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5756 if (!Invalid &&
5757 !Context.hasSameType(OldTD->getUnderlyingType(),
5758 NewTD->getUnderlyingType())) {
5759 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5760 // but we can't reasonably accept it.
5761 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5762 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5763 if (OldTD->getLocation().isValid())
5764 Diag(OldTD->getLocation(), diag::note_previous_definition);
5765 Invalid = true;
5766 }
5767 }
5768 }
5769
5770 // Merge any previous default template arguments into our parameters,
5771 // and check the parameter list.
5772 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5773 TPC_TypeAliasTemplate))
5774 return 0;
5775
5776 TypeAliasTemplateDecl *NewDecl =
5777 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5778 Name.Identifier, TemplateParams,
5779 NewTD);
5780
5781 NewDecl->setAccess(AS);
5782
5783 if (Invalid)
5784 NewDecl->setInvalidDecl();
5785 else if (OldDecl)
5786 NewDecl->setPreviousDeclaration(OldDecl);
5787
5788 NewND = NewDecl;
5789 } else {
5790 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5791 NewND = NewTD;
5792 }
Richard Smithdda56e42011-04-15 14:24:37 +00005793
5794 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00005795 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00005796
Richard Smith3f1b5d02011-05-05 21:57:07 +00005797 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00005798}
5799
John McCall48871652010-08-21 09:40:31 +00005800Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005801 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005802 SourceLocation AliasLoc,
5803 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005804 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00005805 SourceLocation IdentLoc,
5806 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00005807
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005808 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00005809 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5810 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005811
Anders Carlssondca83c42009-03-28 06:23:46 +00005812 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00005813 NamedDecl *PrevDecl
5814 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5815 ForRedeclaration);
5816 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5817 PrevDecl = 0;
5818
5819 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005820 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00005821 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005822 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00005823 // FIXME: At some point, we'll want to create the (redundant)
5824 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00005825 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00005826 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00005827 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00005828 }
Mike Stump11289f42009-09-09 15:08:12 +00005829
Anders Carlssondca83c42009-03-28 06:23:46 +00005830 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5831 diag::err_redefinition_different_kind;
5832 Diag(AliasLoc, DiagID) << Alias;
5833 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00005834 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00005835 }
5836
John McCall27b18f82009-11-17 02:14:36 +00005837 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00005838 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005839
John McCall9f3059a2009-10-09 21:13:30 +00005840 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005841 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005842 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00005843 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00005844 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00005845 }
Mike Stump11289f42009-09-09 15:08:12 +00005846
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005847 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00005848 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00005849 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00005850 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00005851
John McCalld8d0d432010-02-16 06:53:13 +00005852 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00005853 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00005854}
5855
Douglas Gregora57478e2010-05-01 15:04:51 +00005856namespace {
5857 /// \brief Scoped object used to handle the state changes required in Sema
5858 /// to implicitly define the body of a C++ member function;
5859 class ImplicitlyDefinedFunctionScope {
5860 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00005861 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00005862
5863 public:
5864 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00005865 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00005866 {
Douglas Gregora57478e2010-05-01 15:04:51 +00005867 S.PushFunctionScope();
5868 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5869 }
5870
5871 ~ImplicitlyDefinedFunctionScope() {
5872 S.PopExpressionEvaluationContext();
5873 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00005874 }
5875 };
5876}
5877
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005878Sema::ImplicitExceptionSpecification
5879Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00005880 // C++ [except.spec]p14:
5881 // An implicitly declared special member function (Clause 12) shall have an
5882 // exception-specification. [...]
5883 ImplicitExceptionSpecification ExceptSpec(Context);
5884
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005885 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005886 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5887 BEnd = ClassDecl->bases_end();
5888 B != BEnd; ++B) {
5889 if (B->isVirtual()) // Handled below.
5890 continue;
5891
Douglas Gregor9672f922010-07-03 00:47:00 +00005892 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5893 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005894 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5895 // If this is a deleted function, add it anyway. This might be conformant
5896 // with the standard. This might not. I'm not sure. It might not matter.
5897 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005898 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005899 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005900 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005901
5902 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005903 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5904 BEnd = ClassDecl->vbases_end();
5905 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00005906 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5907 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00005908 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5909 // If this is a deleted function, add it anyway. This might be conformant
5910 // with the standard. This might not. I'm not sure. It might not matter.
5911 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005912 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005913 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005914 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005915
5916 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00005917 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5918 FEnd = ClassDecl->field_end();
5919 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00005920 if (F->hasInClassInitializer()) {
5921 if (Expr *E = F->getInClassInitializer())
5922 ExceptSpec.CalledExpr(E);
5923 else if (!F->isInvalidDecl())
5924 ExceptSpec.SetDelayed();
5925 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00005926 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00005927 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5928 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5929 // If this is a deleted function, add it anyway. This might be conformant
5930 // with the standard. This might not. I'm not sure. It might not matter.
5931 // In particular, the problem is that this function never gets called. It
5932 // might just be ill-formed because this function attempts to refer to
5933 // a deleted function here.
5934 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00005935 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00005936 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00005937 }
John McCalldb40c7f2010-12-14 08:05:40 +00005938
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005939 return ExceptSpec;
5940}
5941
5942CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5943 CXXRecordDecl *ClassDecl) {
5944 // C++ [class.ctor]p5:
5945 // A default constructor for a class X is a constructor of class X
5946 // that can be called without an argument. If there is no
5947 // user-declared constructor for class X, a default constructor is
5948 // implicitly declared. An implicitly-declared default constructor
5949 // is an inline public member of its class.
5950 assert(!ClassDecl->hasUserDeclaredConstructor() &&
5951 "Should not build implicit default constructor!");
5952
5953 ImplicitExceptionSpecification Spec =
5954 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5955 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00005956
Douglas Gregor6d880b12010-07-01 22:31:05 +00005957 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005958 CanQualType ClassType
5959 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005960 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005961 DeclarationName Name
5962 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005963 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005964 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00005965 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005966 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005967 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005968 /*TInfo=*/0,
5969 /*isExplicit=*/false,
5970 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00005971 /*isImplicitlyDeclared=*/true);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005972 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00005973 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005974 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00005975 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00005976
5977 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00005978 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5979
Douglas Gregor0be31a22010-07-02 17:43:08 +00005980 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00005981 PushOnScopeChains(DefaultCon, S, false);
5982 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00005983
5984 if (ShouldDeleteDefaultConstructor(DefaultCon))
5985 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00005986
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005987 return DefaultCon;
5988}
5989
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00005990void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5991 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00005992 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00005993 !Constructor->doesThisDeclarationHaveABody() &&
5994 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00005995 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005996
Anders Carlsson423f5d82010-04-23 16:04:08 +00005997 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00005998 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00005999
Douglas Gregora57478e2010-05-01 15:04:51 +00006000 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006001 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00006002 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006003 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006004 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00006005 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00006006 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00006007 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00006008 }
Douglas Gregor73193272010-09-20 16:48:21 +00006009
6010 SourceLocation Loc = Constructor->getLocation();
6011 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6012
6013 Constructor->setUsed();
6014 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006015
6016 if (ASTMutationListener *L = getASTMutationListener()) {
6017 L->CompletedImplicitDefinition(Constructor);
6018 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006019}
6020
Richard Smith938f40b2011-06-11 17:19:42 +00006021/// Get any existing defaulted default constructor for the given class. Do not
6022/// implicitly define one if it does not exist.
6023static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6024 CXXRecordDecl *D) {
6025 ASTContext &Context = Self.Context;
6026 QualType ClassType = Context.getTypeDeclType(D);
6027 DeclarationName ConstructorName
6028 = Context.DeclarationNames.getCXXConstructorName(
6029 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6030
6031 DeclContext::lookup_const_iterator Con, ConEnd;
6032 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6033 Con != ConEnd; ++Con) {
6034 // A function template cannot be defaulted.
6035 if (isa<FunctionTemplateDecl>(*Con))
6036 continue;
6037
6038 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6039 if (Constructor->isDefaultConstructor())
6040 return Constructor->isDefaulted() ? Constructor : 0;
6041 }
6042 return 0;
6043}
6044
6045void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6046 if (!D) return;
6047 AdjustDeclIfTemplate(D);
6048
6049 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6050 CXXConstructorDecl *CtorDecl
6051 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6052
6053 if (!CtorDecl) return;
6054
6055 // Compute the exception specification for the default constructor.
6056 const FunctionProtoType *CtorTy =
6057 CtorDecl->getType()->castAs<FunctionProtoType>();
6058 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6059 ImplicitExceptionSpecification Spec =
6060 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6061 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6062 assert(EPI.ExceptionSpecType != EST_Delayed);
6063
6064 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6065 }
6066
6067 // If the default constructor is explicitly defaulted, checking the exception
6068 // specification is deferred until now.
6069 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6070 !ClassDecl->isDependentType())
6071 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6072}
6073
Sebastian Redl08905022011-02-05 19:23:19 +00006074void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6075 // We start with an initial pass over the base classes to collect those that
6076 // inherit constructors from. If there are none, we can forgo all further
6077 // processing.
6078 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6079 BasesVector BasesToInheritFrom;
6080 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6081 BaseE = ClassDecl->bases_end();
6082 BaseIt != BaseE; ++BaseIt) {
6083 if (BaseIt->getInheritConstructors()) {
6084 QualType Base = BaseIt->getType();
6085 if (Base->isDependentType()) {
6086 // If we inherit constructors from anything that is dependent, just
6087 // abort processing altogether. We'll get another chance for the
6088 // instantiations.
6089 return;
6090 }
6091 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6092 }
6093 }
6094 if (BasesToInheritFrom.empty())
6095 return;
6096
6097 // Now collect the constructors that we already have in the current class.
6098 // Those take precedence over inherited constructors.
6099 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6100 // unless there is a user-declared constructor with the same signature in
6101 // the class where the using-declaration appears.
6102 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6103 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6104 CtorE = ClassDecl->ctor_end();
6105 CtorIt != CtorE; ++CtorIt) {
6106 ExistingConstructors.insert(
6107 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6108 }
6109
6110 Scope *S = getScopeForContext(ClassDecl);
6111 DeclarationName CreatedCtorName =
6112 Context.DeclarationNames.getCXXConstructorName(
6113 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6114
6115 // Now comes the true work.
6116 // First, we keep a map from constructor types to the base that introduced
6117 // them. Needed for finding conflicting constructors. We also keep the
6118 // actually inserted declarations in there, for pretty diagnostics.
6119 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6120 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6121 ConstructorToSourceMap InheritedConstructors;
6122 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6123 BaseE = BasesToInheritFrom.end();
6124 BaseIt != BaseE; ++BaseIt) {
6125 const RecordType *Base = *BaseIt;
6126 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6127 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6128 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6129 CtorE = BaseDecl->ctor_end();
6130 CtorIt != CtorE; ++CtorIt) {
6131 // Find the using declaration for inheriting this base's constructors.
6132 DeclarationName Name =
6133 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6134 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6135 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6136 SourceLocation UsingLoc = UD ? UD->getLocation() :
6137 ClassDecl->getLocation();
6138
6139 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6140 // from the class X named in the using-declaration consists of actual
6141 // constructors and notional constructors that result from the
6142 // transformation of defaulted parameters as follows:
6143 // - all non-template default constructors of X, and
6144 // - for each non-template constructor of X that has at least one
6145 // parameter with a default argument, the set of constructors that
6146 // results from omitting any ellipsis parameter specification and
6147 // successively omitting parameters with a default argument from the
6148 // end of the parameter-type-list.
6149 CXXConstructorDecl *BaseCtor = *CtorIt;
6150 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6151 const FunctionProtoType *BaseCtorType =
6152 BaseCtor->getType()->getAs<FunctionProtoType>();
6153
6154 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6155 maxParams = BaseCtor->getNumParams();
6156 params <= maxParams; ++params) {
6157 // Skip default constructors. They're never inherited.
6158 if (params == 0)
6159 continue;
6160 // Skip copy and move constructors for the same reason.
6161 if (CanBeCopyOrMove && params == 1)
6162 continue;
6163
6164 // Build up a function type for this particular constructor.
6165 // FIXME: The working paper does not consider that the exception spec
6166 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00006167 // source. This code doesn't yet, either. When it does, this code will
6168 // need to be delayed until after exception specifications and in-class
6169 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00006170 const Type *NewCtorType;
6171 if (params == maxParams)
6172 NewCtorType = BaseCtorType;
6173 else {
6174 llvm::SmallVector<QualType, 16> Args;
6175 for (unsigned i = 0; i < params; ++i) {
6176 Args.push_back(BaseCtorType->getArgType(i));
6177 }
6178 FunctionProtoType::ExtProtoInfo ExtInfo =
6179 BaseCtorType->getExtProtoInfo();
6180 ExtInfo.Variadic = false;
6181 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6182 Args.data(), params, ExtInfo)
6183 .getTypePtr();
6184 }
6185 const Type *CanonicalNewCtorType =
6186 Context.getCanonicalType(NewCtorType);
6187
6188 // Now that we have the type, first check if the class already has a
6189 // constructor with this signature.
6190 if (ExistingConstructors.count(CanonicalNewCtorType))
6191 continue;
6192
6193 // Then we check if we have already declared an inherited constructor
6194 // with this signature.
6195 std::pair<ConstructorToSourceMap::iterator, bool> result =
6196 InheritedConstructors.insert(std::make_pair(
6197 CanonicalNewCtorType,
6198 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6199 if (!result.second) {
6200 // Already in the map. If it came from a different class, that's an
6201 // error. Not if it's from the same.
6202 CanQualType PreviousBase = result.first->second.first;
6203 if (CanonicalBase != PreviousBase) {
6204 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6205 const CXXConstructorDecl *PrevBaseCtor =
6206 PrevCtor->getInheritedConstructor();
6207 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6208
6209 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6210 Diag(BaseCtor->getLocation(),
6211 diag::note_using_decl_constructor_conflict_current_ctor);
6212 Diag(PrevBaseCtor->getLocation(),
6213 diag::note_using_decl_constructor_conflict_previous_ctor);
6214 Diag(PrevCtor->getLocation(),
6215 diag::note_using_decl_constructor_conflict_previous_using);
6216 }
6217 continue;
6218 }
6219
6220 // OK, we're there, now add the constructor.
6221 // C++0x [class.inhctor]p8: [...] that would be performed by a
6222 // user-writtern inline constructor [...]
6223 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6224 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00006225 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6226 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00006227 /*ImplicitlyDeclared=*/true);
Sebastian Redl08905022011-02-05 19:23:19 +00006228 NewCtor->setAccess(BaseCtor->getAccess());
6229
6230 // Build up the parameter decls and add them.
6231 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6232 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006233 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6234 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00006235 /*IdentifierInfo=*/0,
6236 BaseCtorType->getArgType(i),
6237 /*TInfo=*/0, SC_None,
6238 SC_None, /*DefaultArg=*/0));
6239 }
6240 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6241 NewCtor->setInheritedConstructor(BaseCtor);
6242
6243 PushOnScopeChains(NewCtor, S, false);
6244 ClassDecl->addDecl(NewCtor);
6245 result.first->second.second = NewCtor;
6246 }
6247 }
6248 }
6249}
6250
Alexis Huntf91729462011-05-12 22:46:25 +00006251Sema::ImplicitExceptionSpecification
6252Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00006253 // C++ [except.spec]p14:
6254 // An implicitly declared special member function (Clause 12) shall have
6255 // an exception-specification.
6256 ImplicitExceptionSpecification ExceptSpec(Context);
6257
6258 // Direct base-class destructors.
6259 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6260 BEnd = ClassDecl->bases_end();
6261 B != BEnd; ++B) {
6262 if (B->isVirtual()) // Handled below.
6263 continue;
6264
6265 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6266 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006267 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006268 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006269
Douglas Gregorf1203042010-07-01 19:09:28 +00006270 // Virtual base-class destructors.
6271 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6272 BEnd = ClassDecl->vbases_end();
6273 B != BEnd; ++B) {
6274 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6275 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006276 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006277 }
Sebastian Redl623ea822011-05-19 05:13:44 +00006278
Douglas Gregorf1203042010-07-01 19:09:28 +00006279 // Field destructors.
6280 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6281 FEnd = ClassDecl->field_end();
6282 F != FEnd; ++F) {
6283 if (const RecordType *RecordTy
6284 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6285 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00006286 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00006287 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006288
Alexis Huntf91729462011-05-12 22:46:25 +00006289 return ExceptSpec;
6290}
6291
6292CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6293 // C++ [class.dtor]p2:
6294 // If a class has no user-declared destructor, a destructor is
6295 // declared implicitly. An implicitly-declared destructor is an
6296 // inline public member of its class.
6297
6298 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00006299 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00006300 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6301
Douglas Gregor7454c562010-07-02 20:37:36 +00006302 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00006303 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006304
Douglas Gregorf1203042010-07-01 19:09:28 +00006305 CanQualType ClassType
6306 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00006307 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00006308 DeclarationName Name
6309 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006310 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00006311 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006312 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6313 /*isInline=*/true,
6314 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00006315 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00006316 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00006317 Destructor->setImplicit();
6318 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00006319
6320 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00006321 ++ASTContext::NumImplicitDestructorsDeclared;
6322
6323 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006324 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00006325 PushOnScopeChains(Destructor, S, false);
6326 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00006327
6328 // This could be uniqued if it ever proves significant.
6329 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00006330
6331 if (ShouldDeleteDestructor(Destructor))
6332 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00006333
6334 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00006335
Douglas Gregorf1203042010-07-01 19:09:28 +00006336 return Destructor;
6337}
6338
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006339void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00006340 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006341 assert((Destructor->isDefaulted() &&
6342 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006343 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00006344 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006345 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006346
Douglas Gregor54818f02010-05-12 16:39:35 +00006347 if (Destructor->isInvalidDecl())
6348 return;
6349
Douglas Gregora57478e2010-05-01 15:04:51 +00006350 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006351
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006352 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00006353 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6354 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00006355
Douglas Gregor54818f02010-05-12 16:39:35 +00006356 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00006357 Diag(CurrentLocation, diag::note_member_synthesized_at)
6358 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6359
6360 Destructor->setInvalidDecl();
6361 return;
6362 }
6363
Douglas Gregor73193272010-09-20 16:48:21 +00006364 SourceLocation Loc = Destructor->getLocation();
6365 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6366
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006367 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006368 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00006369
6370 if (ASTMutationListener *L = getASTMutationListener()) {
6371 L->CompletedImplicitDefinition(Destructor);
6372 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006373}
6374
Sebastian Redl623ea822011-05-19 05:13:44 +00006375void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6376 CXXDestructorDecl *destructor) {
6377 // C++11 [class.dtor]p3:
6378 // A declaration of a destructor that does not have an exception-
6379 // specification is implicitly considered to have the same exception-
6380 // specification as an implicit declaration.
6381 const FunctionProtoType *dtorType = destructor->getType()->
6382 getAs<FunctionProtoType>();
6383 if (dtorType->hasExceptionSpec())
6384 return;
6385
6386 ImplicitExceptionSpecification exceptSpec =
6387 ComputeDefaultedDtorExceptionSpec(classDecl);
6388
6389 // Replace the destructor's type.
6390 FunctionProtoType::ExtProtoInfo epi;
6391 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6392 epi.NumExceptions = exceptSpec.size();
6393 epi.Exceptions = exceptSpec.data();
6394 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6395
6396 destructor->setType(ty);
6397
6398 // FIXME: If the destructor has a body that could throw, and the newly created
6399 // spec doesn't allow exceptions, we should emit a warning, because this
6400 // change in behavior can break conforming C++03 programs at runtime.
6401 // However, we don't have a body yet, so it needs to be done somewhere else.
6402}
6403
Douglas Gregorb139cd52010-05-01 20:49:11 +00006404/// \brief Builds a statement that copies the given entity from \p From to
6405/// \c To.
6406///
6407/// This routine is used to copy the members of a class with an
6408/// implicitly-declared copy assignment operator. When the entities being
6409/// copied are arrays, this routine builds for loops to copy them.
6410///
6411/// \param S The Sema object used for type-checking.
6412///
6413/// \param Loc The location where the implicit copy is being generated.
6414///
6415/// \param T The type of the expressions being copied. Both expressions must
6416/// have this type.
6417///
6418/// \param To The expression we are copying to.
6419///
6420/// \param From The expression we are copying from.
6421///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006422/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6423/// Otherwise, it's a non-static member subobject.
6424///
Douglas Gregorb139cd52010-05-01 20:49:11 +00006425/// \param Depth Internal parameter recording the depth of the recursion.
6426///
6427/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00006428static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00006429BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00006430 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006431 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006432 // C++0x [class.copy]p30:
6433 // Each subobject is assigned in the manner appropriate to its type:
6434 //
6435 // - if the subobject is of class type, the copy assignment operator
6436 // for the class is used (as if by explicit qualification; that is,
6437 // ignoring any possible virtual overriding functions in more derived
6438 // classes);
6439 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6440 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6441
6442 // Look for operator=.
6443 DeclarationName Name
6444 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6445 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6446 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6447
6448 // Filter out any result that isn't a copy-assignment operator.
6449 LookupResult::Filter F = OpLookup.makeFilter();
6450 while (F.hasNext()) {
6451 NamedDecl *D = F.next();
6452 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6453 if (Method->isCopyAssignmentOperator())
6454 continue;
6455
6456 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00006457 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006458 F.done();
6459
Douglas Gregor40c92bb2010-05-04 15:20:55 +00006460 // Suppress the protected check (C++ [class.protected]) for each of the
6461 // assignment operators we found. This strange dance is required when
6462 // we're assigning via a base classes's copy-assignment operator. To
6463 // ensure that we're getting the right base class subobject (without
6464 // ambiguities), we need to cast "this" to that subobject type; to
6465 // ensure that we don't go through the virtual call mechanism, we need
6466 // to qualify the operator= name with the base class (see below). However,
6467 // this means that if the base class has a protected copy assignment
6468 // operator, the protected member access check will fail. So, we
6469 // rewrite "protected" access to "public" access in this case, since we
6470 // know by construction that we're calling from a derived class.
6471 if (CopyingBaseSubobject) {
6472 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6473 L != LEnd; ++L) {
6474 if (L.getAccess() == AS_protected)
6475 L.setAccess(AS_public);
6476 }
6477 }
6478
Douglas Gregorb139cd52010-05-01 20:49:11 +00006479 // Create the nested-name-specifier that will be used to qualify the
6480 // reference to operator=; this is required to suppress the virtual
6481 // call mechanism.
6482 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00006483 SS.MakeTrivial(S.Context,
6484 NestedNameSpecifier::Create(S.Context, 0, false,
6485 T.getTypePtr()),
6486 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006487
6488 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00006489 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00006490 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006491 /*FirstQualifierInScope=*/0, OpLookup,
6492 /*TemplateArgs=*/0,
6493 /*SuppressQualifierCheck=*/true);
6494 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006495 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006496
6497 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00006498
John McCalldadc5752010-08-24 06:29:42 +00006499 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006500 OpEqualRef.takeAs<Expr>(),
6501 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006502 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006503 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006504
6505 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006506 }
John McCallab8c2732010-03-16 06:11:48 +00006507
Douglas Gregorb139cd52010-05-01 20:49:11 +00006508 // - if the subobject is of scalar type, the built-in assignment
6509 // operator is used.
6510 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6511 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00006512 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006513 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006514 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006515
6516 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006517 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006518
6519 // - if the subobject is an array, each element is assigned, in the
6520 // manner appropriate to the element type;
6521
6522 // Construct a loop over the array bounds, e.g.,
6523 //
6524 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6525 //
6526 // that will copy each of the array elements.
6527 QualType SizeType = S.Context.getSizeType();
6528
6529 // Create the iteration variable.
6530 IdentifierInfo *IterationVarName = 0;
6531 {
6532 llvm::SmallString<8> Str;
6533 llvm::raw_svector_ostream OS(Str);
6534 OS << "__i" << Depth;
6535 IterationVarName = &S.Context.Idents.get(OS.str());
6536 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00006537 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006538 IterationVarName, SizeType,
6539 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006540 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006541
6542 // Initialize the iteration variable to zero.
6543 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006544 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006545
6546 // Create a reference to the iteration variable; we'll use this several
6547 // times throughout.
6548 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00006549 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006550 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6551
6552 // Create the DeclStmt that holds the iteration variable.
6553 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6554
6555 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006556 llvm::APInt Upper
6557 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00006558 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00006559 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00006560 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6561 BO_NE, S.Context.BoolTy,
6562 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006563
6564 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006565 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00006566 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6567 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006568
6569 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00006570 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6571 IterationVarRef, Loc));
6572 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6573 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00006574
6575 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00006576 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6577 To, From, CopyingBaseSubobject,
6578 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00006579 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006580 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006581
6582 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00006583 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00006584 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00006585 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00006586 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006587}
6588
Alexis Hunt119f3652011-05-14 05:23:20 +00006589std::pair<Sema::ImplicitExceptionSpecification, bool>
6590Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6591 CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006592 // C++ [class.copy]p10:
6593 // If the class definition does not explicitly declare a copy
6594 // assignment operator, one is declared implicitly.
6595 // The implicitly-defined copy assignment operator for a class X
6596 // will have the form
6597 //
6598 // X& X::operator=(const X&)
6599 //
6600 // if
6601 bool HasConstCopyAssignment = true;
6602
6603 // -- each direct base class B of X has a copy assignment operator
6604 // whose parameter is of type const B&, const volatile B& or B,
6605 // and
6606 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6607 BaseEnd = ClassDecl->bases_end();
6608 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006609 // We'll handle this below
6610 if (LangOpts.CPlusPlus0x && Base->isVirtual())
6611 continue;
6612
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006613 assert(!Base->getType()->isDependentType() &&
6614 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00006615 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6616 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6617 &HasConstCopyAssignment);
6618 }
6619
6620 // In C++0x, the above citation has "or virtual added"
6621 if (LangOpts.CPlusPlus0x) {
6622 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6623 BaseEnd = ClassDecl->vbases_end();
6624 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6625 assert(!Base->getType()->isDependentType() &&
6626 "Cannot generate implicit members for class with dependent bases.");
6627 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6628 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6629 &HasConstCopyAssignment);
6630 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006631 }
6632
6633 // -- for all the nonstatic data members of X that are of a class
6634 // type M (or array thereof), each such class type has a copy
6635 // assignment operator whose parameter is of type const M&,
6636 // const volatile M& or M.
6637 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6638 FieldEnd = ClassDecl->field_end();
6639 HasConstCopyAssignment && Field != FieldEnd;
6640 ++Field) {
6641 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006642 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6643 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6644 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006645 }
6646 }
6647
6648 // Otherwise, the implicitly declared copy assignment operator will
6649 // have the form
6650 //
6651 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006652
Douglas Gregor68e11362010-07-01 17:48:08 +00006653 // C++ [except.spec]p14:
6654 // An implicitly declared special member function (Clause 12) shall have an
6655 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00006656
6657 // It is unspecified whether or not an implicit copy assignment operator
6658 // attempts to deduplicate calls to assignment operators of virtual bases are
6659 // made. As such, this exception specification is effectively unspecified.
6660 // Based on a similar decision made for constness in C++0x, we're erring on
6661 // the side of assuming such calls to be made regardless of whether they
6662 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00006663 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00006664 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00006665 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6666 BaseEnd = ClassDecl->bases_end();
6667 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00006668 if (Base->isVirtual())
6669 continue;
6670
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006671 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00006672 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00006673 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6674 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00006675 ExceptSpec.CalledDecl(CopyAssign);
6676 }
Alexis Hunt491ec602011-06-21 23:42:56 +00006677
6678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6679 BaseEnd = ClassDecl->vbases_end();
6680 Base != BaseEnd; ++Base) {
6681 CXXRecordDecl *BaseClassDecl
6682 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6683 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6684 ArgQuals, false, 0))
6685 ExceptSpec.CalledDecl(CopyAssign);
6686 }
6687
Douglas Gregor68e11362010-07-01 17:48:08 +00006688 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6689 FieldEnd = ClassDecl->field_end();
6690 Field != FieldEnd;
6691 ++Field) {
6692 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00006693 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6694 if (CXXMethodDecl *CopyAssign =
6695 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6696 ExceptSpec.CalledDecl(CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00006697 }
6698 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006699
Alexis Hunt119f3652011-05-14 05:23:20 +00006700 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6701}
6702
6703CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6704 // Note: The following rules are largely analoguous to the copy
6705 // constructor rules. Note that virtual bases are not taken into account
6706 // for determining the argument type of the operator. Note also that
6707 // operators taking an object instead of a reference are allowed.
6708
6709 ImplicitExceptionSpecification Spec(Context);
6710 bool Const;
6711 llvm::tie(Spec, Const) =
6712 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6713
6714 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6715 QualType RetType = Context.getLValueReferenceType(ArgType);
6716 if (Const)
6717 ArgType = ArgType.withConst();
6718 ArgType = Context.getLValueReferenceType(ArgType);
6719
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006720 // An implicitly-declared copy assignment operator is an inline public
6721 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00006722 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006723 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00006724 SourceLocation ClassLoc = ClassDecl->getLocation();
6725 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006726 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00006727 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00006728 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006729 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00006730 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00006731 /*isInline=*/true,
6732 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006733 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00006734 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006735 CopyAssignment->setImplicit();
6736 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006737
6738 // Add the parameter to the operator.
6739 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006740 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006741 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00006742 SC_None,
6743 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006744 CopyAssignment->setParams(&FromParam, 1);
6745
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006746 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006747 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00006748
Douglas Gregor0be31a22010-07-02 17:43:08 +00006749 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006750 PushOnScopeChains(CopyAssignment, S, false);
6751 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006752
Alexis Huntd74c85f2011-06-22 01:05:13 +00006753 // C++0x [class.copy]p18:
6754 // ... If the class definition declares a move constructor or move
6755 // assignment operator, the implicitly declared copy assignment operator is
6756 // defined as deleted; ...
6757 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6758 ClassDecl->hasUserDeclaredMoveAssignment() ||
6759 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00006760 CopyAssignment->setDeletedAsWritten();
6761
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00006762 AddOverriddenMethods(ClassDecl, CopyAssignment);
6763 return CopyAssignment;
6764}
6765
Douglas Gregorb139cd52010-05-01 20:49:11 +00006766void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6767 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00006768 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006769 CopyAssignOperator->isOverloadedOperator() &&
6770 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00006771 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00006772 "DefineImplicitCopyAssignment called for wrong function");
6773
6774 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6775
6776 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6777 CopyAssignOperator->setInvalidDecl();
6778 return;
6779 }
6780
6781 CopyAssignOperator->setUsed();
6782
6783 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006784 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006785
6786 // C++0x [class.copy]p30:
6787 // The implicitly-defined or explicitly-defaulted copy assignment operator
6788 // for a non-union class X performs memberwise copy assignment of its
6789 // subobjects. The direct base classes of X are assigned first, in the
6790 // order of their declaration in the base-specifier-list, and then the
6791 // immediate non-static data members of X are assigned, in the order in
6792 // which they were declared in the class definition.
6793
6794 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00006795 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006796
6797 // The parameter for the "other" object, which we are copying from.
6798 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6799 Qualifiers OtherQuals = Other->getType().getQualifiers();
6800 QualType OtherRefType = Other->getType();
6801 if (const LValueReferenceType *OtherRef
6802 = OtherRefType->getAs<LValueReferenceType>()) {
6803 OtherRefType = OtherRef->getPointeeType();
6804 OtherQuals = OtherRefType.getQualifiers();
6805 }
6806
6807 // Our location for everything implicitly-generated.
6808 SourceLocation Loc = CopyAssignOperator->getLocation();
6809
6810 // Construct a reference to the "other" object. We'll be using this
6811 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00006812 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006813 assert(OtherRef && "Reference to parameter cannot fail!");
6814
6815 // Construct the "this" pointer. We'll be using this throughout the generated
6816 // ASTs.
6817 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6818 assert(This && "Reference to this cannot fail!");
6819
6820 // Assign base classes.
6821 bool Invalid = false;
6822 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6823 E = ClassDecl->bases_end(); Base != E; ++Base) {
6824 // Form the assignment:
6825 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6826 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00006827 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006828 Invalid = true;
6829 continue;
6830 }
6831
John McCallcf142162010-08-07 06:22:56 +00006832 CXXCastPath BasePath;
6833 BasePath.push_back(Base);
6834
Douglas Gregorb139cd52010-05-01 20:49:11 +00006835 // Construct the "from" expression, which is an implicit cast to the
6836 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00006837 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00006838 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6839 CK_UncheckedDerivedToBase,
6840 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006841
6842 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00006843 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006844
6845 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00006846 To = ImpCastExprToType(To.take(),
6847 Context.getCVRQualifiedType(BaseType,
6848 CopyAssignOperator->getTypeQualifiers()),
6849 CK_UncheckedDerivedToBase,
6850 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006851
6852 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00006853 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00006854 To.get(), From,
6855 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006856 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006857 Diag(CurrentLocation, diag::note_member_synthesized_at)
6858 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6859 CopyAssignOperator->setInvalidDecl();
6860 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006861 }
6862
6863 // Success! Record the copy.
6864 Statements.push_back(Copy.takeAs<Expr>());
6865 }
6866
6867 // \brief Reference to the __builtin_memcpy function.
6868 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006869 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006870 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006871
6872 // Assign non-static members.
6873 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6874 FieldEnd = ClassDecl->field_end();
6875 Field != FieldEnd; ++Field) {
6876 // Check for members of reference type; we can't copy those.
6877 if (Field->getType()->isReferenceType()) {
6878 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6879 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6880 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006881 Diag(CurrentLocation, diag::note_member_synthesized_at)
6882 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006883 Invalid = true;
6884 continue;
6885 }
6886
6887 // Check for members of const-qualified, non-class type.
6888 QualType BaseType = Context.getBaseElementType(Field->getType());
6889 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6890 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6891 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6892 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00006893 Diag(CurrentLocation, diag::note_member_synthesized_at)
6894 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006895 Invalid = true;
6896 continue;
6897 }
John McCall1b1a1db2011-06-17 00:18:42 +00006898
6899 // Suppress assigning zero-width bitfields.
6900 if (const Expr *Width = Field->getBitWidth())
6901 if (Width->EvaluateAsInt(Context) == 0)
6902 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00006903
6904 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00006905 if (FieldType->isIncompleteArrayType()) {
6906 assert(ClassDecl->hasFlexibleArrayMember() &&
6907 "Incomplete array type is not valid");
6908 continue;
6909 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006910
6911 // Build references to the field in the object we're copying from and to.
6912 CXXScopeSpec SS; // Intentionally empty
6913 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6914 LookupMemberName);
6915 MemberLookup.addDecl(*Field);
6916 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00006917 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00006918 Loc, /*IsArrow=*/false,
6919 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00006920 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00006921 Loc, /*IsArrow=*/true,
6922 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006923 assert(!From.isInvalid() && "Implicit field reference cannot fail");
6924 assert(!To.isInvalid() && "Implicit field reference cannot fail");
6925
6926 // If the field should be copied with __builtin_memcpy rather than via
6927 // explicit assignments, do so. This optimization only applies for arrays
6928 // of scalars and arrays of class type with trivial copy-assignment
6929 // operators.
John McCall31168b02011-06-15 23:02:42 +00006930 if (FieldType->isArrayType() &&
6931 BaseType.hasTrivialCopyAssignment(Context)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006932 // Compute the size of the memory buffer to be copied.
6933 QualType SizeType = Context.getSizeType();
6934 llvm::APInt Size(Context.getTypeSize(SizeType),
6935 Context.getTypeSizeInChars(BaseType).getQuantity());
6936 for (const ConstantArrayType *Array
6937 = Context.getAsConstantArrayType(FieldType);
6938 Array;
6939 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00006940 llvm::APInt ArraySize
6941 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00006942 Size *= ArraySize;
6943 }
6944
6945 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00006946 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6947 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006948
6949 bool NeedsCollectableMemCpy =
6950 (BaseType->isRecordType() &&
6951 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6952
6953 if (NeedsCollectableMemCpy) {
6954 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00006955 // Create a reference to the __builtin_objc_memmove_collectable function.
6956 LookupResult R(*this,
6957 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006958 Loc, LookupOrdinaryName);
6959 LookupName(R, TUScope, true);
6960
6961 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6962 if (!CollectableMemCpy) {
6963 // Something went horribly wrong earlier, and we will have
6964 // complained about it.
6965 Invalid = true;
6966 continue;
6967 }
6968
6969 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6970 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006971 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006972 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6973 }
6974 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00006975 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00006976 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00006977 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6978 LookupOrdinaryName);
6979 LookupName(R, TUScope, true);
6980
6981 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6982 if (!BuiltinMemCpy) {
6983 // Something went horribly wrong earlier, and we will have complained
6984 // about it.
6985 Invalid = true;
6986 continue;
6987 }
6988
6989 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6990 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006991 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00006992 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6993 }
6994
John McCall37ad5512010-08-23 06:44:23 +00006995 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00006996 CallArgs.push_back(To.takeAs<Expr>());
6997 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006998 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00006999 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007000 if (NeedsCollectableMemCpy)
7001 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007002 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007003 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007004 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007005 else
7006 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00007007 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007008 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007009 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00007010
Douglas Gregorb139cd52010-05-01 20:49:11 +00007011 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7012 Statements.push_back(Call.takeAs<Expr>());
7013 continue;
7014 }
7015
7016 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00007017 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00007018 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007019 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007020 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007021 Diag(CurrentLocation, diag::note_member_synthesized_at)
7022 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7023 CopyAssignOperator->setInvalidDecl();
7024 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007025 }
7026
7027 // Success! Record the copy.
7028 Statements.push_back(Copy.takeAs<Stmt>());
7029 }
7030
7031 if (!Invalid) {
7032 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00007033 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007034
John McCalldadc5752010-08-24 06:29:42 +00007035 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00007036 if (Return.isInvalid())
7037 Invalid = true;
7038 else {
7039 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00007040
7041 if (Trap.hasErrorOccurred()) {
7042 Diag(CurrentLocation, diag::note_member_synthesized_at)
7043 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7044 Invalid = true;
7045 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007046 }
7047 }
7048
7049 if (Invalid) {
7050 CopyAssignOperator->setInvalidDecl();
7051 return;
7052 }
7053
John McCalldadc5752010-08-24 06:29:42 +00007054 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00007055 /*isStmtExpr=*/false);
7056 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7057 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00007058
7059 if (ASTMutationListener *L = getASTMutationListener()) {
7060 L->CompletedImplicitDefinition(CopyAssignOperator);
7061 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007062}
7063
Alexis Hunt913820d2011-05-13 06:10:58 +00007064std::pair<Sema::ImplicitExceptionSpecification, bool>
7065Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00007066 // C++ [class.copy]p5:
7067 // The implicitly-declared copy constructor for a class X will
7068 // have the form
7069 //
7070 // X::X(const X&)
7071 //
7072 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00007073 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00007074 bool HasConstCopyConstructor = true;
7075
7076 // -- each direct or virtual base class B of X has a copy
7077 // constructor whose first parameter is of type const B& or
7078 // const volatile B&, and
7079 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7080 BaseEnd = ClassDecl->bases_end();
7081 HasConstCopyConstructor && Base != BaseEnd;
7082 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007083 // Virtual bases are handled below.
7084 if (Base->isVirtual())
7085 continue;
7086
Douglas Gregora6d69502010-07-02 23:41:54 +00007087 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00007088 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007089 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7090 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00007091 }
7092
7093 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7094 BaseEnd = ClassDecl->vbases_end();
7095 HasConstCopyConstructor && Base != BaseEnd;
7096 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007097 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00007098 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007099 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7100 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007101 }
7102
7103 // -- for all the nonstatic data members of X that are of a
7104 // class type M (or array thereof), each such class type
7105 // has a copy constructor whose first parameter is of type
7106 // const M& or const volatile M&.
7107 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7108 FieldEnd = ClassDecl->field_end();
7109 HasConstCopyConstructor && Field != FieldEnd;
7110 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00007111 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007112 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007113 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7114 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00007115 }
7116 }
Douglas Gregor54be3392010-07-01 17:57:27 +00007117 // Otherwise, the implicitly declared copy constructor will have
7118 // the form
7119 //
7120 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00007121
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007122 // C++ [except.spec]p14:
7123 // An implicitly declared special member function (Clause 12) shall have an
7124 // exception-specification. [...]
7125 ImplicitExceptionSpecification ExceptSpec(Context);
7126 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7127 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7128 BaseEnd = ClassDecl->bases_end();
7129 Base != BaseEnd;
7130 ++Base) {
7131 // Virtual bases are handled below.
7132 if (Base->isVirtual())
7133 continue;
7134
Douglas Gregora6d69502010-07-02 23:41:54 +00007135 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007136 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007137 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007138 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007139 ExceptSpec.CalledDecl(CopyConstructor);
7140 }
7141 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7142 BaseEnd = ClassDecl->vbases_end();
7143 Base != BaseEnd;
7144 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007145 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007146 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00007147 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007148 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007149 ExceptSpec.CalledDecl(CopyConstructor);
7150 }
7151 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7152 FieldEnd = ClassDecl->field_end();
7153 Field != FieldEnd;
7154 ++Field) {
7155 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00007156 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7157 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00007158 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00007159 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00007160 }
7161 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007162
Alexis Hunt913820d2011-05-13 06:10:58 +00007163 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7164}
7165
7166CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7167 CXXRecordDecl *ClassDecl) {
7168 // C++ [class.copy]p4:
7169 // If the class definition does not explicitly declare a copy
7170 // constructor, one is declared implicitly.
7171
7172 ImplicitExceptionSpecification Spec(Context);
7173 bool Const;
7174 llvm::tie(Spec, Const) =
7175 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7176
7177 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7178 QualType ArgType = ClassType;
7179 if (Const)
7180 ArgType = ArgType.withConst();
7181 ArgType = Context.getLValueReferenceType(ArgType);
7182
7183 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7184
Douglas Gregor54be3392010-07-01 17:57:27 +00007185 DeclarationName Name
7186 = Context.DeclarationNames.getCXXConstructorName(
7187 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007188 SourceLocation ClassLoc = ClassDecl->getLocation();
7189 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00007190
7191 // An implicitly-declared copy constructor is an inline public
7192 // member of its class.
Douglas Gregor54be3392010-07-01 17:57:27 +00007193 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00007194 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00007195 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00007196 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00007197 /*TInfo=*/0,
7198 /*isExplicit=*/false,
7199 /*isInline=*/true,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00007200 /*isImplicitlyDeclared=*/true);
Douglas Gregor54be3392010-07-01 17:57:27 +00007201 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00007202 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00007203 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7204
Douglas Gregora6d69502010-07-02 23:41:54 +00007205 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00007206 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7207
Douglas Gregor54be3392010-07-01 17:57:27 +00007208 // Add the parameter to the constructor.
7209 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007210 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00007211 /*IdentifierInfo=*/0,
7212 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007213 SC_None,
7214 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00007215 CopyConstructor->setParams(&FromParam, 1);
Alexis Hunt913820d2011-05-13 06:10:58 +00007216
Douglas Gregor0be31a22010-07-02 17:43:08 +00007217 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00007218 PushOnScopeChains(CopyConstructor, S, false);
7219 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007220
Alexis Huntd74c85f2011-06-22 01:05:13 +00007221 // C++0x [class.copy]p7:
7222 // ... If the class definition declares a move constructor or move
7223 // assignment operator, the implicitly declared constructor is defined as
7224 // deleted; ...
7225 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7226 ClassDecl->hasUserDeclaredMoveAssignment() ||
7227 ShouldDeleteCopyConstructor(CopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007228 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00007229
7230 return CopyConstructor;
7231}
7232
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007233void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00007234 CXXConstructorDecl *CopyConstructor) {
7235 assert((CopyConstructor->isDefaulted() &&
7236 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007237 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007238 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007239
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00007240 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007241 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007242
Douglas Gregora57478e2010-05-01 15:04:51 +00007243 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007244 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007245
Alexis Hunt1d792652011-01-08 20:30:50 +00007246 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007247 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00007248 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00007249 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00007250 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00007251 } else {
7252 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7253 CopyConstructor->getLocation(),
7254 MultiStmtArg(*this, 0, 0),
7255 /*isStmtExpr=*/false)
7256 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00007257 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00007258
7259 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00007260
7261 if (ASTMutationListener *L = getASTMutationListener()) {
7262 L->CompletedImplicitDefinition(CopyConstructor);
7263 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00007264}
7265
John McCalldadc5752010-08-24 06:29:42 +00007266ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007267Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00007268 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007269 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007270 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007271 unsigned ConstructKind,
7272 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00007273 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00007274
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007275 // C++0x [class.copy]p34:
7276 // When certain criteria are met, an implementation is allowed to
7277 // omit the copy/move construction of a class object, even if the
7278 // copy/move constructor and/or destructor for the object have
7279 // side effects. [...]
7280 // - when a temporary class object that has not been bound to a
7281 // reference (12.2) would be copied/moved to a class object
7282 // with the same cv-unqualified type, the copy/move operation
7283 // can be omitted by constructing the temporary object
7284 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00007285 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00007286 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00007287 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00007288 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00007289 }
Mike Stump11289f42009-09-09 15:08:12 +00007290
7291 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007292 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007293 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00007294}
7295
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007296/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7297/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00007298ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00007299Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7300 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007301 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007302 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007303 unsigned ConstructKind,
7304 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007305 unsigned NumExprs = ExprArgs.size();
7306 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00007307
Nick Lewyckyd4693212011-03-25 01:44:32 +00007308 for (specific_attr_iterator<NonNullAttr>
7309 i = Constructor->specific_attr_begin<NonNullAttr>(),
7310 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7311 const NonNullAttr *NonNull = *i;
7312 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7313 }
7314
Douglas Gregor27381f32009-11-23 12:27:39 +00007315 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00007316 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00007317 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00007318 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00007319 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7320 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007321}
7322
Mike Stump11289f42009-09-09 15:08:12 +00007323bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00007324 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00007325 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00007326 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00007327 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00007328 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00007329 move(Exprs), false, CXXConstructExpr::CK_Complete,
7330 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007331 if (TempResult.isInvalid())
7332 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007333
Anders Carlsson6eb55572009-08-25 05:12:04 +00007334 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00007335 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00007336 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00007337 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00007338 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00007339
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00007340 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00007341}
7342
John McCall03c48482010-02-02 09:10:11 +00007343void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00007344 if (VD->isInvalidDecl()) return;
7345
John McCall03c48482010-02-02 09:10:11 +00007346 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00007347 if (ClassDecl->isInvalidDecl()) return;
7348 if (ClassDecl->hasTrivialDestructor()) return;
7349 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00007350
Chandler Carruth86d17d32011-03-27 21:26:48 +00007351 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7352 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7353 CheckDestructorAccess(VD->getLocation(), Destructor,
7354 PDiag(diag::err_access_dtor_var)
7355 << VD->getDeclName()
7356 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00007357
Chandler Carruth86d17d32011-03-27 21:26:48 +00007358 if (!VD->hasGlobalStorage()) return;
7359
7360 // Emit warning for non-trivial dtor in global scope (a real global,
7361 // class-static, function-static).
7362 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7363
7364 // TODO: this should be re-enabled for static locals by !CXAAtExit
7365 if (!VD->isStaticLocal())
7366 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007367}
7368
Mike Stump11289f42009-09-09 15:08:12 +00007369/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007370/// ActOnDeclarator, when a C++ direct initializer is present.
7371/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00007372void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007373 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00007374 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00007375 SourceLocation RParenLoc,
7376 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00007377 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007378
7379 // If there is no declaration, there was an error parsing it. Just ignore
7380 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00007381 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007382 return;
Mike Stump11289f42009-09-09 15:08:12 +00007383
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007384 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7385 if (!VDecl) {
7386 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7387 RealDecl->setInvalidDecl();
7388 return;
7389 }
7390
Richard Smith30482bc2011-02-20 03:19:35 +00007391 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7392 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00007393 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7394 if (Exprs.size() > 1) {
7395 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7396 diag::err_auto_var_init_multiple_expressions)
7397 << VDecl->getDeclName() << VDecl->getType()
7398 << VDecl->getSourceRange();
7399 RealDecl->setInvalidDecl();
7400 return;
7401 }
7402
7403 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00007404 TypeSourceInfo *DeducedType = 0;
7405 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00007406 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7407 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7408 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00007409 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00007410 RealDecl->setInvalidDecl();
7411 return;
7412 }
Richard Smith9647d3c2011-03-17 16:11:59 +00007413 VDecl->setTypeSourceInfo(DeducedType);
7414 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00007415
John McCall31168b02011-06-15 23:02:42 +00007416 // In ARC, infer lifetime.
7417 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7418 VDecl->setInvalidDecl();
7419
Richard Smith30482bc2011-02-20 03:19:35 +00007420 // If this is a redeclaration, check that the type we just deduced matches
7421 // the previously declared type.
7422 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7423 MergeVarDeclTypes(VDecl, Old);
7424 }
7425
Douglas Gregor402250f2009-08-26 21:14:46 +00007426 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007427 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007428 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7429 //
7430 // Clients that want to distinguish between the two forms, can check for
7431 // direct initializer using VarDecl::hasCXXDirectInitializer().
7432 // A major benefit is that clients that don't particularly care about which
7433 // exactly form was it (like the CodeGen) can handle both cases without
7434 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007435
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007436 // C++ 8.5p11:
7437 // The form of initialization (using parentheses or '=') is generally
7438 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007439 // class type.
7440
Douglas Gregor50dc2192010-02-11 22:55:30 +00007441 if (!VDecl->getType()->isDependentType() &&
7442 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00007443 diag::err_typecheck_decl_incomplete_type)) {
7444 VDecl->setInvalidDecl();
7445 return;
7446 }
7447
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007448 // The variable can not have an abstract class type.
7449 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7450 diag::err_abstract_type_in_decl,
7451 AbstractVariableType))
7452 VDecl->setInvalidDecl();
7453
Sebastian Redl5ca79842010-02-01 20:16:42 +00007454 const VarDecl *Def;
7455 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007456 Diag(VDecl->getLocation(), diag::err_redefinition)
7457 << VDecl->getDeclName();
7458 Diag(Def->getLocation(), diag::note_previous_definition);
7459 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00007460 return;
7461 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00007462
Douglas Gregorf0f83692010-08-24 05:27:49 +00007463 // C++ [class.static.data]p4
7464 // If a static data member is of const integral or const
7465 // enumeration type, its declaration in the class definition can
7466 // specify a constant-initializer which shall be an integral
7467 // constant expression (5.19). In that case, the member can appear
7468 // in integral constant expressions. The member shall still be
7469 // defined in a namespace scope if it is used in the program and the
7470 // namespace scope definition shall not contain an initializer.
7471 //
7472 // We already performed a redefinition check above, but for static
7473 // data members we also need to check whether there was an in-class
7474 // declaration with an initializer.
7475 const VarDecl* PrevInit = 0;
7476 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7477 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7478 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7479 return;
7480 }
7481
Douglas Gregor71f39c92010-12-16 01:31:22 +00007482 bool IsDependent = false;
7483 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7484 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7485 VDecl->setInvalidDecl();
7486 return;
7487 }
7488
7489 if (Exprs.get()[I]->isTypeDependent())
7490 IsDependent = true;
7491 }
7492
Douglas Gregor50dc2192010-02-11 22:55:30 +00007493 // If either the declaration has a dependent type or if any of the
7494 // expressions is type-dependent, we represent the initialization
7495 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00007496 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00007497 // Let clients know that initialization was done with a direct initializer.
7498 VDecl->setCXXDirectInitializer(true);
7499
7500 // Store the initialization expressions as a ParenListExpr.
7501 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00007502 VDecl->setInit(new (Context) ParenListExpr(
7503 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7504 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00007505 return;
7506 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007507
7508 // Capture the variable that is being initialized and the style of
7509 // initialization.
7510 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7511
7512 // FIXME: Poor source location information.
7513 InitializationKind Kind
7514 = InitializationKind::CreateDirect(VDecl->getLocation(),
7515 LParenLoc, RParenLoc);
7516
7517 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00007518 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00007519 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007520 if (Result.isInvalid()) {
7521 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007522 return;
7523 }
John McCallacf0ee52010-10-08 02:01:28 +00007524
7525 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00007526
Douglas Gregora40433a2010-12-07 00:41:46 +00007527 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00007528 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007529 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00007530
John McCall8b7fd8f12011-01-19 11:48:09 +00007531 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007532}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00007533
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007534/// \brief Given a constructor and the set of arguments provided for the
7535/// constructor, convert the arguments and add any required default arguments
7536/// to form a proper call to this constructor.
7537///
7538/// \returns true if an error occurred, false otherwise.
7539bool
7540Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7541 MultiExprArg ArgsPtr,
7542 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00007543 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007544 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7545 unsigned NumArgs = ArgsPtr.size();
7546 Expr **Args = (Expr **)ArgsPtr.get();
7547
7548 const FunctionProtoType *Proto
7549 = Constructor->getType()->getAs<FunctionProtoType>();
7550 assert(Proto && "Constructor without a prototype?");
7551 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007552
7553 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007554 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007555 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007556 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00007557 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00007558
7559 VariadicCallType CallType =
7560 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7561 llvm::SmallVector<Expr *, 8> AllArgs;
7562 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7563 Proto, 0, Args, NumArgs, AllArgs,
7564 CallType);
7565 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7566 ConvertedArgs.push_back(AllArgs[i]);
7567 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00007568}
7569
Anders Carlssone363c8e2009-12-12 00:32:00 +00007570static inline bool
7571CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7572 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007573 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00007574 if (isa<NamespaceDecl>(DC)) {
7575 return SemaRef.Diag(FnDecl->getLocation(),
7576 diag::err_operator_new_delete_declared_in_namespace)
7577 << FnDecl->getDeclName();
7578 }
7579
7580 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00007581 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007582 return SemaRef.Diag(FnDecl->getLocation(),
7583 diag::err_operator_new_delete_declared_static)
7584 << FnDecl->getDeclName();
7585 }
7586
Anders Carlsson60659a82009-12-12 02:43:16 +00007587 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00007588}
7589
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007590static inline bool
7591CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7592 CanQualType ExpectedResultType,
7593 CanQualType ExpectedFirstParamType,
7594 unsigned DependentParamTypeDiag,
7595 unsigned InvalidParamTypeDiag) {
7596 QualType ResultType =
7597 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7598
7599 // Check that the result type is not dependent.
7600 if (ResultType->isDependentType())
7601 return SemaRef.Diag(FnDecl->getLocation(),
7602 diag::err_operator_new_delete_dependent_result_type)
7603 << FnDecl->getDeclName() << ExpectedResultType;
7604
7605 // Check that the result type is what we expect.
7606 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7607 return SemaRef.Diag(FnDecl->getLocation(),
7608 diag::err_operator_new_delete_invalid_result_type)
7609 << FnDecl->getDeclName() << ExpectedResultType;
7610
7611 // A function template must have at least 2 parameters.
7612 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7613 return SemaRef.Diag(FnDecl->getLocation(),
7614 diag::err_operator_new_delete_template_too_few_parameters)
7615 << FnDecl->getDeclName();
7616
7617 // The function decl must have at least 1 parameter.
7618 if (FnDecl->getNumParams() == 0)
7619 return SemaRef.Diag(FnDecl->getLocation(),
7620 diag::err_operator_new_delete_too_few_parameters)
7621 << FnDecl->getDeclName();
7622
7623 // Check the the first parameter type is not dependent.
7624 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7625 if (FirstParamType->isDependentType())
7626 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7627 << FnDecl->getDeclName() << ExpectedFirstParamType;
7628
7629 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00007630 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007631 ExpectedFirstParamType)
7632 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7633 << FnDecl->getDeclName() << ExpectedFirstParamType;
7634
7635 return false;
7636}
7637
Anders Carlsson12308f42009-12-11 23:23:22 +00007638static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007639CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00007640 // C++ [basic.stc.dynamic.allocation]p1:
7641 // A program is ill-formed if an allocation function is declared in a
7642 // namespace scope other than global scope or declared static in global
7643 // scope.
7644 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7645 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007646
7647 CanQualType SizeTy =
7648 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7649
7650 // C++ [basic.stc.dynamic.allocation]p1:
7651 // The return type shall be void*. The first parameter shall have type
7652 // std::size_t.
7653 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7654 SizeTy,
7655 diag::err_operator_new_dependent_param_type,
7656 diag::err_operator_new_param_type))
7657 return true;
7658
7659 // C++ [basic.stc.dynamic.allocation]p1:
7660 // The first parameter shall not have an associated default argument.
7661 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00007662 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007663 diag::err_operator_new_default_arg)
7664 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7665
7666 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00007667}
7668
7669static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00007670CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7671 // C++ [basic.stc.dynamic.deallocation]p1:
7672 // A program is ill-formed if deallocation functions are declared in a
7673 // namespace scope other than global scope or declared static in global
7674 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00007675 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7676 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007677
7678 // C++ [basic.stc.dynamic.deallocation]p2:
7679 // Each deallocation function shall return void and its first parameter
7680 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007681 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7682 SemaRef.Context.VoidPtrTy,
7683 diag::err_operator_delete_dependent_param_type,
7684 diag::err_operator_delete_param_type))
7685 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00007686
Anders Carlsson12308f42009-12-11 23:23:22 +00007687 return false;
7688}
7689
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007690/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7691/// of this overloaded operator is well-formed. If so, returns false;
7692/// otherwise, emits appropriate diagnostics and returns true.
7693bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00007694 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007695 "Expected an overloaded operator declaration");
7696
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007697 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7698
Mike Stump11289f42009-09-09 15:08:12 +00007699 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007700 // The allocation and deallocation functions, operator new,
7701 // operator new[], operator delete and operator delete[], are
7702 // described completely in 3.7.3. The attributes and restrictions
7703 // found in the rest of this subclause do not apply to them unless
7704 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00007705 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00007706 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00007707
Anders Carlsson22f443f2009-12-12 00:26:23 +00007708 if (Op == OO_New || Op == OO_Array_New)
7709 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007710
7711 // C++ [over.oper]p6:
7712 // An operator function shall either be a non-static member
7713 // function or be a non-member function and have at least one
7714 // parameter whose type is a class, a reference to a class, an
7715 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00007716 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7717 if (MethodDecl->isStatic())
7718 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007719 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007720 } else {
7721 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00007722 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7723 ParamEnd = FnDecl->param_end();
7724 Param != ParamEnd; ++Param) {
7725 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00007726 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7727 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007728 ClassOrEnumParam = true;
7729 break;
7730 }
7731 }
7732
Douglas Gregord69246b2008-11-17 16:14:12 +00007733 if (!ClassOrEnumParam)
7734 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007735 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007736 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007737 }
7738
7739 // C++ [over.oper]p8:
7740 // An operator function cannot have default arguments (8.3.6),
7741 // except where explicitly stated below.
7742 //
Mike Stump11289f42009-09-09 15:08:12 +00007743 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007744 // (C++ [over.call]p1).
7745 if (Op != OO_Call) {
7746 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7747 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007748 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00007749 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00007750 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00007751 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007752 }
7753 }
7754
Douglas Gregor6cf08062008-11-10 13:38:07 +00007755 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7756 { false, false, false }
7757#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7758 , { Unary, Binary, MemberOnly }
7759#include "clang/Basic/OperatorKinds.def"
7760 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007761
Douglas Gregor6cf08062008-11-10 13:38:07 +00007762 bool CanBeUnaryOperator = OperatorUses[Op][0];
7763 bool CanBeBinaryOperator = OperatorUses[Op][1];
7764 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007765
7766 // C++ [over.oper]p8:
7767 // [...] Operator functions cannot have more or fewer parameters
7768 // than the number required for the corresponding operator, as
7769 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00007770 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00007771 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007772 if (Op != OO_Call &&
7773 ((NumParams == 1 && !CanBeUnaryOperator) ||
7774 (NumParams == 2 && !CanBeBinaryOperator) ||
7775 (NumParams < 1) || (NumParams > 2))) {
7776 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007777 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00007778 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007779 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00007780 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007781 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007782 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00007783 assert(CanBeBinaryOperator &&
7784 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007785 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00007786 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007787
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00007788 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007789 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007790 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007791
Douglas Gregord69246b2008-11-17 16:14:12 +00007792 // Overloaded operators other than operator() cannot be variadic.
7793 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00007794 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007795 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007796 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007797 }
7798
7799 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00007800 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7801 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00007802 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007803 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007804 }
7805
7806 // C++ [over.inc]p1:
7807 // The user-defined function called operator++ implements the
7808 // prefix and postfix ++ operator. If this function is a member
7809 // function with no parameters, or a non-member function with one
7810 // parameter of class or enumeration type, it defines the prefix
7811 // increment operator ++ for objects of that type. If the function
7812 // is a member function with one parameter (which shall be of type
7813 // int) or a non-member function with two parameters (the second
7814 // of which shall be of type int), it defines the postfix
7815 // increment operator ++ for objects of that type.
7816 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7817 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7818 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00007819 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007820 ParamIsInt = BT->getKind() == BuiltinType::Int;
7821
Chris Lattner2b786902008-11-21 07:50:02 +00007822 if (!ParamIsInt)
7823 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00007824 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007825 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007826 }
7827
Douglas Gregord69246b2008-11-17 16:14:12 +00007828 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00007829}
Chris Lattner3b024a32008-12-17 07:09:26 +00007830
Alexis Huntc88db062010-01-13 09:01:02 +00007831/// CheckLiteralOperatorDeclaration - Check whether the declaration
7832/// of this literal operator function is well-formed. If so, returns
7833/// false; otherwise, emits appropriate diagnostics and returns true.
7834bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7835 DeclContext *DC = FnDecl->getDeclContext();
7836 Decl::Kind Kind = DC->getDeclKind();
7837 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7838 Kind != Decl::LinkageSpec) {
7839 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7840 << FnDecl->getDeclName();
7841 return true;
7842 }
7843
7844 bool Valid = false;
7845
Alexis Hunt7dd26172010-04-07 23:11:06 +00007846 // template <char...> type operator "" name() is the only valid template
7847 // signature, and the only valid signature with no parameters.
7848 if (FnDecl->param_size() == 0) {
7849 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7850 // Must have only one template parameter
7851 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7852 if (Params->size() == 1) {
7853 NonTypeTemplateParmDecl *PmDecl =
7854 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00007855
Alexis Hunt7dd26172010-04-07 23:11:06 +00007856 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00007857 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7858 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7859 Valid = true;
7860 }
7861 }
7862 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00007863 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00007864 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7865
Alexis Huntc88db062010-01-13 09:01:02 +00007866 QualType T = (*Param)->getType();
7867
Alexis Hunt079a6f72010-04-07 22:57:35 +00007868 // unsigned long long int, long double, and any character type are allowed
7869 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00007870 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7871 Context.hasSameType(T, Context.LongDoubleTy) ||
7872 Context.hasSameType(T, Context.CharTy) ||
7873 Context.hasSameType(T, Context.WCharTy) ||
7874 Context.hasSameType(T, Context.Char16Ty) ||
7875 Context.hasSameType(T, Context.Char32Ty)) {
7876 if (++Param == FnDecl->param_end())
7877 Valid = true;
7878 goto FinishedParams;
7879 }
7880
Alexis Hunt079a6f72010-04-07 22:57:35 +00007881 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00007882 const PointerType *PT = T->getAs<PointerType>();
7883 if (!PT)
7884 goto FinishedParams;
7885 T = PT->getPointeeType();
7886 if (!T.isConstQualified())
7887 goto FinishedParams;
7888 T = T.getUnqualifiedType();
7889
7890 // Move on to the second parameter;
7891 ++Param;
7892
7893 // If there is no second parameter, the first must be a const char *
7894 if (Param == FnDecl->param_end()) {
7895 if (Context.hasSameType(T, Context.CharTy))
7896 Valid = true;
7897 goto FinishedParams;
7898 }
7899
7900 // const char *, const wchar_t*, const char16_t*, and const char32_t*
7901 // are allowed as the first parameter to a two-parameter function
7902 if (!(Context.hasSameType(T, Context.CharTy) ||
7903 Context.hasSameType(T, Context.WCharTy) ||
7904 Context.hasSameType(T, Context.Char16Ty) ||
7905 Context.hasSameType(T, Context.Char32Ty)))
7906 goto FinishedParams;
7907
7908 // The second and final parameter must be an std::size_t
7909 T = (*Param)->getType().getUnqualifiedType();
7910 if (Context.hasSameType(T, Context.getSizeType()) &&
7911 ++Param == FnDecl->param_end())
7912 Valid = true;
7913 }
7914
7915 // FIXME: This diagnostic is absolutely terrible.
7916FinishedParams:
7917 if (!Valid) {
7918 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7919 << FnDecl->getDeclName();
7920 return true;
7921 }
7922
7923 return false;
7924}
7925
Douglas Gregor07665a62009-01-05 19:45:36 +00007926/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7927/// linkage specification, including the language and (if present)
7928/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7929/// the location of the language string literal, which is provided
7930/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7931/// the '{' brace. Otherwise, this linkage specification does not
7932/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00007933Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7934 SourceLocation LangLoc,
7935 llvm::StringRef Lang,
7936 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00007937 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007938 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007939 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00007940 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00007941 Language = LinkageSpecDecl::lang_cxx;
7942 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00007943 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00007944 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00007945 }
Mike Stump11289f42009-09-09 15:08:12 +00007946
Chris Lattner438e5012008-12-17 07:13:27 +00007947 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00007948
Douglas Gregor07665a62009-01-05 19:45:36 +00007949 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00007950 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007951 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00007952 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00007953 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00007954}
7955
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00007956/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00007957/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7958/// valid, it's the position of the closing '}' brace in a linkage
7959/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00007960Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007961 Decl *LinkageSpec,
7962 SourceLocation RBraceLoc) {
7963 if (LinkageSpec) {
7964 if (RBraceLoc.isValid()) {
7965 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7966 LSDecl->setRBraceLoc(RBraceLoc);
7967 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007968 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00007969 }
Douglas Gregor07665a62009-01-05 19:45:36 +00007970 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00007971}
7972
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007973/// \brief Perform semantic analysis for the variable declaration that
7974/// occurs within a C++ catch clause, returning the newly-created
7975/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007976VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00007977 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007978 SourceLocation StartLoc,
7979 SourceLocation Loc,
7980 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007981 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007982 QualType ExDeclType = TInfo->getType();
7983
Sebastian Redl54c04d42008-12-22 19:15:10 +00007984 // Arrays and functions decay.
7985 if (ExDeclType->isArrayType())
7986 ExDeclType = Context.getArrayDecayedType(ExDeclType);
7987 else if (ExDeclType->isFunctionType())
7988 ExDeclType = Context.getPointerType(ExDeclType);
7989
7990 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7991 // The exception-declaration shall not denote a pointer or reference to an
7992 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00007993 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00007994 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00007995 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00007996 Invalid = true;
7997 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00007998
Douglas Gregor104ee002010-03-08 01:47:36 +00007999 // GCC allows catching pointers and references to incomplete types
8000 // as an extension; so do we, but we warn by default.
8001
Sebastian Redl54c04d42008-12-22 19:15:10 +00008002 QualType BaseType = ExDeclType;
8003 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00008004 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00008005 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008006 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008007 BaseType = Ptr->getPointeeType();
8008 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00008009 DK = diag::ext_catch_incomplete_ptr;
8010 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00008011 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00008012 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008013 BaseType = Ref->getPointeeType();
8014 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00008015 DK = diag::ext_catch_incomplete_ref;
8016 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008017 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00008018 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00008019 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8020 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00008021 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008022
Mike Stump11289f42009-09-09 15:08:12 +00008023 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008024 RequireNonAbstractType(Loc, ExDeclType,
8025 diag::err_abstract_type_in_decl,
8026 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00008027 Invalid = true;
8028
John McCall2ca705e2010-07-24 00:37:23 +00008029 // Only the non-fragile NeXT runtime currently supports C++ catches
8030 // of ObjC types, and no runtime supports catching ObjC types by value.
8031 if (!Invalid && getLangOptions().ObjC1) {
8032 QualType T = ExDeclType;
8033 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8034 T = RT->getPointeeType();
8035
8036 if (T->isObjCObjectType()) {
8037 Diag(Loc, diag::err_objc_object_catch);
8038 Invalid = true;
8039 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00008040 if (!getLangOptions().ObjCNonFragileABI)
8041 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00008042 }
8043 }
8044
Abramo Bagnaradff19302011-03-08 08:55:46 +00008045 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8046 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00008047 ExDecl->setExceptionVariable(true);
8048
Douglas Gregor6de584c2010-03-05 23:38:39 +00008049 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00008050 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00008051 // C++ [except.handle]p16:
8052 // The object declared in an exception-declaration or, if the
8053 // exception-declaration does not specify a name, a temporary (12.2) is
8054 // copy-initialized (8.5) from the exception object. [...]
8055 // The object is destroyed when the handler exits, after the destruction
8056 // of any automatic objects initialized within the handler.
8057 //
8058 // We just pretend to initialize the object with itself, then make sure
8059 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00008060 QualType initType = ExDeclType;
8061
8062 InitializedEntity entity =
8063 InitializedEntity::InitializeVariable(ExDecl);
8064 InitializationKind initKind =
8065 InitializationKind::CreateCopy(Loc, SourceLocation());
8066
8067 Expr *opaqueValue =
8068 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8069 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8070 ExprResult result = sequence.Perform(*this, entity, initKind,
8071 MultiExprArg(&opaqueValue, 1));
8072 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00008073 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00008074 else {
8075 // If the constructor used was non-trivial, set this as the
8076 // "initializer".
8077 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8078 if (!construct->getConstructor()->isTrivial()) {
8079 Expr *init = MaybeCreateExprWithCleanups(construct);
8080 ExDecl->setInit(init);
8081 }
8082
8083 // And make sure it's destructable.
8084 FinalizeVarWithDestructor(ExDecl, recordType);
8085 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00008086 }
8087 }
8088
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008089 if (Invalid)
8090 ExDecl->setInvalidDecl();
8091
8092 return ExDecl;
8093}
8094
8095/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8096/// handler.
John McCall48871652010-08-21 09:40:31 +00008097Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00008098 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00008099 bool Invalid = D.isInvalidType();
8100
8101 // Check for unexpanded parameter packs.
8102 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8103 UPPC_ExceptionType)) {
8104 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8105 D.getIdentifierLoc());
8106 Invalid = true;
8107 }
8108
Sebastian Redl54c04d42008-12-22 19:15:10 +00008109 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008110 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00008111 LookupOrdinaryName,
8112 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008113 // The scope should be freshly made just for us. There is just no way
8114 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00008115 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00008116 if (PrevDecl->isTemplateParameter()) {
8117 // Maybe we will complain about the shadowed template parameter.
8118 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008119 }
8120 }
8121
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008122 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00008123 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8124 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008125 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008126 }
8127
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00008128 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008129 D.getSourceRange().getBegin(),
8130 D.getIdentifierLoc(),
8131 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008132 if (Invalid)
8133 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00008134
Sebastian Redl54c04d42008-12-22 19:15:10 +00008135 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00008136 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00008137 PushOnScopeChains(ExDecl, S);
8138 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008139 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00008140
Douglas Gregor758a8692009-06-17 21:51:59 +00008141 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00008142 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00008143}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008144
Abramo Bagnaraea947882011-03-08 16:41:52 +00008145Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00008146 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00008147 Expr *AssertMessageExpr_,
8148 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00008149 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008150
Anders Carlsson54b26982009-03-14 00:33:21 +00008151 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8152 llvm::APSInt Value(32);
8153 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008154 Diag(StaticAssertLoc,
8155 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00008156 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008157 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00008158 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008159
Anders Carlsson54b26982009-03-14 00:33:21 +00008160 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00008161 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00008162 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00008163 }
8164 }
Mike Stump11289f42009-09-09 15:08:12 +00008165
Douglas Gregoref68fee2010-12-15 23:55:21 +00008166 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8167 return 0;
8168
Abramo Bagnaraea947882011-03-08 16:41:52 +00008169 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8170 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00008171
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008172 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00008173 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00008174}
Sebastian Redlf769df52009-03-24 22:27:57 +00008175
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008176/// \brief Perform semantic analysis of the given friend type declaration.
8177///
8178/// \returns A friend declaration that.
8179FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8180 TypeSourceInfo *TSInfo) {
8181 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8182
8183 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008184 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008185
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008186 if (!getLangOptions().CPlusPlus0x) {
8187 // C++03 [class.friend]p2:
8188 // An elaborated-type-specifier shall be used in a friend declaration
8189 // for a class.*
8190 //
8191 // * The class-key of the elaborated-type-specifier is required.
8192 if (!ActiveTemplateInstantiations.empty()) {
8193 // Do not complain about the form of friend template types during
8194 // template instantiation; we will already have complained when the
8195 // template was declared.
8196 } else if (!T->isElaboratedTypeSpecifier()) {
8197 // If we evaluated the type to a record type, suggest putting
8198 // a tag in front.
8199 if (const RecordType *RT = T->getAs<RecordType>()) {
8200 RecordDecl *RD = RT->getDecl();
8201
8202 std::string InsertionText = std::string(" ") + RD->getKindName();
8203
8204 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8205 << (unsigned) RD->getTagKind()
8206 << T
8207 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8208 InsertionText);
8209 } else {
8210 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8211 << T
8212 << SourceRange(FriendLoc, TypeRange.getEnd());
8213 }
8214 } else if (T->getAs<EnumType>()) {
8215 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008216 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008217 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008218 }
8219 }
8220
Douglas Gregor3b4abb62010-04-07 17:57:12 +00008221 // C++0x [class.friend]p3:
8222 // If the type specifier in a friend declaration designates a (possibly
8223 // cv-qualified) class type, that class is declared as a friend; otherwise,
8224 // the friend declaration is ignored.
8225
8226 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8227 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008228
8229 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8230}
8231
John McCallace48cd2010-10-19 01:40:49 +00008232/// Handle a friend tag declaration where the scope specifier was
8233/// templated.
8234Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8235 unsigned TagSpec, SourceLocation TagLoc,
8236 CXXScopeSpec &SS,
8237 IdentifierInfo *Name, SourceLocation NameLoc,
8238 AttributeList *Attr,
8239 MultiTemplateParamsArg TempParamLists) {
8240 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8241
8242 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00008243 bool Invalid = false;
8244
8245 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00008246 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +00008247 TempParamLists.get(),
8248 TempParamLists.size(),
8249 /*friend*/ true,
8250 isExplicitSpecialization,
8251 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00008252 if (TemplateParams->size() > 0) {
8253 // This is a declaration of a class template.
8254 if (Invalid)
8255 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008256
John McCallace48cd2010-10-19 01:40:49 +00008257 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8258 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008259 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00008260 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00008261 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00008262 } else {
8263 // The "template<>" header is extraneous.
8264 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8265 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8266 isExplicitSpecialization = true;
8267 }
8268 }
8269
8270 if (Invalid) return 0;
8271
8272 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8273
8274 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00008275 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00008276 if (TempParamLists.get()[I]->size()) {
8277 isAllExplicitSpecializations = false;
8278 break;
8279 }
8280 }
8281
8282 // FIXME: don't ignore attributes.
8283
8284 // If it's explicit specializations all the way down, just forget
8285 // about the template header and build an appropriate non-templated
8286 // friend. TODO: for source fidelity, remember the headers.
8287 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008288 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00008289 ElaboratedTypeKeyword Keyword
8290 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008291 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00008292 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00008293 if (T.isNull())
8294 return 0;
8295
8296 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8297 if (isa<DependentNameType>(T)) {
8298 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8299 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008300 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008301 TL.setNameLoc(NameLoc);
8302 } else {
8303 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8304 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00008305 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00008306 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8307 }
8308
8309 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8310 TSI, FriendLoc);
8311 Friend->setAccess(AS_public);
8312 CurContext->addDecl(Friend);
8313 return Friend;
8314 }
8315
8316 // Handle the case of a templated-scope friend class. e.g.
8317 // template <class T> class A<T>::B;
8318 // FIXME: we don't support these right now.
8319 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8320 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8321 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8322 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8323 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00008324 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00008325 TL.setNameLoc(NameLoc);
8326
8327 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8328 TSI, FriendLoc);
8329 Friend->setAccess(AS_public);
8330 Friend->setUnsupportedFriend(true);
8331 CurContext->addDecl(Friend);
8332 return Friend;
8333}
8334
8335
John McCall11083da2009-09-16 22:47:08 +00008336/// Handle a friend type declaration. This works in tandem with
8337/// ActOnTag.
8338///
8339/// Notes on friend class templates:
8340///
8341/// We generally treat friend class declarations as if they were
8342/// declaring a class. So, for example, the elaborated type specifier
8343/// in a friend declaration is required to obey the restrictions of a
8344/// class-head (i.e. no typedefs in the scope chain), template
8345/// parameters are required to match up with simple template-ids, &c.
8346/// However, unlike when declaring a template specialization, it's
8347/// okay to refer to a template specialization without an empty
8348/// template parameter declaration, e.g.
8349/// friend class A<T>::B<unsigned>;
8350/// We permit this as a special case; if there are any template
8351/// parameters present at all, require proper matching, i.e.
8352/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00008353Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00008354 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008355 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00008356
8357 assert(DS.isFriendSpecified());
8358 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8359
John McCall11083da2009-09-16 22:47:08 +00008360 // Try to convert the decl specifier to a type. This works for
8361 // friend templates because ActOnTag never produces a ClassTemplateDecl
8362 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00008363 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00008364 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8365 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00008366 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00008367 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008368
Douglas Gregor6c110f32010-12-16 01:14:37 +00008369 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8370 return 0;
8371
John McCall11083da2009-09-16 22:47:08 +00008372 // This is definitely an error in C++98. It's probably meant to
8373 // be forbidden in C++0x, too, but the specification is just
8374 // poorly written.
8375 //
8376 // The problem is with declarations like the following:
8377 // template <T> friend A<T>::foo;
8378 // where deciding whether a class C is a friend or not now hinges
8379 // on whether there exists an instantiation of A that causes
8380 // 'foo' to equal C. There are restrictions on class-heads
8381 // (which we declare (by fiat) elaborated friend declarations to
8382 // be) that makes this tractable.
8383 //
8384 // FIXME: handle "template <> friend class A<T>;", which
8385 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00008386 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00008387 Diag(Loc, diag::err_tagless_friend_type_template)
8388 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00008389 return 0;
John McCall11083da2009-09-16 22:47:08 +00008390 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008391
John McCallaa74a0c2009-08-28 07:59:38 +00008392 // C++98 [class.friend]p1: A friend of a class is a function
8393 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00008394 // This is fixed in DR77, which just barely didn't make the C++03
8395 // deadline. It's also a very silly restriction that seriously
8396 // affects inner classes and which nobody else seems to implement;
8397 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00008398 //
8399 // But note that we could warn about it: it's always useless to
8400 // friend one of your own members (it's not, however, worthless to
8401 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00008402
John McCall11083da2009-09-16 22:47:08 +00008403 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008404 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00008405 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008406 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00008407 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00008408 TSI,
John McCall11083da2009-09-16 22:47:08 +00008409 DS.getFriendSpecLoc());
8410 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008411 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8412
8413 if (!D)
John McCall48871652010-08-21 09:40:31 +00008414 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00008415
John McCall11083da2009-09-16 22:47:08 +00008416 D->setAccess(AS_public);
8417 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00008418
John McCall48871652010-08-21 09:40:31 +00008419 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00008420}
8421
John McCallde3fd222010-10-12 23:13:28 +00008422Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8423 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00008424 const DeclSpec &DS = D.getDeclSpec();
8425
8426 assert(DS.isFriendSpecified());
8427 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8428
8429 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00008430 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8431 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00008432
8433 // C++ [class.friend]p1
8434 // A friend of a class is a function or class....
8435 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00008436 // It *doesn't* see through dependent types, which is correct
8437 // according to [temp.arg.type]p3:
8438 // If a declaration acquires a function type through a
8439 // type dependent on a template-parameter and this causes
8440 // a declaration that does not use the syntactic form of a
8441 // function declarator to have a function type, the program
8442 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00008443 if (!T->isFunctionType()) {
8444 Diag(Loc, diag::err_unexpected_friend);
8445
8446 // It might be worthwhile to try to recover by creating an
8447 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00008448 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008449 }
8450
8451 // C++ [namespace.memdef]p3
8452 // - If a friend declaration in a non-local class first declares a
8453 // class or function, the friend class or function is a member
8454 // of the innermost enclosing namespace.
8455 // - The name of the friend is not found by simple name lookup
8456 // until a matching declaration is provided in that namespace
8457 // scope (either before or after the class declaration granting
8458 // friendship).
8459 // - If a friend function is called, its name may be found by the
8460 // name lookup that considers functions from namespaces and
8461 // classes associated with the types of the function arguments.
8462 // - When looking for a prior declaration of a class or a function
8463 // declared as a friend, scopes outside the innermost enclosing
8464 // namespace scope are not considered.
8465
John McCallde3fd222010-10-12 23:13:28 +00008466 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008467 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8468 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00008469 assert(Name);
8470
Douglas Gregor6c110f32010-12-16 01:14:37 +00008471 // Check for unexpanded parameter packs.
8472 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8473 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8474 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8475 return 0;
8476
John McCall07e91c02009-08-06 02:15:43 +00008477 // The context we found the declaration in, or in which we should
8478 // create the declaration.
8479 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00008480 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008481 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00008482 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00008483
John McCallde3fd222010-10-12 23:13:28 +00008484 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00008485
John McCallde3fd222010-10-12 23:13:28 +00008486 // There are four cases here.
8487 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00008488 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00008489 // there as appropriate.
8490 // Recover from invalid scope qualifiers as if they just weren't there.
8491 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00008492 // C++0x [namespace.memdef]p3:
8493 // If the name in a friend declaration is neither qualified nor
8494 // a template-id and the declaration is a function or an
8495 // elaborated-type-specifier, the lookup to determine whether
8496 // the entity has been previously declared shall not consider
8497 // any scopes outside the innermost enclosing namespace.
8498 // C++0x [class.friend]p11:
8499 // If a friend declaration appears in a local class and the name
8500 // specified is an unqualified name, a prior declaration is
8501 // looked up without considering scopes that are outside the
8502 // innermost enclosing non-class scope. For a friend function
8503 // declaration, if there is no prior declaration, the program is
8504 // ill-formed.
8505 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00008506 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00008507
John McCallf7cfb222010-10-13 05:45:15 +00008508 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00008509 DC = CurContext;
8510 while (true) {
8511 // Skip class contexts. If someone can cite chapter and verse
8512 // for this behavior, that would be nice --- it's what GCC and
8513 // EDG do, and it seems like a reasonable intent, but the spec
8514 // really only says that checks for unqualified existing
8515 // declarations should stop at the nearest enclosing namespace,
8516 // not that they should only consider the nearest enclosing
8517 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008518 while (DC->isRecord())
8519 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00008520
John McCall1f82f242009-11-18 22:49:29 +00008521 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00008522
8523 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00008524 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00008525 break;
John McCallf7cfb222010-10-13 05:45:15 +00008526
John McCallf4776592010-10-14 22:22:28 +00008527 if (isTemplateId) {
8528 if (isa<TranslationUnitDecl>(DC)) break;
8529 } else {
8530 if (DC->isFileContext()) break;
8531 }
John McCall07e91c02009-08-06 02:15:43 +00008532 DC = DC->getParent();
8533 }
8534
8535 // C++ [class.friend]p1: A friend of a class is a function or
8536 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00008537 // C++0x changes this for both friend types and functions.
8538 // Most C++ 98 compilers do seem to give an error here, so
8539 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00008540 if (!Previous.empty() && DC->Equals(CurContext)
8541 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00008542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00008543
John McCallccbc0322010-10-13 06:22:15 +00008544 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00008545
John McCallde3fd222010-10-12 23:13:28 +00008546 // - There's a non-dependent scope specifier, in which case we
8547 // compute it and do a previous lookup there for a function
8548 // or function template.
8549 } else if (!SS.getScopeRep()->isDependent()) {
8550 DC = computeDeclContext(SS);
8551 if (!DC) return 0;
8552
8553 if (RequireCompleteDeclContext(SS, DC)) return 0;
8554
8555 LookupQualifiedName(Previous, DC);
8556
8557 // Ignore things found implicitly in the wrong scope.
8558 // TODO: better diagnostics for this case. Suggesting the right
8559 // qualified scope would be nice...
8560 LookupResult::Filter F = Previous.makeFilter();
8561 while (F.hasNext()) {
8562 NamedDecl *D = F.next();
8563 if (!DC->InEnclosingNamespaceSetOf(
8564 D->getDeclContext()->getRedeclContext()))
8565 F.erase();
8566 }
8567 F.done();
8568
8569 if (Previous.empty()) {
8570 D.setInvalidType();
8571 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8572 return 0;
8573 }
8574
8575 // C++ [class.friend]p1: A friend of a class is a function or
8576 // class that is not a member of the class . . .
8577 if (DC->Equals(CurContext))
8578 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8579
8580 // - There's a scope specifier that does not match any template
8581 // parameter lists, in which case we use some arbitrary context,
8582 // create a method or method template, and wait for instantiation.
8583 // - There's a scope specifier that does match some template
8584 // parameter lists, which we don't handle right now.
8585 } else {
8586 DC = CurContext;
8587 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00008588 }
8589
John McCallf7cfb222010-10-13 05:45:15 +00008590 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00008591 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00008592 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8593 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8594 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00008595 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00008596 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8597 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00008598 return 0;
John McCall07e91c02009-08-06 02:15:43 +00008599 }
John McCall07e91c02009-08-06 02:15:43 +00008600 }
8601
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008602 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00008603 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00008604 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00008605 IsDefinition,
8606 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00008607 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00008608
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008609 assert(ND->getDeclContext() == DC);
8610 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00008611
John McCall759e32b2009-08-31 22:39:49 +00008612 // Add the function declaration to the appropriate lookup tables,
8613 // adjusting the redeclarations list as necessary. We don't
8614 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00008615 //
John McCall759e32b2009-08-31 22:39:49 +00008616 // Also update the scope-based lookup if the target context's
8617 // lookup context is in lexical scope.
8618 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00008619 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008620 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008621 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008622 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00008623 }
John McCallaa74a0c2009-08-28 07:59:38 +00008624
8625 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00008626 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00008627 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00008628 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00008629 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00008630
John McCallde3fd222010-10-12 23:13:28 +00008631 if (ND->isInvalidDecl())
8632 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00008633 else {
8634 FunctionDecl *FD;
8635 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8636 FD = FTD->getTemplatedDecl();
8637 else
8638 FD = cast<FunctionDecl>(ND);
8639
8640 // Mark templated-scope function declarations as unsupported.
8641 if (FD->getNumTemplateParameterLists())
8642 FrD->setUnsupportedFriend(true);
8643 }
John McCallde3fd222010-10-12 23:13:28 +00008644
John McCall48871652010-08-21 09:40:31 +00008645 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00008646}
8647
John McCall48871652010-08-21 09:40:31 +00008648void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8649 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00008650
Sebastian Redlf769df52009-03-24 22:27:57 +00008651 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8652 if (!Fn) {
8653 Diag(DelLoc, diag::err_deleted_non_function);
8654 return;
8655 }
8656 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8657 Diag(DelLoc, diag::err_deleted_decl_not_first);
8658 Diag(Prev->getLocation(), diag::note_previous_declaration);
8659 // If the declaration wasn't the first, we delete the function anyway for
8660 // recovery.
8661 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +00008662 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +00008663}
Sebastian Redl4c018662009-04-27 21:33:24 +00008664
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008665void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8666 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8667
8668 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +00008669 if (MD->getParent()->isDependentType()) {
8670 MD->setDefaulted();
8671 MD->setExplicitlyDefaulted();
8672 return;
8673 }
8674
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008675 CXXSpecialMember Member = getSpecialMember(MD);
8676 if (Member == CXXInvalid) {
8677 Diag(DefaultLoc, diag::err_default_special_members);
8678 return;
8679 }
8680
8681 MD->setDefaulted();
8682 MD->setExplicitlyDefaulted();
8683
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008684 // If this definition appears within the record, do the checking when
8685 // the record is complete.
8686 const FunctionDecl *Primary = MD;
8687 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8688 // Find the uninstantiated declaration that actually had the '= default'
8689 // on it.
8690 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8691
8692 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008693 return;
8694
8695 switch (Member) {
8696 case CXXDefaultConstructor: {
8697 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8698 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008699 if (!CD->isInvalidDecl())
8700 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8701 break;
8702 }
8703
8704 case CXXCopyConstructor: {
8705 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8706 CheckExplicitlyDefaultedCopyConstructor(CD);
8707 if (!CD->isInvalidDecl())
8708 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008709 break;
8710 }
Alexis Huntf91729462011-05-12 22:46:25 +00008711
Alexis Huntc9a55732011-05-14 05:23:28 +00008712 case CXXCopyAssignment: {
8713 CheckExplicitlyDefaultedCopyAssignment(MD);
8714 if (!MD->isInvalidDecl())
8715 DefineImplicitCopyAssignment(DefaultLoc, MD);
8716 break;
8717 }
8718
Alexis Huntf91729462011-05-12 22:46:25 +00008719 case CXXDestructor: {
8720 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8721 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +00008722 if (!DD->isInvalidDecl())
8723 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +00008724 break;
8725 }
8726
Alexis Hunt119c10e2011-05-25 23:16:36 +00008727 case CXXMoveConstructor:
8728 case CXXMoveAssignment:
8729 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8730 break;
8731
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008732 default:
Alexis Huntc9a55732011-05-14 05:23:28 +00008733 // FIXME: Do the rest once we have move functions
Alexis Hunt5a7fa252011-05-12 06:15:49 +00008734 break;
8735 }
8736 } else {
8737 Diag(DefaultLoc, diag::err_default_special_members);
8738 }
8739}
8740
Sebastian Redl4c018662009-04-27 21:33:24 +00008741static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00008742 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00008743 Stmt *SubStmt = *CI;
8744 if (!SubStmt)
8745 continue;
8746 if (isa<ReturnStmt>(SubStmt))
8747 Self.Diag(SubStmt->getSourceRange().getBegin(),
8748 diag::err_return_in_constructor_handler);
8749 if (!isa<Expr>(SubStmt))
8750 SearchForReturnInStmt(Self, SubStmt);
8751 }
8752}
8753
8754void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8755 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8756 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8757 SearchForReturnInStmt(*this, Handler);
8758 }
8759}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008760
Mike Stump11289f42009-09-09 15:08:12 +00008761bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008762 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00008763 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8764 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008765
Chandler Carruth284bb2e2010-02-15 11:53:20 +00008766 if (Context.hasSameType(NewTy, OldTy) ||
8767 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008768 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008769
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008770 // Check if the return types are covariant
8771 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00008772
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008773 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008774 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8775 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008776 NewClassTy = NewPT->getPointeeType();
8777 OldClassTy = OldPT->getPointeeType();
8778 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008779 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8780 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8781 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8782 NewClassTy = NewRT->getPointeeType();
8783 OldClassTy = OldRT->getPointeeType();
8784 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008785 }
8786 }
Mike Stump11289f42009-09-09 15:08:12 +00008787
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008788 // The return types aren't either both pointers or references to a class type.
8789 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00008790 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008791 diag::err_different_return_type_for_overriding_virtual_function)
8792 << New->getDeclName() << NewTy << OldTy;
8793 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00008794
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008795 return true;
8796 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008797
Anders Carlssone60365b2009-12-31 18:34:24 +00008798 // C++ [class.virtual]p6:
8799 // If the return type of D::f differs from the return type of B::f, the
8800 // class type in the return type of D::f shall be complete at the point of
8801 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008802 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8803 if (!RT->isBeingDefined() &&
8804 RequireCompleteType(New->getLocation(), NewClassTy,
8805 PDiag(diag::err_covariant_return_incomplete)
8806 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00008807 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00008808 }
Anders Carlssone60365b2009-12-31 18:34:24 +00008809
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008810 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008811 // Check if the new class derives from the old class.
8812 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8813 Diag(New->getLocation(),
8814 diag::err_covariant_return_not_derived)
8815 << New->getDeclName() << NewTy << OldTy;
8816 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8817 return true;
8818 }
Mike Stump11289f42009-09-09 15:08:12 +00008819
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008820 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00008821 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00008822 diag::err_covariant_return_inaccessible_base,
8823 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8824 // FIXME: Should this point to the return type?
8825 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00008826 // FIXME: this note won't trigger for delayed access control
8827 // diagnostics, and it's impossible to get an undelayed error
8828 // here from access control during the original parse because
8829 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008830 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8831 return true;
8832 }
8833 }
Mike Stump11289f42009-09-09 15:08:12 +00008834
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008835 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00008836 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008837 Diag(New->getLocation(),
8838 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008839 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008840 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8841 return true;
8842 };
Mike Stump11289f42009-09-09 15:08:12 +00008843
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008844
8845 // The new class type must have the same or less qualifiers as the old type.
8846 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8847 Diag(New->getLocation(),
8848 diag::err_covariant_return_type_class_type_more_qualified)
8849 << New->getDeclName() << NewTy << OldTy;
8850 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8851 return true;
8852 };
Mike Stump11289f42009-09-09 15:08:12 +00008853
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00008854 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00008855}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008856
Douglas Gregor21920e372009-12-01 17:24:26 +00008857/// \brief Mark the given method pure.
8858///
8859/// \param Method the method to be marked pure.
8860///
8861/// \param InitRange the source range that covers the "0" initializer.
8862bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008863 SourceLocation EndLoc = InitRange.getEnd();
8864 if (EndLoc.isValid())
8865 Method->setRangeEnd(EndLoc);
8866
Douglas Gregor21920e372009-12-01 17:24:26 +00008867 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8868 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00008869 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008870 }
Douglas Gregor21920e372009-12-01 17:24:26 +00008871
8872 if (!Method->isInvalidDecl())
8873 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8874 << Method->getDeclName() << InitRange;
8875 return true;
8876}
8877
John McCall1f4ee7b2009-12-19 09:28:58 +00008878/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8879/// an initializer for the out-of-line declaration 'Dcl'. The scope
8880/// is a fresh scope pushed for just this purpose.
8881///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008882/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8883/// static data member of class X, names should be looked up in the scope of
8884/// class X.
John McCall48871652010-08-21 09:40:31 +00008885void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008886 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008887 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008888
John McCall1f4ee7b2009-12-19 09:28:58 +00008889 // We should only get called for declarations with scope specifiers, like:
8890 // int foo::bar;
8891 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008892 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008893}
8894
8895/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00008896/// initializer for the out-of-line declaration 'D'.
8897void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008898 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +00008899 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008900
John McCall1f4ee7b2009-12-19 09:28:58 +00008901 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00008902 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00008903}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008904
8905/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8906/// C++ if/switch/while/for statement.
8907/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00008908DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008909 // C++ 6.4p2:
8910 // The declarator shall not specify a function or an array.
8911 // The type-specifier-seq shall not contain typedef and shall not declare a
8912 // new class or enumeration.
8913 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8914 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +00008915
8916 Decl *Dcl = ActOnDeclarator(S, D);
8917 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
8918 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008919 << D.getSourceRange();
8920 return DeclResult();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008921 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008922
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00008923 return Dcl;
8924}
Anders Carlssonf98849e2009-12-02 17:15:43 +00008925
Douglas Gregor88d292c2010-05-13 16:44:06 +00008926void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8927 bool DefinitionRequired) {
8928 // Ignore any vtable uses in unevaluated operands or for classes that do
8929 // not have a vtable.
8930 if (!Class->isDynamicClass() || Class->isDependentContext() ||
8931 CurContext->isDependentContext() ||
8932 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00008933 return;
8934
Douglas Gregor88d292c2010-05-13 16:44:06 +00008935 // Try to insert this class into the map.
8936 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8937 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8938 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8939 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00008940 // If we already had an entry, check to see if we are promoting this vtable
8941 // to required a definition. If so, we need to reappend to the VTableUses
8942 // list, since we may have already processed the first entry.
8943 if (DefinitionRequired && !Pos.first->second) {
8944 Pos.first->second = true;
8945 } else {
8946 // Otherwise, we can early exit.
8947 return;
8948 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00008949 }
8950
8951 // Local classes need to have their virtual members marked
8952 // immediately. For all other classes, we mark their virtual members
8953 // at the end of the translation unit.
8954 if (Class->isLocalClass())
8955 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00008956 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00008957 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00008958}
8959
Douglas Gregor88d292c2010-05-13 16:44:06 +00008960bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008961 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00008962 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00008963
Douglas Gregor88d292c2010-05-13 16:44:06 +00008964 // Note: The VTableUses vector could grow as a result of marking
8965 // the members of a class as "used", so we check the size each
8966 // time through the loop and prefer indices (with are stable) to
8967 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +00008968 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +00008969 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00008970 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00008971 if (!Class)
8972 continue;
8973
8974 SourceLocation Loc = VTableUses[I].second;
8975
8976 // If this class has a key function, but that key function is
8977 // defined in another translation unit, we don't need to emit the
8978 // vtable even though we're using it.
8979 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00008980 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00008981 switch (KeyFunction->getTemplateSpecializationKind()) {
8982 case TSK_Undeclared:
8983 case TSK_ExplicitSpecialization:
8984 case TSK_ExplicitInstantiationDeclaration:
8985 // The key function is in another translation unit.
8986 continue;
8987
8988 case TSK_ExplicitInstantiationDefinition:
8989 case TSK_ImplicitInstantiation:
8990 // We will be instantiating the key function.
8991 break;
8992 }
8993 } else if (!KeyFunction) {
8994 // If we have a class with no key function that is the subject
8995 // of an explicit instantiation declaration, suppress the
8996 // vtable; it will live with the explicit instantiation
8997 // definition.
8998 bool IsExplicitInstantiationDeclaration
8999 = Class->getTemplateSpecializationKind()
9000 == TSK_ExplicitInstantiationDeclaration;
9001 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9002 REnd = Class->redecls_end();
9003 R != REnd; ++R) {
9004 TemplateSpecializationKind TSK
9005 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9006 if (TSK == TSK_ExplicitInstantiationDeclaration)
9007 IsExplicitInstantiationDeclaration = true;
9008 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9009 IsExplicitInstantiationDeclaration = false;
9010 break;
9011 }
9012 }
9013
9014 if (IsExplicitInstantiationDeclaration)
9015 continue;
9016 }
9017
9018 // Mark all of the virtual members of this class as referenced, so
9019 // that we can build a vtable. Then, tell the AST consumer that a
9020 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +00009021 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +00009022 MarkVirtualMembersReferenced(Loc, Class);
9023 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9024 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9025
9026 // Optionally warn if we're emitting a weak vtable.
9027 if (Class->getLinkage() == ExternalLinkage &&
9028 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00009029 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00009030 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9031 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00009032 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00009033 VTableUses.clear();
9034
Douglas Gregor97509692011-04-22 22:25:37 +00009035 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +00009036}
Anders Carlsson82fccd02009-12-07 08:24:59 +00009037
Rafael Espindola5b334082010-03-26 00:36:59 +00009038void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9039 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00009040 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9041 e = RD->method_end(); i != e; ++i) {
9042 CXXMethodDecl *MD = *i;
9043
9044 // C++ [basic.def.odr]p2:
9045 // [...] A virtual member function is used if it is not pure. [...]
9046 if (MD->isVirtual() && !MD->isPure())
9047 MarkDeclarationReferenced(Loc, MD);
9048 }
Rafael Espindola5b334082010-03-26 00:36:59 +00009049
9050 // Only classes that have virtual bases need a VTT.
9051 if (RD->getNumVBases() == 0)
9052 return;
9053
9054 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9055 e = RD->bases_end(); i != e; ++i) {
9056 const CXXRecordDecl *Base =
9057 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00009058 if (Base->getNumVBases() == 0)
9059 continue;
9060 MarkVirtualMembersReferenced(Loc, Base);
9061 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00009062}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009063
9064/// SetIvarInitializers - This routine builds initialization ASTs for the
9065/// Objective-C implementation whose ivars need be initialized.
9066void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9067 if (!getLangOptions().CPlusPlus)
9068 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00009069 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009070 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9071 CollectIvarsToConstructOrDestruct(OID, ivars);
9072 if (ivars.empty())
9073 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00009074 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009075 for (unsigned i = 0; i < ivars.size(); i++) {
9076 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00009077 if (Field->isInvalidDecl())
9078 continue;
9079
Alexis Hunt1d792652011-01-08 20:30:50 +00009080 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009081 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9082 InitializationKind InitKind =
9083 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9084
9085 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00009086 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00009087 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00009088 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009089 // Note, MemberInit could actually come back empty if no initialization
9090 // is required (e.g., because it would call a trivial default constructor)
9091 if (!MemberInit.get() || MemberInit.isInvalid())
9092 continue;
John McCallacf0ee52010-10-08 02:01:28 +00009093
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009094 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00009095 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9096 SourceLocation(),
9097 MemberInit.takeAs<Expr>(),
9098 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009099 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00009100
9101 // Be sure that the destructor is accessible and is marked as referenced.
9102 if (const RecordType *RecordTy
9103 = Context.getBaseElementType(Field->getType())
9104 ->getAs<RecordType>()) {
9105 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00009106 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00009107 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9108 CheckDestructorAccess(Field->getLocation(), Destructor,
9109 PDiag(diag::err_access_dtor_ivar)
9110 << Context.getBaseElementType(Field->getType()));
9111 }
9112 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00009113 }
9114 ObjCImplementation->setIvarInitializers(Context,
9115 AllToInit.data(), AllToInit.size());
9116 }
9117}
Alexis Hunt6118d662011-05-04 05:57:24 +00009118
Alexis Hunt27a761d2011-05-04 23:29:54 +00009119static
9120void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9121 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9122 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9123 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9124 Sema &S) {
9125 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9126 CE = Current.end();
9127 if (Ctor->isInvalidDecl())
9128 return;
9129
9130 const FunctionDecl *FNTarget = 0;
9131 CXXConstructorDecl *Target;
9132
9133 // We ignore the result here since if we don't have a body, Target will be
9134 // null below.
9135 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9136 Target
9137= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9138
9139 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9140 // Avoid dereferencing a null pointer here.
9141 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9142
9143 if (!Current.insert(Canonical))
9144 return;
9145
9146 // We know that beyond here, we aren't chaining into a cycle.
9147 if (!Target || !Target->isDelegatingConstructor() ||
9148 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9149 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9150 Valid.insert(*CI);
9151 Current.clear();
9152 // We've hit a cycle.
9153 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9154 Current.count(TCanonical)) {
9155 // If we haven't diagnosed this cycle yet, do so now.
9156 if (!Invalid.count(TCanonical)) {
9157 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +00009158 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +00009159 << Ctor;
9160
9161 // Don't add a note for a function delegating directo to itself.
9162 if (TCanonical != Canonical)
9163 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9164
9165 CXXConstructorDecl *C = Target;
9166 while (C->getCanonicalDecl() != Canonical) {
9167 (void)C->getTargetConstructor()->hasBody(FNTarget);
9168 assert(FNTarget && "Ctor cycle through bodiless function");
9169
9170 C
9171 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9172 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9173 }
9174 }
9175
9176 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9177 Invalid.insert(*CI);
9178 Current.clear();
9179 } else {
9180 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9181 }
9182}
9183
9184
Alexis Hunt6118d662011-05-04 05:57:24 +00009185void Sema::CheckDelegatingCtorCycles() {
9186 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9187
Alexis Hunt27a761d2011-05-04 23:29:54 +00009188 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9189 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +00009190
9191 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
Alexis Hunt27a761d2011-05-04 23:29:54 +00009192 I = DelegatingCtorDecls.begin(),
9193 E = DelegatingCtorDecls.end();
9194 I != E; ++I) {
9195 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +00009196 }
Alexis Hunt27a761d2011-05-04 23:29:54 +00009197
9198 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9199 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +00009200}