blob: 36f2734a1ad7e7e8b3e70f14fbda9f6c86c90731 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000028#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner8123a952008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattner9e979552008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 public:
Mike Stump1eb44332009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000054 };
Chris Lattner8123a952008-04-10 02:22:51 +000055
Chris Lattner9e979552008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000063 }
64
Chris Lattner9e979552008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000090 }
Chris Lattner8123a952008-04-10 02:22:51 +000091
Douglas Gregor3996f232008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattner9e979552008-04-12 23:52:44 +000094
Douglas Gregor796da182008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000103 }
Chris Lattner8123a952008-04-10 02:22:51 +0000104}
105
Anders Carlssoned961f92009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson5653ca52009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssoned961f92009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000127 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Anders Carlssoned961f92009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Anders Carlssoned961f92009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000137}
138
Chris Lattner8123a952008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142void
Mike Stump1eb44332009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlsson66e30672009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump1eb44332009-09-09 15:08:12 +0000168
Anders Carlssoned961f92009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000170}
171
Douglas Gregor61366e92008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson5e300d12009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187}
188
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000200}
201
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregor6cc15182009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000267 // FIXME: If the parameter doesn't have an identifier then the location
268 // points to the '=' which means that the fixit hint won't remove any
269 // extra spaces between the type and the '='.
270 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000271 if (NewParam->getIdentifier())
272 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000273
Mike Stump1eb44332009-09-09 15:08:12 +0000274 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000275 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000276 << NewParam->getDefaultArgRange()
277 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
278 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000279
280 // Look for the function declaration where the default argument was
281 // actually written, which may be a declaration prior to Old.
282 for (FunctionDecl *Older = Old->getPreviousDeclaration();
283 Older; Older = Older->getPreviousDeclaration()) {
284 if (!Older->getParamDecl(p)->hasDefaultArg())
285 break;
286
287 OldParam = Older->getParamDecl(p);
288 }
289
290 Diag(OldParam->getLocation(), diag::note_previous_definition)
291 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000292 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000293 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000294 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000295 if (OldParam->hasUninstantiatedDefaultArg())
296 NewParam->setUninstantiatedDefaultArg(
297 OldParam->getUninstantiatedDefaultArg());
298 else
299 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000300 } else if (NewParam->hasDefaultArg()) {
301 if (New->getDescribedFunctionTemplate()) {
302 // Paragraph 4, quoted above, only applies to non-template functions.
303 Diag(NewParam->getLocation(),
304 diag::err_param_default_argument_template_redecl)
305 << NewParam->getDefaultArgRange();
306 Diag(Old->getLocation(), diag::note_template_prev_declaration)
307 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000308 } else if (New->getTemplateSpecializationKind()
309 != TSK_ImplicitInstantiation &&
310 New->getTemplateSpecializationKind() != TSK_Undeclared) {
311 // C++ [temp.expr.spec]p21:
312 // Default function arguments shall not be specified in a declaration
313 // or a definition for one of the following explicit specializations:
314 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000315 // - the explicit specialization of a member function template;
316 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000317 // template where the class template specialization to which the
318 // member function specialization belongs is implicitly
319 // instantiated.
320 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
321 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
322 << New->getDeclName()
323 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000324 } else if (New->getDeclContext()->isDependentContext()) {
325 // C++ [dcl.fct.default]p6 (DR217):
326 // Default arguments for a member function of a class template shall
327 // be specified on the initial declaration of the member function
328 // within the class template.
329 //
330 // Reading the tea leaves a bit in DR217 and its reference to DR205
331 // leads me to the conclusion that one cannot add default function
332 // arguments for an out-of-line definition of a member function of a
333 // dependent type.
334 int WhichKind = 2;
335 if (CXXRecordDecl *Record
336 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
337 if (Record->getDescribedClassTemplate())
338 WhichKind = 0;
339 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
340 WhichKind = 1;
341 else
342 WhichKind = 2;
343 }
344
345 Diag(NewParam->getLocation(),
346 diag::err_param_default_argument_member_template_redecl)
347 << WhichKind
348 << NewParam->getDefaultArgRange();
349 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000350 }
351 }
352
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000353 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000354 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
355 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000356 Invalid = true;
357 }
358
Douglas Gregorcda9c672009-02-16 17:45:42 +0000359 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000360}
361
362/// CheckCXXDefaultArguments - Verify that the default arguments for a
363/// function declaration are well-formed according to C++
364/// [dcl.fct.default].
365void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
366 unsigned NumParams = FD->getNumParams();
367 unsigned p;
368
369 // Find first parameter with a default argument
370 for (p = 0; p < NumParams; ++p) {
371 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000372 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000373 break;
374 }
375
376 // C++ [dcl.fct.default]p4:
377 // In a given function declaration, all parameters
378 // subsequent to a parameter with a default argument shall
379 // have default arguments supplied in this or previous
380 // declarations. A default argument shall not be redefined
381 // by a later declaration (not even to the same value).
382 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000383 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000385 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000386 if (Param->isInvalidDecl())
387 /* We already complained about this parameter. */;
388 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000389 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000390 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000391 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000392 else
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000394 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 LastMissingDefaultArg = p;
397 }
398 }
399
400 if (LastMissingDefaultArg > 0) {
401 // Some default arguments were missing. Clear out all of the
402 // default arguments up to (and including) the last missing
403 // default argument, so that we leave the function parameters
404 // in a semantically valid state.
405 for (p = 0; p <= LastMissingDefaultArg; ++p) {
406 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000407 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000408 if (!Param->hasUnparsedDefaultArg())
409 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000410 Param->setDefaultArg(0);
411 }
412 }
413 }
414}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000415
Douglas Gregorb48fe382008-10-31 09:07:45 +0000416/// isCurrentClassName - Determine whether the identifier II is the
417/// name of the class type currently being defined. In the case of
418/// nested classes, this will only return true if II is the name of
419/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000420bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
421 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000422 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000423 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000424 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000425 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
426 } else
427 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
428
429 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000430 return &II == CurDecl->getIdentifier();
431 else
432 return false;
433}
434
Mike Stump1eb44332009-09-09 15:08:12 +0000435/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000436///
437/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
438/// and returns NULL otherwise.
439CXXBaseSpecifier *
440Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
441 SourceRange SpecifierRange,
442 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000443 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000444 SourceLocation BaseLoc) {
445 // C++ [class.union]p1:
446 // A union shall not have base classes.
447 if (Class->isUnion()) {
448 Diag(Class->getLocation(), diag::err_base_clause_on_union)
449 << SpecifierRange;
450 return 0;
451 }
452
453 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000454 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000455 Class->getTagKind() == RecordDecl::TK_class,
456 Access, BaseType);
457
458 // Base specifiers must be record types.
459 if (!BaseType->isRecordType()) {
460 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
461 return 0;
462 }
463
464 // C++ [class.union]p1:
465 // A union shall not be used as a base class.
466 if (BaseType->isUnionType()) {
467 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.derived]p2:
472 // The class-name in a base-specifier shall not be an incompletely
473 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000474 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000475 PDiag(diag::err_incomplete_base_class)
476 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000477 return 0;
478
Eli Friedman1d954f62009-08-15 21:55:26 +0000479 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000480 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000481 assert(BaseDecl && "Record type has no declaration");
482 BaseDecl = BaseDecl->getDefinition(Context);
483 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
485 assert(CXXBaseDecl && "Base type is not a C++ type");
486 if (!CXXBaseDecl->isEmpty())
487 Class->setEmpty(false);
488 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489 Class->setPolymorphic(true);
490
491 // C++ [dcl.init.aggr]p1:
492 // An aggregate is [...] a class with [...] no base classes [...].
493 Class->setAggregate(false);
494 Class->setPOD(false);
495
Anders Carlsson347ba892009-04-16 00:08:20 +0000496 if (Virtual) {
497 // C++ [class.ctor]p5:
498 // A constructor is trivial if its class has no virtual base classes.
499 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000500
501 // C++ [class.copy]p6:
502 // A copy constructor is trivial if its class has no virtual base classes.
503 Class->setHasTrivialCopyConstructor(false);
504
505 // C++ [class.copy]p11:
506 // A copy assignment operator is trivial if its class has no virtual
507 // base classes.
508 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000509
510 // C++0x [meta.unary.prop] is_empty:
511 // T is a class type, but not a union type, with ... no virtual base
512 // classes
513 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000514 } else {
515 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000516 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000517 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000518 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
519 Class->setHasTrivialConstructor(false);
520
521 // C++ [class.copy]p6:
522 // A copy constructor is trivial if all the direct base classes of its
523 // class have trivial copy constructors.
524 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
525 Class->setHasTrivialCopyConstructor(false);
526
527 // C++ [class.copy]p11:
528 // A copy assignment operator is trivial if all the direct base classes
529 // of its class have trivial copy assignment operators.
530 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
531 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000533
534 // C++ [class.ctor]p3:
535 // A destructor is trivial if all the direct base classes of its class
536 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000537 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
538 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor2943aed2009-03-03 04:44:36 +0000540 // Create the base specifier.
541 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000542 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
543 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000544 Access, BaseType);
545}
546
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000547/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
548/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000549/// example:
550/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000551/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000552Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000553Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000554 bool Virtual, AccessSpecifier Access,
555 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000556 if (!classdecl)
557 return true;
558
Douglas Gregor40808ce2009-03-09 23:48:35 +0000559 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000560 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000561 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000562 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
563 Virtual, Access,
564 BaseType, BaseLoc))
565 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Douglas Gregor2943aed2009-03-03 04:44:36 +0000567 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000568}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000569
Douglas Gregor2943aed2009-03-03 04:44:36 +0000570/// \brief Performs the actual work of attaching the given base class
571/// specifiers to a C++ class.
572bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
573 unsigned NumBases) {
574 if (NumBases == 0)
575 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000576
577 // Used to keep track of which base types we have already seen, so
578 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000579 // that the key is always the unqualified canonical type of the base
580 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000581 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
582
583 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000584 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000585 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000586 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000587 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000588 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000589 NewBaseType = NewBaseType.getUnqualifiedType();
590
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000591 if (KnownBaseTypes[NewBaseType]) {
592 // C++ [class.mi]p3:
593 // A class shall not be specified as a direct base class of a
594 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000596 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000597 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000599
600 // Delete the duplicate base class specifier; we're going to
601 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000602 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603
604 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605 } else {
606 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 KnownBaseTypes[NewBaseType] = Bases[idx];
608 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609 }
610 }
611
612 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000613 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000614
615 // Delete the remaining (good) base class specifiers, since their
616 // data has been copied into the CXXRecordDecl.
617 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000618 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000619
620 return Invalid;
621}
622
623/// ActOnBaseSpecifiers - Attach the given base specifiers to the
624/// class, after checking whether there are any duplicate base
625/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000626void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 unsigned NumBases) {
628 if (!ClassDecl || !Bases || !NumBases)
629 return;
630
631 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000632 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000634}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000635
Douglas Gregora8f32e02009-10-06 17:59:45 +0000636/// \brief Determine whether the type \p Derived is a C++ class that is
637/// derived from the type \p Base.
638bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
639 if (!getLangOptions().CPlusPlus)
640 return false;
641
642 const RecordType *DerivedRT = Derived->getAs<RecordType>();
643 if (!DerivedRT)
644 return false;
645
646 const RecordType *BaseRT = Base->getAs<RecordType>();
647 if (!BaseRT)
648 return false;
649
650 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
651 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
652 return DerivedRD->isDerivedFrom(BaseRD);
653}
654
655/// \brief Determine whether the type \p Derived is a C++ class that is
656/// derived from the type \p Base.
657bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
658 if (!getLangOptions().CPlusPlus)
659 return false;
660
661 const RecordType *DerivedRT = Derived->getAs<RecordType>();
662 if (!DerivedRT)
663 return false;
664
665 const RecordType *BaseRT = Base->getAs<RecordType>();
666 if (!BaseRT)
667 return false;
668
669 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
670 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
671 return DerivedRD->isDerivedFrom(BaseRD, Paths);
672}
673
674/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
675/// conversion (where Derived and Base are class types) is
676/// well-formed, meaning that the conversion is unambiguous (and
677/// that all of the base classes are accessible). Returns true
678/// and emits a diagnostic if the code is ill-formed, returns false
679/// otherwise. Loc is the location where this routine should point to
680/// if there is an error, and Range is the source range to highlight
681/// if there is an error.
682bool
683Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
684 unsigned InaccessibleBaseID,
685 unsigned AmbigiousBaseConvID,
686 SourceLocation Loc, SourceRange Range,
687 DeclarationName Name) {
688 // First, determine whether the path from Derived to Base is
689 // ambiguous. This is slightly more expensive than checking whether
690 // the Derived to Base conversion exists, because here we need to
691 // explore multiple paths to determine if there is an ambiguity.
692 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
693 /*DetectVirtual=*/false);
694 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
695 assert(DerivationOkay &&
696 "Can only be used with a derived-to-base conversion");
697 (void)DerivationOkay;
698
699 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
700 // Check that the base class can be accessed.
701 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
702 Name);
703 }
704
705 // We know that the derived-to-base conversion is ambiguous, and
706 // we're going to produce a diagnostic. Perform the derived-to-base
707 // search just one more time to compute all of the possible paths so
708 // that we can print them out. This is more expensive than any of
709 // the previous derived-to-base checks we've done, but at this point
710 // performance isn't as much of an issue.
711 Paths.clear();
712 Paths.setRecordingPaths(true);
713 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
714 assert(StillOkay && "Can only be used with a derived-to-base conversion");
715 (void)StillOkay;
716
717 // Build up a textual representation of the ambiguous paths, e.g.,
718 // D -> B -> A, that will be used to illustrate the ambiguous
719 // conversions in the diagnostic. We only print one of the paths
720 // to each base class subobject.
721 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
722
723 Diag(Loc, AmbigiousBaseConvID)
724 << Derived << Base << PathDisplayStr << Range << Name;
725 return true;
726}
727
728bool
729Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
730 SourceLocation Loc, SourceRange Range) {
731 return CheckDerivedToBaseConversion(Derived, Base,
732 diag::err_conv_to_inaccessible_base,
733 diag::err_ambiguous_derived_to_base_conv,
734 Loc, Range, DeclarationName());
735}
736
737
738/// @brief Builds a string representing ambiguous paths from a
739/// specific derived class to different subobjects of the same base
740/// class.
741///
742/// This function builds a string that can be used in error messages
743/// to show the different paths that one can take through the
744/// inheritance hierarchy to go from the derived class to different
745/// subobjects of a base class. The result looks something like this:
746/// @code
747/// struct D -> struct B -> struct A
748/// struct D -> struct C -> struct A
749/// @endcode
750std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
751 std::string PathDisplayStr;
752 std::set<unsigned> DisplayedPaths;
753 for (CXXBasePaths::paths_iterator Path = Paths.begin();
754 Path != Paths.end(); ++Path) {
755 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
756 // We haven't displayed a path to this particular base
757 // class subobject yet.
758 PathDisplayStr += "\n ";
759 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
760 for (CXXBasePath::const_iterator Element = Path->begin();
761 Element != Path->end(); ++Element)
762 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
763 }
764 }
765
766 return PathDisplayStr;
767}
768
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000769//===----------------------------------------------------------------------===//
770// C++ class member Handling
771//===----------------------------------------------------------------------===//
772
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000773/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
774/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
775/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000776/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000777Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000778Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000779 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000780 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000781 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000782 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000783 Expr *BitWidth = static_cast<Expr*>(BW);
784 Expr *Init = static_cast<Expr*>(InitExpr);
785 SourceLocation Loc = D.getIdentifierLoc();
786
Sebastian Redl669d5d72008-11-14 23:42:31 +0000787 bool isFunc = D.isFunctionDeclarator();
788
John McCall67d1a672009-08-06 02:15:43 +0000789 assert(!DS.isFriendSpecified());
790
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000791 // C++ 9.2p6: A member shall not be declared to have automatic storage
792 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000793 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
794 // data members and cannot be applied to names declared const or static,
795 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000796 switch (DS.getStorageClassSpec()) {
797 case DeclSpec::SCS_unspecified:
798 case DeclSpec::SCS_typedef:
799 case DeclSpec::SCS_static:
800 // FALL THROUGH.
801 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000802 case DeclSpec::SCS_mutable:
803 if (isFunc) {
804 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000805 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000806 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000807 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Sebastian Redla11f42f2008-11-17 23:24:37 +0000809 // FIXME: It would be nicer if the keyword was ignored only for this
810 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000811 D.getMutableDeclSpec().ClearStorageClassSpecs();
812 } else {
813 QualType T = GetTypeForDeclarator(D, S);
814 diag::kind err = static_cast<diag::kind>(0);
815 if (T->isReferenceType())
816 err = diag::err_mutable_reference;
817 else if (T.isConstQualified())
818 err = diag::err_mutable_const;
819 if (err != 0) {
820 if (DS.getStorageClassSpecLoc().isValid())
821 Diag(DS.getStorageClassSpecLoc(), err);
822 else
823 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000824 // FIXME: It would be nicer if the keyword was ignored only for this
825 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000826 D.getMutableDeclSpec().ClearStorageClassSpecs();
827 }
828 }
829 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000830 default:
831 if (DS.getStorageClassSpecLoc().isValid())
832 Diag(DS.getStorageClassSpecLoc(),
833 diag::err_storageclass_invalid_for_member);
834 else
835 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
836 D.getMutableDeclSpec().ClearStorageClassSpecs();
837 }
838
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000839 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000840 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000841 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000842 // Check also for this case:
843 //
844 // typedef int f();
845 // f a;
846 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000847 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000848 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000849 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000850
Sebastian Redl669d5d72008-11-14 23:42:31 +0000851 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
852 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000853 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000854
855 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000856 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000857 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000858 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
859 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000860 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000861 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000862 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
863 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000864 if (!Member) {
865 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000866 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000867 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000868
869 // Non-instance-fields can't have a bitfield.
870 if (BitWidth) {
871 if (Member->isInvalidDecl()) {
872 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000873 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000874 // C++ 9.6p3: A bit-field shall not be a static member.
875 // "static member 'A' cannot be a bit-field"
876 Diag(Loc, diag::err_static_not_bitfield)
877 << Name << BitWidth->getSourceRange();
878 } else if (isa<TypedefDecl>(Member)) {
879 // "typedef member 'x' cannot be a bit-field"
880 Diag(Loc, diag::err_typedef_not_bitfield)
881 << Name << BitWidth->getSourceRange();
882 } else {
883 // A function typedef ("typedef int f(); f a;").
884 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
885 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000886 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000887 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Chris Lattner8b963ef2009-03-05 23:01:03 +0000890 DeleteExpr(BitWidth);
891 BitWidth = 0;
892 Member->setInvalidDecl();
893 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000894
895 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Douglas Gregor37b372b2009-08-20 22:52:58 +0000897 // If we have declared a member function template, set the access of the
898 // templated declaration as well.
899 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
900 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000901 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000902
Douglas Gregor10bd3682008-11-17 22:58:34 +0000903 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000904
Douglas Gregor021c3b32009-03-11 23:00:04 +0000905 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000906 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000907 if (Deleted) // FIXME: Source location is not very good.
908 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000909
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000910 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000911 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000912 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000913 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000914 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915}
916
Douglas Gregor7ad83902008-11-05 04:29:56 +0000917/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000918Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000919Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000920 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000921 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000922 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000923 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000924 SourceLocation IdLoc,
925 SourceLocation LParenLoc,
926 ExprTy **Args, unsigned NumArgs,
927 SourceLocation *CommaLocs,
928 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000929 if (!ConstructorD)
930 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000932 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
934 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000935 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000936 if (!Constructor) {
937 // The user wrote a constructor initializer on a function that is
938 // not a C++ constructor. Ignore the error for now, because we may
939 // have more member initializers coming; we'll diagnose it just
940 // once in ActOnMemInitializers.
941 return true;
942 }
943
944 CXXRecordDecl *ClassDecl = Constructor->getParent();
945
946 // C++ [class.base.init]p2:
947 // Names in a mem-initializer-id are looked up in the scope of the
948 // constructor’s class and, if not found in that scope, are looked
949 // up in the scope containing the constructor’s
950 // definition. [Note: if the constructor’s class contains a member
951 // with the same name as a direct or virtual base class of the
952 // class, a mem-initializer-id naming the member or base class and
953 // composed of a single identifier refers to the class member. A
954 // mem-initializer-id for the hidden base class may be specified
955 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000956 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000957 // Look for a member, first.
958 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000959 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000960 = ClassDecl->lookup(MemberOrBase);
961 if (Result.first != Result.second)
962 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000963
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000964 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000965
Eli Friedman59c04372009-07-29 19:44:27 +0000966 if (Member)
967 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
968 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000970 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000971 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000972 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000973 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000974 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
975 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000977 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000978
Eli Friedman59c04372009-07-29 19:44:27 +0000979 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
980 RParenLoc, ClassDecl);
981}
982
John McCallb4190042009-11-04 23:02:40 +0000983/// Checks an initializer expression for use of uninitialized fields, such as
984/// containing the field that is being initialized. Returns true if there is an
985/// uninitialized field was used an updates the SourceLocation parameter; false
986/// otherwise.
987static bool InitExprContainsUninitializedFields(const Stmt* S,
988 const FieldDecl* LhsField,
989 SourceLocation* L) {
990 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
991 if (ME) {
992 const NamedDecl* RhsField = ME->getMemberDecl();
993 if (RhsField == LhsField) {
994 // Initializing a field with itself. Throw a warning.
995 // But wait; there are exceptions!
996 // Exception #1: The field may not belong to this record.
997 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
998 const Expr* base = ME->getBase();
999 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1000 // Even though the field matches, it does not belong to this record.
1001 return false;
1002 }
1003 // None of the exceptions triggered; return true to indicate an
1004 // uninitialized field was used.
1005 *L = ME->getMemberLoc();
1006 return true;
1007 }
1008 }
1009 bool found = false;
1010 for (Stmt::const_child_iterator it = S->child_begin();
1011 it != S->child_end() && found == false;
1012 ++it) {
1013 if (isa<CallExpr>(S)) {
1014 // Do not descend into function calls or constructors, as the use
1015 // of an uninitialized field may be valid. One would have to inspect
1016 // the contents of the function/ctor to determine if it is safe or not.
1017 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1018 // may be safe, depending on what the function/ctor does.
1019 continue;
1020 }
1021 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1022 }
1023 return found;
1024}
1025
Eli Friedman59c04372009-07-29 19:44:27 +00001026Sema::MemInitResult
1027Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1028 unsigned NumArgs, SourceLocation IdLoc,
1029 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001030 // Diagnose value-uses of fields to initialize themselves, e.g.
1031 // foo(foo)
1032 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001033 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001034 for (unsigned i = 0; i < NumArgs; ++i) {
1035 SourceLocation L;
1036 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1037 // FIXME: Return true in the case when other fields are used before being
1038 // uninitialized. For example, let this field be the i'th field. When
1039 // initializing the i'th field, throw a warning if any of the >= i'th
1040 // fields are used, as they are not yet initialized.
1041 // Right now we are only handling the case where the i'th field uses
1042 // itself in its initializer.
1043 Diag(L, diag::warn_field_is_uninit);
1044 }
1045 }
1046
Eli Friedman59c04372009-07-29 19:44:27 +00001047 bool HasDependentArg = false;
1048 for (unsigned i = 0; i < NumArgs; i++)
1049 HasDependentArg |= Args[i]->isTypeDependent();
1050
1051 CXXConstructorDecl *C = 0;
1052 QualType FieldType = Member->getType();
1053 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1054 FieldType = Array->getElementType();
1055 if (FieldType->isDependentType()) {
1056 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001057 } else if (FieldType->isRecordType()) {
1058 // Member is a record (struct/union/class), so pass the initializer
1059 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001060 if (!HasDependentArg) {
1061 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1062
1063 C = PerformInitializationByConstructor(FieldType,
1064 MultiExprArg(*this,
1065 (void**)Args,
1066 NumArgs),
1067 IdLoc,
1068 SourceRange(IdLoc, RParenLoc),
1069 Member->getDeclName(), IK_Direct,
1070 ConstructorArgs);
1071
1072 if (C) {
1073 // Take over the constructor arguments as our own.
1074 NumArgs = ConstructorArgs.size();
1075 Args = (Expr **)ConstructorArgs.take();
1076 }
1077 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001078 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001079 // The member type is not a record type (or an array of record
1080 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001081 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001082 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1083 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001084 Expr *NewExp;
1085 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001086 if (FieldType->isReferenceType()) {
1087 Diag(IdLoc, diag::err_null_intialized_reference_member)
1088 << Member->getDeclName();
1089 return Diag(Member->getLocation(), diag::note_declared_at);
1090 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001091 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1092 NumArgs = 1;
1093 }
1094 else
1095 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001096 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1097 return true;
1098 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001099 }
Eli Friedman59c04372009-07-29 19:44:27 +00001100 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001101 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001102 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001103}
1104
1105Sema::MemInitResult
1106Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1107 unsigned NumArgs, SourceLocation IdLoc,
1108 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1109 bool HasDependentArg = false;
1110 for (unsigned i = 0; i < NumArgs; i++)
1111 HasDependentArg |= Args[i]->isTypeDependent();
1112
1113 if (!BaseType->isDependentType()) {
1114 if (!BaseType->isRecordType())
1115 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1116 << BaseType << SourceRange(IdLoc, RParenLoc);
1117
1118 // C++ [class.base.init]p2:
1119 // [...] Unless the mem-initializer-id names a nonstatic data
1120 // member of the constructor’s class or a direct or virtual base
1121 // of that class, the mem-initializer is ill-formed. A
1122 // mem-initializer-list can initialize a base class using any
1123 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Eli Friedman59c04372009-07-29 19:44:27 +00001125 // First, check for a direct base class.
1126 const CXXBaseSpecifier *DirectBaseSpec = 0;
1127 for (CXXRecordDecl::base_class_const_iterator Base =
1128 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001129 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +00001130 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1131 // We found a direct base of this type. That's what we're
1132 // initializing.
1133 DirectBaseSpec = &*Base;
1134 break;
1135 }
1136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Eli Friedman59c04372009-07-29 19:44:27 +00001138 // Check for a virtual base class.
1139 // FIXME: We might be able to short-circuit this if we know in advance that
1140 // there are no virtual bases.
1141 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1142 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1143 // We haven't found a base yet; search the class hierarchy for a
1144 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1146 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001147 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001148 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001149 Path != Paths.end(); ++Path) {
1150 if (Path->back().Base->isVirtual()) {
1151 VirtualBaseSpec = Path->back().Base;
1152 break;
1153 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001154 }
1155 }
1156 }
Eli Friedman59c04372009-07-29 19:44:27 +00001157
1158 // C++ [base.class.init]p2:
1159 // If a mem-initializer-id is ambiguous because it designates both
1160 // a direct non-virtual base class and an inherited virtual base
1161 // class, the mem-initializer is ill-formed.
1162 if (DirectBaseSpec && VirtualBaseSpec)
1163 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1164 << BaseType << SourceRange(IdLoc, RParenLoc);
1165 // C++ [base.class.init]p2:
1166 // Unless the mem-initializer-id names a nonstatic data membeer of the
1167 // constructor's class ot a direst or virtual base of that class, the
1168 // mem-initializer is ill-formed.
1169 if (!DirectBaseSpec && !VirtualBaseSpec)
1170 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1171 << BaseType << ClassDecl->getNameAsCString()
1172 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001173 }
1174
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001175 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001176 if (!BaseType->isDependentType() && !HasDependentArg) {
1177 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001178 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001179 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1180
1181 C = PerformInitializationByConstructor(BaseType,
1182 MultiExprArg(*this,
1183 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001184 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001185 Name, IK_Direct,
1186 ConstructorArgs);
1187 if (C) {
1188 // Take over the constructor arguments as our own.
1189 NumArgs = ConstructorArgs.size();
1190 Args = (Expr **)ConstructorArgs.take();
1191 }
Eli Friedman59c04372009-07-29 19:44:27 +00001192 }
1193
Mike Stump1eb44332009-09-09 15:08:12 +00001194 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001195 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001196}
1197
Eli Friedman80c30da2009-11-09 19:20:36 +00001198bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001199Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001200 CXXBaseOrMemberInitializer **Initializers,
1201 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001202 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001203 // We need to build the initializer AST according to order of construction
1204 // and not what user specified in the Initializers list.
1205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1206 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1207 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1208 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001209 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001211 for (unsigned i = 0; i < NumInitializers; i++) {
1212 CXXBaseOrMemberInitializer *Member = Initializers[i];
1213 if (Member->isBaseInitializer()) {
1214 if (Member->getBaseClass()->isDependentType())
1215 HasDependentBaseInit = true;
1216 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1217 } else {
1218 AllBaseFields[Member->getMember()] = Member;
1219 }
1220 }
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001222 if (HasDependentBaseInit) {
1223 // FIXME. This does not preserve the ordering of the initializers.
1224 // Try (with -Wreorder)
1225 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001226 // template<class X> struct B : A<X> {
1227 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001228 // int x1;
1229 // };
1230 // B<int> x;
1231 // On seeing one dependent type, we should essentially exit this routine
1232 // while preserving user-declared initializer list. When this routine is
1233 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001234 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001236 // If we have a dependent base initialization, we can't determine the
1237 // association between initializers and bases; just dump the known
1238 // initializers into the list, and don't try to deal with other bases.
1239 for (unsigned i = 0; i < NumInitializers; i++) {
1240 CXXBaseOrMemberInitializer *Member = Initializers[i];
1241 if (Member->isBaseInitializer())
1242 AllToInit.push_back(Member);
1243 }
1244 } else {
1245 // Push virtual bases before others.
1246 for (CXXRecordDecl::base_class_iterator VBase =
1247 ClassDecl->vbases_begin(),
1248 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1249 if (VBase->getType()->isDependentType())
1250 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001251 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001252 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001253 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001254 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001255 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001256 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1257 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001258 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001259 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001260 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001261 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001262 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001263 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001264 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001265 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001266 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1267 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1268 << 0 << VBase->getType();
1269 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1270 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001271 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001272 continue;
1273 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001274
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001275 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1276 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1277 Constructor->getLocation(), CtorArgs))
1278 continue;
1279
1280 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1281
Mike Stump1eb44332009-09-09 15:08:12 +00001282 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001283 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1284 CtorArgs.takeAs<Expr>(),
1285 CtorArgs.size(), Ctor,
1286 SourceLocation(),
1287 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001288 AllToInit.push_back(Member);
1289 }
1290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001292 for (CXXRecordDecl::base_class_iterator Base =
1293 ClassDecl->bases_begin(),
1294 E = ClassDecl->bases_end(); Base != E; ++Base) {
1295 // Virtuals are in the virtual base list and already constructed.
1296 if (Base->isVirtual())
1297 continue;
1298 // Skip dependent types.
1299 if (Base->getType()->isDependentType())
1300 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001301 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001302 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001303 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001304 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001305 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001306 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1307 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001308 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001309 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001310 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001311 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001312 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001313 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001314 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001315 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001316 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1317 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1318 << 0 << Base->getType();
1319 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1320 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001321 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001322 continue;
1323 }
1324
1325 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1326 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1327 Constructor->getLocation(), CtorArgs))
1328 continue;
1329
1330 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001331
Mike Stump1eb44332009-09-09 15:08:12 +00001332 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001333 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1334 CtorArgs.takeAs<Expr>(),
1335 CtorArgs.size(), Ctor,
1336 SourceLocation(),
1337 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001338 AllToInit.push_back(Member);
1339 }
1340 }
1341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001343 // non-static data members.
1344 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1345 E = ClassDecl->field_end(); Field != E; ++Field) {
1346 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001347 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001348 Field->getType()->getAs<RecordType>()) {
1349 CXXRecordDecl *FieldClassDecl
1350 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001351 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001352 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1353 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1354 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1355 // set to the anonymous union data member used in the initializer
1356 // list.
1357 Value->setMember(*Field);
1358 Value->setAnonUnionMember(*FA);
1359 AllToInit.push_back(Value);
1360 break;
1361 }
1362 }
1363 }
1364 continue;
1365 }
1366 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001367 QualType FT = (*Field)->getType();
1368 if (const RecordType* RT = FT->getAs<RecordType>()) {
1369 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001370 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001371 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001372 FieldRecDecl->getDefaultConstructor(Context))
1373 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1374 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001375 AllToInit.push_back(Value);
1376 continue;
1377 }
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Eli Friedman49c16da2009-11-09 01:05:47 +00001379 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001380 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001381
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001382 QualType FT = Context.getBaseElementType((*Field)->getType());
1383 if (const RecordType* RT = FT->getAs<RecordType>()) {
1384 CXXConstructorDecl *Ctor =
1385 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001386 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001387 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1388 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1389 << 1 << (*Field)->getDeclName();
1390 Diag(Field->getLocation(), diag::note_field_decl);
1391 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1392 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001393 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001394 continue;
1395 }
1396
1397 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1398 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1399 Constructor->getLocation(), CtorArgs))
1400 continue;
1401
Mike Stump1eb44332009-09-09 15:08:12 +00001402 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001403 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1404 CtorArgs.size(), Ctor,
1405 SourceLocation(),
1406 SourceLocation());
1407
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001408 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001409 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1410 if (FT.isConstQualified() && Ctor->isTrivial()) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001411 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001412 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1413 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001414 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001415 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001416 }
1417 }
1418 else if (FT->isReferenceType()) {
1419 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001420 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1421 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001422 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001423 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001424 }
1425 else if (FT.isConstQualified()) {
1426 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001427 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1428 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001429 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001430 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001431 }
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001434 NumInitializers = AllToInit.size();
1435 if (NumInitializers > 0) {
1436 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1437 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1438 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001440 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1441 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1442 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1443 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001444
1445 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001446}
1447
Eli Friedman6347f422009-07-21 19:28:10 +00001448static void *GetKeyForTopLevelField(FieldDecl *Field) {
1449 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001450 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001451 if (RT->getDecl()->isAnonymousStructOrUnion())
1452 return static_cast<void *>(RT->getDecl());
1453 }
1454 return static_cast<void *>(Field);
1455}
1456
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001457static void *GetKeyForBase(QualType BaseType) {
1458 if (const RecordType *RT = BaseType->getAs<RecordType>())
1459 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001461 assert(0 && "Unexpected base type!");
1462 return 0;
1463}
1464
Mike Stump1eb44332009-09-09 15:08:12 +00001465static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001466 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001467 // For fields injected into the class via declaration of an anonymous union,
1468 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001469 if (Member->isMemberInitializer()) {
1470 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Eli Friedman49c16da2009-11-09 01:05:47 +00001472 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001473 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001474 // in AnonUnionMember field.
1475 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1476 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001477 if (Field->getDeclContext()->isRecord()) {
1478 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1479 if (RD->isAnonymousStructOrUnion())
1480 return static_cast<void *>(RD);
1481 }
1482 return static_cast<void *>(Field);
1483 }
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001485 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001486}
1487
John McCall6aee6212009-11-04 23:13:52 +00001488/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001489void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001490 SourceLocation ColonLoc,
1491 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001492 if (!ConstructorDecl)
1493 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001494
1495 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
1497 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001498 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Anders Carlssona7b35212009-03-25 02:58:17 +00001500 if (!Constructor) {
1501 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1502 return;
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001505 if (!Constructor->isDependentContext()) {
1506 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1507 bool err = false;
1508 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001509 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001510 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1511 void *KeyToMember = GetKeyForMember(Member);
1512 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1513 if (!PrevMember) {
1514 PrevMember = Member;
1515 continue;
1516 }
1517 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001518 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001519 diag::error_multiple_mem_initialization)
1520 << Field->getNameAsString();
1521 else {
1522 Type *BaseClass = Member->getBaseClass();
1523 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001524 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001525 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001526 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001527 }
1528 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1529 << 0;
1530 err = true;
1531 }
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001533 if (err)
1534 return;
1535 }
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Eli Friedman49c16da2009-11-09 01:05:47 +00001537 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001538 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001539 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001541 if (Constructor->isDependentContext())
1542 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001543
1544 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001545 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001546 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001547 Diagnostic::Ignored)
1548 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001550 // Also issue warning if order of ctor-initializer list does not match order
1551 // of 1) base class declarations and 2) order of non-static data members.
1552 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001554 CXXRecordDecl *ClassDecl
1555 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1556 // Push virtual bases before others.
1557 for (CXXRecordDecl::base_class_iterator VBase =
1558 ClassDecl->vbases_begin(),
1559 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001560 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001562 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1563 E = ClassDecl->bases_end(); Base != E; ++Base) {
1564 // Virtuals are alread in the virtual base list and are constructed
1565 // first.
1566 if (Base->isVirtual())
1567 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001568 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001571 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1572 E = ClassDecl->field_end(); Field != E; ++Field)
1573 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001575 int Last = AllBaseOrMembers.size();
1576 int curIndex = 0;
1577 CXXBaseOrMemberInitializer *PrevMember = 0;
1578 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001579 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001580 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1581 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001582
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001583 for (; curIndex < Last; curIndex++)
1584 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1585 break;
1586 if (curIndex == Last) {
1587 assert(PrevMember && "Member not in member list?!");
1588 // Initializer as specified in ctor-initializer list is out of order.
1589 // Issue a warning diagnostic.
1590 if (PrevMember->isBaseInitializer()) {
1591 // Diagnostics is for an initialized base class.
1592 Type *BaseClass = PrevMember->getBaseClass();
1593 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001594 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001595 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001596 } else {
1597 FieldDecl *Field = PrevMember->getMember();
1598 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001599 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001600 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001601 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001602 // Also the note!
1603 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001604 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001605 diag::note_fieldorbase_initialized_here) << 0
1606 << Field->getNameAsString();
1607 else {
1608 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001609 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001610 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001611 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001612 }
1613 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001614 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001615 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001616 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001617 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001618 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001619}
1620
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001621void
1622Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1623 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1624 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001626 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1627 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1628 if (VBase->getType()->isDependentType())
1629 continue;
1630 // Skip over virtual bases which have trivial destructors.
1631 CXXRecordDecl *BaseClassDecl
1632 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1633 if (BaseClassDecl->hasTrivialDestructor())
1634 continue;
1635 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001636 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001637 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001638
1639 uintptr_t Member =
1640 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001641 | CXXDestructorDecl::VBASE;
1642 AllToDestruct.push_back(Member);
1643 }
1644 for (CXXRecordDecl::base_class_iterator Base =
1645 ClassDecl->bases_begin(),
1646 E = ClassDecl->bases_end(); Base != E; ++Base) {
1647 if (Base->isVirtual())
1648 continue;
1649 if (Base->getType()->isDependentType())
1650 continue;
1651 // Skip over virtual bases which have trivial destructors.
1652 CXXRecordDecl *BaseClassDecl
1653 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1654 if (BaseClassDecl->hasTrivialDestructor())
1655 continue;
1656 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001657 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001658 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001659 uintptr_t Member =
1660 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001661 | CXXDestructorDecl::DRCTNONVBASE;
1662 AllToDestruct.push_back(Member);
1663 }
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001665 // non-static data members.
1666 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1667 E = ClassDecl->field_end(); Field != E; ++Field) {
1668 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001670 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1671 // Skip over virtual bases which have trivial destructors.
1672 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1673 if (FieldClassDecl->hasTrivialDestructor())
1674 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001675 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001676 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001677 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001678 const_cast<CXXDestructorDecl*>(Dtor));
1679 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1680 AllToDestruct.push_back(Member);
1681 }
1682 }
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001684 unsigned NumDestructions = AllToDestruct.size();
1685 if (NumDestructions > 0) {
1686 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001687 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001688 new (Context) uintptr_t [NumDestructions];
1689 // Insert in reverse order.
1690 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1691 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1692 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1693 }
1694}
1695
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001696void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001697 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001698 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001700 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
1702 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001703 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001704 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001705}
1706
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001707namespace {
1708 /// PureVirtualMethodCollector - traverses a class and its superclasses
1709 /// and determines if it has any pure virtual methods.
1710 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1711 ASTContext &Context;
1712
Sebastian Redldfe292d2009-03-22 21:28:55 +00001713 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001714 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001715
1716 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001717 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001719 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001721 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001722 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001723 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001725 MethodList List;
1726 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001728 // Copy the temporary list to methods, and make sure to ignore any
1729 // null entries.
1730 for (size_t i = 0, e = List.size(); i != e; ++i) {
1731 if (List[i])
1732 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001733 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001736 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001738 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1739 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001740 };
Mike Stump1eb44332009-09-09 15:08:12 +00001741
1742 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001743 MethodList& Methods) {
1744 // First, collect the pure virtual methods for the base classes.
1745 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1746 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001747 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001748 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001749 if (BaseDecl && BaseDecl->isAbstract())
1750 Collect(BaseDecl, Methods);
1751 }
1752 }
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001754 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001755 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001757 MethodSetTy OverriddenMethods;
1758 size_t MethodsSize = Methods.size();
1759
Mike Stump1eb44332009-09-09 15:08:12 +00001760 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001761 i != e; ++i) {
1762 // Traverse the record, looking for methods.
1763 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001764 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001765 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001766 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlsson27823022009-10-18 19:34:08 +00001768 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001769 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1770 E = MD->end_overridden_methods(); I != E; ++I) {
1771 // Keep track of the overridden methods.
1772 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001773 }
1774 }
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
1777 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001778 // overridden.
1779 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1780 if (OverriddenMethods.count(Methods[i]))
1781 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001782 }
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001784 }
1785}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001786
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001787
Mike Stump1eb44332009-09-09 15:08:12 +00001788bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001789 unsigned DiagID, AbstractDiagSelID SelID,
1790 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001791 if (SelID == -1)
1792 return RequireNonAbstractType(Loc, T,
1793 PDiag(DiagID), CurrentRD);
1794 else
1795 return RequireNonAbstractType(Loc, T,
1796 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001797}
1798
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001799bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1800 const PartialDiagnostic &PD,
1801 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001802 if (!getLangOptions().CPlusPlus)
1803 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Anders Carlsson11f21a02009-03-23 19:10:31 +00001805 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001806 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001807 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Ted Kremenek6217b802009-07-29 21:53:49 +00001809 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001810 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001811 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001812 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001814 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001815 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001816 }
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Ted Kremenek6217b802009-07-29 21:53:49 +00001818 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001819 if (!RT)
1820 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001822 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1823 if (!RD)
1824 return false;
1825
Anders Carlssone65a3c82009-03-24 17:23:42 +00001826 if (CurrentRD && CurrentRD != RD)
1827 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001829 if (!RD->isAbstract())
1830 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001832 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001834 // Check if we've already emitted the list of pure virtual functions for this
1835 // class.
1836 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1837 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001839 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001840
1841 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001842 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1843 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
1845 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001846 MD->getDeclName();
1847 }
1848
1849 if (!PureVirtualClassDiagSet)
1850 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1851 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001853 return true;
1854}
1855
Anders Carlsson8211eff2009-03-24 01:19:16 +00001856namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001857 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001858 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1859 Sema &SemaRef;
1860 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Anders Carlssone65a3c82009-03-24 17:23:42 +00001862 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001863 bool Invalid = false;
1864
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001865 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1866 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001867 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001868
Anders Carlsson8211eff2009-03-24 01:19:16 +00001869 return Invalid;
1870 }
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Anders Carlssone65a3c82009-03-24 17:23:42 +00001872 public:
1873 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1874 : SemaRef(SemaRef), AbstractClass(ac) {
1875 Visit(SemaRef.Context.getTranslationUnitDecl());
1876 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001877
Anders Carlssone65a3c82009-03-24 17:23:42 +00001878 bool VisitFunctionDecl(const FunctionDecl *FD) {
1879 if (FD->isThisDeclarationADefinition()) {
1880 // No need to do the check if we're in a definition, because it requires
1881 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001882 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001883 return VisitDeclContext(FD);
1884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Anders Carlssone65a3c82009-03-24 17:23:42 +00001886 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001887 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001888 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001889 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1890 diag::err_abstract_type_in_decl,
1891 Sema::AbstractReturnType,
1892 AbstractClass);
1893
Mike Stump1eb44332009-09-09 15:08:12 +00001894 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001895 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001896 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001897 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001898 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001899 VD->getOriginalType(),
1900 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001901 Sema::AbstractParamType,
1902 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001903 }
1904
1905 return Invalid;
1906 }
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Anders Carlssone65a3c82009-03-24 17:23:42 +00001908 bool VisitDecl(const Decl* D) {
1909 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1910 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Anders Carlssone65a3c82009-03-24 17:23:42 +00001912 return false;
1913 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001914 };
1915}
1916
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001917void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001918 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001919 SourceLocation LBrac,
1920 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001921 if (!TagDecl)
1922 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Douglas Gregor42af25f2009-05-11 19:58:34 +00001924 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001925 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001926 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001927 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001928
Chris Lattnerb28317a2009-03-28 19:18:32 +00001929 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001930 if (!RD->isAbstract()) {
1931 // Collect all the pure virtual methods and see if this is an abstract
1932 // class after all.
1933 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001934 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001935 RD->setAbstract(true);
1936 }
Mike Stump1eb44332009-09-09 15:08:12 +00001937
1938 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001939 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Douglas Gregor663b5a02009-10-14 20:14:33 +00001941 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001942 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001943}
1944
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001945/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1946/// special functions, such as the default constructor, copy
1947/// constructor, or destructor, to the given C++ class (C++
1948/// [special]p1). This routine can only be executed just before the
1949/// definition of the class is complete.
1950void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001951 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001952 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001953
Sebastian Redl465226e2009-05-27 22:11:52 +00001954 // FIXME: Implicit declarations have exception specifications, which are
1955 // the union of the specifications of the implicitly called functions.
1956
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001957 if (!ClassDecl->hasUserDeclaredConstructor()) {
1958 // C++ [class.ctor]p5:
1959 // A default constructor for a class X is a constructor of class X
1960 // that can be called without an argument. If there is no
1961 // user-declared constructor for class X, a default constructor is
1962 // implicitly declared. An implicitly-declared default constructor
1963 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001964 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001965 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001966 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001967 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001968 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001969 Context.getFunctionType(Context.VoidTy,
1970 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001971 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001972 /*isExplicit=*/false,
1973 /*isInline=*/true,
1974 /*isImplicitlyDeclared=*/true);
1975 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001976 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001977 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001978 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001979 }
1980
1981 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1982 // C++ [class.copy]p4:
1983 // If the class definition does not explicitly declare a copy
1984 // constructor, one is declared implicitly.
1985
1986 // C++ [class.copy]p5:
1987 // The implicitly-declared copy constructor for a class X will
1988 // have the form
1989 //
1990 // X::X(const X&)
1991 //
1992 // if
1993 bool HasConstCopyConstructor = true;
1994
1995 // -- each direct or virtual base class B of X has a copy
1996 // constructor whose first parameter is of type const B& or
1997 // const volatile B&, and
1998 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1999 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2000 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002001 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002002 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002003 = BaseClassDecl->hasConstCopyConstructor(Context);
2004 }
2005
2006 // -- for all the nonstatic data members of X that are of a
2007 // class type M (or array thereof), each such class type
2008 // has a copy constructor whose first parameter is of type
2009 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002010 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2011 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002012 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002013 QualType FieldType = (*Field)->getType();
2014 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2015 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002016 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002017 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002018 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002019 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002020 = FieldClassDecl->hasConstCopyConstructor(Context);
2021 }
2022 }
2023
Sebastian Redl64b45f72009-01-05 20:52:13 +00002024 // Otherwise, the implicitly declared copy constructor will have
2025 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002026 //
2027 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002028 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002029 if (HasConstCopyConstructor)
2030 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002031 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002032
Sebastian Redl64b45f72009-01-05 20:52:13 +00002033 // An implicitly-declared copy constructor is an inline public
2034 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002035 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002036 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002037 CXXConstructorDecl *CopyConstructor
2038 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002039 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002040 Context.getFunctionType(Context.VoidTy,
2041 &ArgType, 1,
2042 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002043 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002044 /*isExplicit=*/false,
2045 /*isInline=*/true,
2046 /*isImplicitlyDeclared=*/true);
2047 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002048 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002049 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002050
2051 // Add the parameter to the constructor.
2052 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2053 ClassDecl->getLocation(),
2054 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002055 ArgType, /*DInfo=*/0,
2056 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002057 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002058 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002059 }
2060
Sebastian Redl64b45f72009-01-05 20:52:13 +00002061 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2062 // Note: The following rules are largely analoguous to the copy
2063 // constructor rules. Note that virtual bases are not taken into account
2064 // for determining the argument type of the operator. Note also that
2065 // operators taking an object instead of a reference are allowed.
2066 //
2067 // C++ [class.copy]p10:
2068 // If the class definition does not explicitly declare a copy
2069 // assignment operator, one is declared implicitly.
2070 // The implicitly-defined copy assignment operator for a class X
2071 // will have the form
2072 //
2073 // X& X::operator=(const X&)
2074 //
2075 // if
2076 bool HasConstCopyAssignment = true;
2077
2078 // -- each direct base class B of X has a copy assignment operator
2079 // whose parameter is of type const B&, const volatile B& or B,
2080 // and
2081 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2082 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002083 assert(!Base->getType()->isDependentType() &&
2084 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002085 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002086 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002087 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002088 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002089 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002090 }
2091
2092 // -- for all the nonstatic data members of X that are of a class
2093 // type M (or array thereof), each such class type has a copy
2094 // assignment operator whose parameter is of type const M&,
2095 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002096 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2097 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002098 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002099 QualType FieldType = (*Field)->getType();
2100 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2101 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002102 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002103 const CXXRecordDecl *FieldClassDecl
2104 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002105 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002106 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002107 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002108 }
2109 }
2110
2111 // Otherwise, the implicitly declared copy assignment operator will
2112 // have the form
2113 //
2114 // X& X::operator=(X&)
2115 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002116 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002117 if (HasConstCopyAssignment)
2118 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002119 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002120
2121 // An implicitly-declared copy assignment operator is an inline public
2122 // member of its class.
2123 DeclarationName Name =
2124 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2125 CXXMethodDecl *CopyAssignment =
2126 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2127 Context.getFunctionType(RetType, &ArgType, 1,
2128 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002129 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002130 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002131 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002132 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002133 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002134
2135 // Add the parameter to the operator.
2136 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2137 ClassDecl->getLocation(),
2138 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002139 ArgType, /*DInfo=*/0,
2140 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002141 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002142
2143 // Don't call addedAssignmentOperator. There is no way to distinguish an
2144 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002145 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002146 }
2147
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002148 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002149 // C++ [class.dtor]p2:
2150 // If a class has no user-declared destructor, a destructor is
2151 // declared implicitly. An implicitly-declared destructor is an
2152 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002153 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002154 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002155 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002156 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002157 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002158 Context.getFunctionType(Context.VoidTy,
2159 0, 0, false, 0),
2160 /*isInline=*/true,
2161 /*isImplicitlyDeclared=*/true);
2162 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002163 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002164 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002165 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002166 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002167}
2168
Douglas Gregor6569d682009-05-27 23:11:45 +00002169void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002170 Decl *D = TemplateD.getAs<Decl>();
2171 if (!D)
2172 return;
2173
2174 TemplateParameterList *Params = 0;
2175 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2176 Params = Template->getTemplateParameters();
2177 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2178 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2179 Params = PartialSpec->getTemplateParameters();
2180 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002181 return;
2182
Douglas Gregor6569d682009-05-27 23:11:45 +00002183 for (TemplateParameterList::iterator Param = Params->begin(),
2184 ParamEnd = Params->end();
2185 Param != ParamEnd; ++Param) {
2186 NamedDecl *Named = cast<NamedDecl>(*Param);
2187 if (Named->getDeclName()) {
2188 S->AddDecl(DeclPtrTy::make(Named));
2189 IdResolver.AddDecl(Named);
2190 }
2191 }
2192}
2193
Douglas Gregor72b505b2008-12-16 21:30:33 +00002194/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2195/// parsing a top-level (non-nested) C++ class, and we are now
2196/// parsing those parts of the given Method declaration that could
2197/// not be parsed earlier (C++ [class.mem]p2), such as default
2198/// arguments. This action should enter the scope of the given
2199/// Method declaration as if we had just parsed the qualified method
2200/// name. However, it should not bring the parameters into scope;
2201/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002202void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002203 if (!MethodD)
2204 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002206 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Douglas Gregor72b505b2008-12-16 21:30:33 +00002208 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002209 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002210 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002211 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2212 SS.setScopeRep(
2213 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002214 ActOnCXXEnterDeclaratorScope(S, SS);
2215}
2216
2217/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2218/// C++ method declaration. We're (re-)introducing the given
2219/// function parameter into scope for use in parsing later parts of
2220/// the method declaration. For example, we could see an
2221/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002222void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002223 if (!ParamD)
2224 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Chris Lattnerb28317a2009-03-28 19:18:32 +00002226 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002227
2228 // If this parameter has an unparsed default argument, clear it out
2229 // to make way for the parsed default argument.
2230 if (Param->hasUnparsedDefaultArg())
2231 Param->setDefaultArg(0);
2232
Chris Lattnerb28317a2009-03-28 19:18:32 +00002233 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002234 if (Param->getDeclName())
2235 IdResolver.AddDecl(Param);
2236}
2237
2238/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2239/// processing the delayed method declaration for Method. The method
2240/// declaration is now considered finished. There may be a separate
2241/// ActOnStartOfFunctionDef action later (not necessarily
2242/// immediately!) for this method, if it was also defined inside the
2243/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002244void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002245 if (!MethodD)
2246 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002248 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Chris Lattnerb28317a2009-03-28 19:18:32 +00002250 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002251 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002252 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002253 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2254 SS.setScopeRep(
2255 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002256 ActOnCXXExitDeclaratorScope(S, SS);
2257
2258 // Now that we have our default arguments, check the constructor
2259 // again. It could produce additional diagnostics or affect whether
2260 // the class has implicitly-declared destructors, among other
2261 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002262 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2263 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002264
2265 // Check the default arguments, which we may have added.
2266 if (!Method->isInvalidDecl())
2267 CheckCXXDefaultArguments(Method);
2268}
2269
Douglas Gregor42a552f2008-11-05 20:51:48 +00002270/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002271/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002272/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002273/// emit diagnostics and set the invalid bit to true. In any case, the type
2274/// will be updated to reflect a well-formed type for the constructor and
2275/// returned.
2276QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2277 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002278 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002279
2280 // C++ [class.ctor]p3:
2281 // A constructor shall not be virtual (10.3) or static (9.4). A
2282 // constructor can be invoked for a const, volatile or const
2283 // volatile object. A constructor shall not be declared const,
2284 // volatile, or const volatile (9.3.2).
2285 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002286 if (!D.isInvalidType())
2287 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2288 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2289 << SourceRange(D.getIdentifierLoc());
2290 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002291 }
2292 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002293 if (!D.isInvalidType())
2294 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2295 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2296 << SourceRange(D.getIdentifierLoc());
2297 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002298 SC = FunctionDecl::None;
2299 }
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattner65401802009-04-25 08:28:21 +00002301 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2302 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002303 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002304 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2305 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002306 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002307 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2308 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002309 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002310 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2311 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002312 }
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Douglas Gregor42a552f2008-11-05 20:51:48 +00002314 // Rebuild the function type "R" without any type qualifiers (in
2315 // case any of the errors above fired) and with "void" as the
2316 // return type, since constructors don't have return types. We
2317 // *always* have to do this, because GetTypeForDeclarator will
2318 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002319 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002320 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2321 Proto->getNumArgs(),
2322 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002323}
2324
Douglas Gregor72b505b2008-12-16 21:30:33 +00002325/// CheckConstructor - Checks a fully-formed constructor for
2326/// well-formedness, issuing any diagnostics required. Returns true if
2327/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002328void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002329 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002330 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2331 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002332 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002333
2334 // C++ [class.copy]p3:
2335 // A declaration of a constructor for a class X is ill-formed if
2336 // its first parameter is of type (optionally cv-qualified) X and
2337 // either there are no other parameters or else all other
2338 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002339 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002340 ((Constructor->getNumParams() == 1) ||
2341 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002342 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002343 QualType ParamType = Constructor->getParamDecl(0)->getType();
2344 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2345 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002346 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2347 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002348 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002349 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002350 }
2351 }
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Douglas Gregor72b505b2008-12-16 21:30:33 +00002353 // Notify the class that we've added a constructor.
2354 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002355}
2356
Mike Stump1eb44332009-09-09 15:08:12 +00002357static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002358FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2359 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2360 FTI.ArgInfo[0].Param &&
2361 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2362}
2363
Douglas Gregor42a552f2008-11-05 20:51:48 +00002364/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2365/// the well-formednes of the destructor declarator @p D with type @p
2366/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002367/// emit diagnostics and set the declarator to invalid. Even if this happens,
2368/// will be updated to reflect a well-formed type for the destructor and
2369/// returned.
2370QualType Sema::CheckDestructorDeclarator(Declarator &D,
2371 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002372 // C++ [class.dtor]p1:
2373 // [...] A typedef-name that names a class is a class-name
2374 // (7.1.3); however, a typedef-name that names a class shall not
2375 // be used as the identifier in the declarator for a destructor
2376 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002377 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002378 if (isa<TypedefType>(DeclaratorType)) {
2379 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002380 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002381 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002382 }
2383
2384 // C++ [class.dtor]p2:
2385 // A destructor is used to destroy objects of its class type. A
2386 // destructor takes no parameters, and no return type can be
2387 // specified for it (not even void). The address of a destructor
2388 // shall not be taken. A destructor shall not be static. A
2389 // destructor can be invoked for a const, volatile or const
2390 // volatile object. A destructor shall not be declared const,
2391 // volatile or const volatile (9.3.2).
2392 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002393 if (!D.isInvalidType())
2394 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2395 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2396 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002397 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002398 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002399 }
Chris Lattner65401802009-04-25 08:28:21 +00002400 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002401 // Destructors don't have return types, but the parser will
2402 // happily parse something like:
2403 //
2404 // class X {
2405 // float ~X();
2406 // };
2407 //
2408 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002409 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2410 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2411 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002412 }
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Chris Lattner65401802009-04-25 08:28:21 +00002414 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2415 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002416 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002417 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2418 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002419 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002420 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2421 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002422 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002423 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2424 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002425 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002426 }
2427
2428 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002429 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002430 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2431
2432 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002433 FTI.freeArgs();
2434 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002435 }
2436
Mike Stump1eb44332009-09-09 15:08:12 +00002437 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002438 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002439 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002440 D.setInvalidType();
2441 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002442
2443 // Rebuild the function type "R" without any type qualifiers or
2444 // parameters (in case any of the errors above fired) and with
2445 // "void" as the return type, since destructors don't have return
2446 // types. We *always* have to do this, because GetTypeForDeclarator
2447 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002448 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002449}
2450
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002451/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2452/// well-formednes of the conversion function declarator @p D with
2453/// type @p R. If there are any errors in the declarator, this routine
2454/// will emit diagnostics and return true. Otherwise, it will return
2455/// false. Either way, the type @p R will be updated to reflect a
2456/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002457void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002458 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002459 // C++ [class.conv.fct]p1:
2460 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002461 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002462 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002463 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002464 if (!D.isInvalidType())
2465 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2466 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2467 << SourceRange(D.getIdentifierLoc());
2468 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002469 SC = FunctionDecl::None;
2470 }
Chris Lattner6e475012009-04-25 08:35:12 +00002471 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002472 // Conversion functions don't have return types, but the parser will
2473 // happily parse something like:
2474 //
2475 // class X {
2476 // float operator bool();
2477 // };
2478 //
2479 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002480 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2481 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2482 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002483 }
2484
2485 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002486 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002487 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2488
2489 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002490 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002491 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002492 }
2493
Mike Stump1eb44332009-09-09 15:08:12 +00002494 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002495 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002496 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002497 D.setInvalidType();
2498 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002499
2500 // C++ [class.conv.fct]p4:
2501 // The conversion-type-id shall not represent a function type nor
2502 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002503 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002504 if (ConvType->isArrayType()) {
2505 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2506 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002507 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002508 } else if (ConvType->isFunctionType()) {
2509 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2510 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002511 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002512 }
2513
2514 // Rebuild the function type "R" without any parameters (in case any
2515 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002516 // return type.
2517 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002518 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002519
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002520 // C++0x explicit conversion operators.
2521 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002522 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002523 diag::warn_explicit_conversion_functions)
2524 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002525}
2526
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002527/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2528/// the declaration of the given C++ conversion function. This routine
2529/// is responsible for recording the conversion function in the C++
2530/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002531Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002532 assert(Conversion && "Expected to receive a conversion function declaration");
2533
Douglas Gregor9d350972008-12-12 08:25:50 +00002534 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002535
2536 // Make sure we aren't redeclaring the conversion function.
2537 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002538
2539 // C++ [class.conv.fct]p1:
2540 // [...] A conversion function is never used to convert a
2541 // (possibly cv-qualified) object to the (possibly cv-qualified)
2542 // same object type (or a reference to it), to a (possibly
2543 // cv-qualified) base class of that type (or a reference to it),
2544 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002545 // FIXME: Suppress this warning if the conversion function ends up being a
2546 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002547 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002548 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002549 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002550 ConvType = ConvTypeRef->getPointeeType();
2551 if (ConvType->isRecordType()) {
2552 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2553 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002554 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002555 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002556 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002557 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002558 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002559 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002560 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002561 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002562 }
2563
Douglas Gregor70316a02008-12-26 15:00:45 +00002564 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002565 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002566 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002567 = Conversion->getDescribedFunctionTemplate())
2568 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002569 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002570 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002571 Conv = Conversions->function_begin(),
2572 ConvEnd = Conversions->function_end();
2573 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002574 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002575 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002576 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002577 }
2578 }
2579 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002580 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002581 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002582 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002583 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002584 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002585
Chris Lattnerb28317a2009-03-28 19:18:32 +00002586 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002587}
2588
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002589//===----------------------------------------------------------------------===//
2590// Namespace Handling
2591//===----------------------------------------------------------------------===//
2592
2593/// ActOnStartNamespaceDef - This is called at the start of a namespace
2594/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002595Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2596 SourceLocation IdentLoc,
2597 IdentifierInfo *II,
2598 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002599 NamespaceDecl *Namespc =
2600 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2601 Namespc->setLBracLoc(LBrace);
2602
2603 Scope *DeclRegionScope = NamespcScope->getParent();
2604
2605 if (II) {
2606 // C++ [namespace.def]p2:
2607 // The identifier in an original-namespace-definition shall not have been
2608 // previously defined in the declarative region in which the
2609 // original-namespace-definition appears. The identifier in an
2610 // original-namespace-definition is the name of the namespace. Subsequently
2611 // in that declarative region, it is treated as an original-namespace-name.
2612
John McCallf36e02d2009-10-09 21:13:30 +00002613 NamedDecl *PrevDecl
2614 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Douglas Gregor44b43212008-12-11 16:49:14 +00002616 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2617 // This is an extended namespace definition.
2618 // Attach this namespace decl to the chain of extended namespace
2619 // definitions.
2620 OrigNS->setNextNamespace(Namespc);
2621 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002622
Mike Stump1eb44332009-09-09 15:08:12 +00002623 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002624 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002625 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002626 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002627 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002628 } else if (PrevDecl) {
2629 // This is an invalid name redefinition.
2630 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2631 << Namespc->getDeclName();
2632 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2633 Namespc->setInvalidDecl();
2634 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002635 } else if (II->isStr("std") &&
2636 CurContext->getLookupContext()->isTranslationUnit()) {
2637 // This is the first "real" definition of the namespace "std", so update
2638 // our cache of the "std" namespace to point at this definition.
2639 if (StdNamespace) {
2640 // We had already defined a dummy namespace "std". Link this new
2641 // namespace definition to the dummy namespace "std".
2642 StdNamespace->setNextNamespace(Namespc);
2643 StdNamespace->setLocation(IdentLoc);
2644 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2645 }
2646
2647 // Make our StdNamespace cache point at the first real definition of the
2648 // "std" namespace.
2649 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002650 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002651
2652 PushOnScopeChains(Namespc, DeclRegionScope);
2653 } else {
John McCall9aeed322009-10-01 00:25:31 +00002654 // Anonymous namespaces.
2655
2656 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2657 // behaves as if it were replaced by
2658 // namespace unique { /* empty body */ }
2659 // using namespace unique;
2660 // namespace unique { namespace-body }
2661 // where all occurrences of 'unique' in a translation unit are
2662 // replaced by the same identifier and this identifier differs
2663 // from all other identifiers in the entire program.
2664
2665 // We just create the namespace with an empty name and then add an
2666 // implicit using declaration, just like the standard suggests.
2667 //
2668 // CodeGen enforces the "universally unique" aspect by giving all
2669 // declarations semantically contained within an anonymous
2670 // namespace internal linkage.
2671
2672 assert(Namespc->isAnonymousNamespace());
2673 CurContext->addDecl(Namespc);
2674
2675 UsingDirectiveDecl* UD
2676 = UsingDirectiveDecl::Create(Context, CurContext,
2677 /* 'using' */ LBrace,
2678 /* 'namespace' */ SourceLocation(),
2679 /* qualifier */ SourceRange(),
2680 /* NNS */ NULL,
2681 /* identifier */ SourceLocation(),
2682 Namespc,
2683 /* Ancestor */ CurContext);
2684 UD->setImplicit();
2685 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002686 }
2687
2688 // Although we could have an invalid decl (i.e. the namespace name is a
2689 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002690 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2691 // for the namespace has the declarations that showed up in that particular
2692 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002693 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002694 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002695}
2696
2697/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2698/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002699void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2700 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002701 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2702 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2703 Namespc->setRBracLoc(RBrace);
2704 PopDeclContext();
2705}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002706
Chris Lattnerb28317a2009-03-28 19:18:32 +00002707Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2708 SourceLocation UsingLoc,
2709 SourceLocation NamespcLoc,
2710 const CXXScopeSpec &SS,
2711 SourceLocation IdentLoc,
2712 IdentifierInfo *NamespcName,
2713 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002714 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2715 assert(NamespcName && "Invalid NamespcName.");
2716 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002717 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002718
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002719 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002720
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002721 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002722 LookupResult R;
2723 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002724 if (R.isAmbiguous()) {
2725 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002726 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002727 }
John McCallf36e02d2009-10-09 21:13:30 +00002728 if (!R.empty()) {
2729 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002730 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002731 // C++ [namespace.udir]p1:
2732 // A using-directive specifies that the names in the nominated
2733 // namespace can be used in the scope in which the
2734 // using-directive appears after the using-directive. During
2735 // unqualified name lookup (3.4.1), the names appear as if they
2736 // were declared in the nearest enclosing namespace which
2737 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002738 // namespace. [Note: in this context, "contains" means "contains
2739 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002740
2741 // Find enclosing context containing both using-directive and
2742 // nominated namespace.
2743 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2744 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2745 CommonAncestor = CommonAncestor->getParent();
2746
Mike Stump1eb44332009-09-09 15:08:12 +00002747 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002748 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002749 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002750 SS.getRange(),
2751 (NestedNameSpecifier *)SS.getScopeRep(),
2752 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002753 cast<NamespaceDecl>(NS),
2754 CommonAncestor);
2755 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002756 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002757 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002758 }
2759
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002760 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002761 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002762 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002763}
2764
2765void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2766 // If scope has associated entity, then using directive is at namespace
2767 // or translation unit scope. We add UsingDirectiveDecls, into
2768 // it's lookup structure.
2769 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002770 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002771 else
2772 // Otherwise it is block-sope. using-directives will affect lookup
2773 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002774 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002775}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002776
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002777
2778Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002779 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002780 SourceLocation UsingLoc,
2781 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002782 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002783 AttributeList *AttrList,
2784 bool IsTypeName) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002785 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002786
Douglas Gregor12c118a2009-11-04 16:30:06 +00002787 switch (Name.getKind()) {
2788 case UnqualifiedId::IK_Identifier:
2789 case UnqualifiedId::IK_OperatorFunctionId:
2790 case UnqualifiedId::IK_ConversionFunctionId:
2791 break;
2792
2793 case UnqualifiedId::IK_ConstructorName:
2794 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2795 << SS.getRange();
2796 return DeclPtrTy();
2797
2798 case UnqualifiedId::IK_DestructorName:
2799 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2800 << SS.getRange();
2801 return DeclPtrTy();
2802
2803 case UnqualifiedId::IK_TemplateId:
2804 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2805 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2806 return DeclPtrTy();
2807 }
2808
2809 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2810 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2811 Name.getSourceRange().getBegin(),
2812 TargetName, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002813 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002814 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002815 UD->setAccess(AS);
2816 }
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Anders Carlssonc72160b2009-08-28 05:40:36 +00002818 return DeclPtrTy::make(UD);
2819}
2820
2821NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2822 const CXXScopeSpec &SS,
2823 SourceLocation IdentLoc,
2824 DeclarationName Name,
2825 AttributeList *AttrList,
2826 bool IsTypeName) {
2827 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2828 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002829
Anders Carlsson550b14b2009-08-28 05:49:21 +00002830 // FIXME: We ignore attributes for now.
2831 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002833 if (SS.isEmpty()) {
2834 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002835 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002836 }
Mike Stump1eb44332009-09-09 15:08:12 +00002837
2838 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002839 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2840
Anders Carlsson550b14b2009-08-28 05:49:21 +00002841 if (isUnknownSpecialization(SS)) {
2842 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2843 SS.getRange(), NNS,
2844 IdentLoc, Name, IsTypeName);
2845 }
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002847 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002849 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2850 // C++0x N2914 [namespace.udecl]p3:
2851 // A using-declaration used as a member-declaration shall refer to a member
2852 // of a base class of the class being defined, shall refer to a member of an
2853 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002854 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002855 // a member of a base class of the class being defined.
2856 const Type *Ty = NNS->getAsType();
2857 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2858 Diag(SS.getRange().getBegin(),
2859 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2860 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002861 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002862 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002863
2864 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2865 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002866 } else {
2867 // C++0x N2914 [namespace.udecl]p8:
2868 // A using-declaration for a class member shall be a member-declaration.
2869 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002870 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002871 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002872 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002875 // C++0x N2914 [namespace.udecl]p9:
2876 // In a using-declaration, a prefix :: refers to the global namespace.
2877 if (NNS->getKind() == NestedNameSpecifier::Global)
2878 LookupContext = Context.getTranslationUnitDecl();
2879 else
2880 LookupContext = NNS->getAsNamespace();
2881 }
2882
2883
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002884 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002885 LookupResult R;
2886 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002887
John McCallf36e02d2009-10-09 21:13:30 +00002888 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002889 Diag(IdentLoc, diag::err_no_member)
2890 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002891 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002892 }
2893
John McCallf36e02d2009-10-09 21:13:30 +00002894 // FIXME: handle ambiguity?
2895 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002897 if (IsTypeName && !isa<TypeDecl>(ND)) {
2898 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002899 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002900 }
2901
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002902 // C++0x N2914 [namespace.udecl]p6:
2903 // A using-declaration shall not name a namespace.
2904 if (isa<NamespaceDecl>(ND)) {
2905 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2906 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002907 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002908 }
Mike Stump1eb44332009-09-09 15:08:12 +00002909
Anders Carlssonc72160b2009-08-28 05:40:36 +00002910 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2911 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002912}
2913
Anders Carlsson81c85c42009-03-28 23:53:49 +00002914/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2915/// is a namespace alias, returns the namespace it points to.
2916static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2917 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2918 return AD->getNamespace();
2919 return dyn_cast_or_null<NamespaceDecl>(D);
2920}
2921
Mike Stump1eb44332009-09-09 15:08:12 +00002922Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002923 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002924 SourceLocation AliasLoc,
2925 IdentifierInfo *Alias,
2926 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002927 SourceLocation IdentLoc,
2928 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Anders Carlsson81c85c42009-03-28 23:53:49 +00002930 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002931 LookupResult R;
2932 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002933
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002934 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002935 if (NamedDecl *PrevDecl
2936 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002937 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002938 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002939 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002940 if (!R.isAmbiguous() && !R.empty() &&
2941 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002942 return DeclPtrTy();
2943 }
Mike Stump1eb44332009-09-09 15:08:12 +00002944
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002945 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2946 diag::err_redefinition_different_kind;
2947 Diag(AliasLoc, DiagID) << Alias;
2948 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002949 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002950 }
2951
Anders Carlsson5721c682009-03-28 06:42:02 +00002952 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002953 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002954 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002955 }
Mike Stump1eb44332009-09-09 15:08:12 +00002956
John McCallf36e02d2009-10-09 21:13:30 +00002957 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002958 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002959 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002960 }
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002962 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002963 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2964 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002965 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002966 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002968 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002969 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002970}
2971
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002972void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2973 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002974 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2975 !Constructor->isUsed()) &&
2976 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Eli Friedman80c30da2009-11-09 19:20:36 +00002978 CXXRecordDecl *ClassDecl
2979 = cast<CXXRecordDecl>(Constructor->getDeclContext());
2980 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00002981
Eli Friedman80c30da2009-11-09 19:20:36 +00002982 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
2983 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
2984 << Context.getTagDeclType(ClassDecl);
2985 Constructor->setInvalidDecl();
2986 } else {
2987 Constructor->setUsed();
2988 }
Eli Friedman49c16da2009-11-09 01:05:47 +00002989 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002990}
2991
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002992void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002993 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002994 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2995 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002997 CXXRecordDecl *ClassDecl
2998 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2999 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3000 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003001 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003002 // implicitly defined, all the implicitly-declared default destructors
3003 // for its base class and its non-static data members shall have been
3004 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003005 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3006 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003007 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003008 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003009 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003010 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003011 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3012 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3013 else
Mike Stump1eb44332009-09-09 15:08:12 +00003014 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003015 "DefineImplicitDestructor - missing dtor in a base class");
3016 }
3017 }
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003019 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3020 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003021 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3022 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3023 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003024 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003025 CXXRecordDecl *FieldClassDecl
3026 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3027 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003028 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003029 const_cast<CXXDestructorDecl*>(
3030 FieldClassDecl->getDestructor(Context)))
3031 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3032 else
Mike Stump1eb44332009-09-09 15:08:12 +00003033 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003034 "DefineImplicitDestructor - missing dtor in class of a data member");
3035 }
3036 }
3037 }
3038 Destructor->setUsed();
3039}
3040
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003041void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3042 CXXMethodDecl *MethodDecl) {
3043 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3044 MethodDecl->getOverloadedOperator() == OO_Equal &&
3045 !MethodDecl->isUsed()) &&
3046 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003048 CXXRecordDecl *ClassDecl
3049 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003051 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003052 // Before the implicitly-declared copy assignment operator for a class is
3053 // implicitly defined, all implicitly-declared copy assignment operators
3054 // for its direct base classes and its nonstatic data members shall have
3055 // been implicitly defined.
3056 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003057 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3058 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003059 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003060 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003061 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003062 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3063 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3064 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003065 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3066 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003067 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3068 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3069 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003070 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003071 CXXRecordDecl *FieldClassDecl
3072 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003073 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003074 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3075 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003076 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003077 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003078 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3079 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003080 Diag(CurrentLocation, diag::note_first_required_here);
3081 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003082 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003083 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003084 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3085 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003086 Diag(CurrentLocation, diag::note_first_required_here);
3087 err = true;
3088 }
3089 }
3090 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003091 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003092}
3093
3094CXXMethodDecl *
3095Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3096 CXXRecordDecl *ClassDecl) {
3097 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3098 QualType RHSType(LHSType);
3099 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003100 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003101 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003102 RHSType = Context.getCVRQualifiedType(RHSType,
3103 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003104 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3105 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003106 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003107 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3108 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003109 SourceLocation()));
3110 Expr *Args[2] = { &*LHS, &*RHS };
3111 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003112 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003113 CandidateSet);
3114 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003115 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003116 ClassDecl->getLocation(), Best) == OR_Success)
3117 return cast<CXXMethodDecl>(Best->Function);
3118 assert(false &&
3119 "getAssignOperatorMethod - copy assignment operator method not found");
3120 return 0;
3121}
3122
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003123void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3124 CXXConstructorDecl *CopyConstructor,
3125 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003126 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003127 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3128 !CopyConstructor->isUsed()) &&
3129 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003131 CXXRecordDecl *ClassDecl
3132 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3133 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003134 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003135 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003136 // implicitly defined, all the implicitly-declared copy constructors
3137 // for its base class and its non-static data members shall have been
3138 // implicitly defined.
3139 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3140 Base != ClassDecl->bases_end(); ++Base) {
3141 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003142 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003143 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003144 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003145 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003146 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003147 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3148 FieldEnd = ClassDecl->field_end();
3149 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003150 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3151 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3152 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003153 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003154 CXXRecordDecl *FieldClassDecl
3155 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003156 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003157 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003158 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003159 }
3160 }
3161 CopyConstructor->setUsed();
3162}
3163
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003164Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003165Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003166 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003167 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003168 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Douglas Gregor39da0b82009-09-09 23:08:42 +00003170 // C++ [class.copy]p15:
3171 // Whenever a temporary class object is copied using a copy constructor, and
3172 // this object and the copy have the same cv-unqualified type, an
3173 // implementation is permitted to treat the original and the copy as two
3174 // different ways of referring to the same object and not perform a copy at
3175 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003177 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003178 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003179 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003180 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3181 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003182 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3183 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3184 E = ICE->getSubExpr();
3185
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003186 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3187 Elidable = true;
3188 }
Mike Stump1eb44332009-09-09 15:08:12 +00003189
3190 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003191 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003192}
3193
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003194/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3195/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003196Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003197Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3198 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003199 MultiExprArg ExprArgs) {
3200 unsigned NumExprs = ExprArgs.size();
3201 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Douglas Gregor39da0b82009-09-09 23:08:42 +00003203 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3204 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003205}
3206
Anders Carlssone7624a72009-08-27 05:08:22 +00003207Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003208Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3209 QualType Ty,
3210 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003211 MultiExprArg Args,
3212 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003213 unsigned NumExprs = Args.size();
3214 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Douglas Gregor39da0b82009-09-09 23:08:42 +00003216 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3217 TyBeginLoc, Exprs,
3218 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003219}
3220
3221
Mike Stump1eb44332009-09-09 15:08:12 +00003222bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003223 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003224 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003225 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003226 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003227 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003228 if (TempResult.isInvalid())
3229 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003231 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003232 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003233 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003234 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Anders Carlssonfe2de492009-08-25 05:18:00 +00003236 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003237}
3238
Mike Stump1eb44332009-09-09 15:08:12 +00003239void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003240 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003241 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003242 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003243 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003244 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003245 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003246}
3247
Mike Stump1eb44332009-09-09 15:08:12 +00003248/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003249/// ActOnDeclarator, when a C++ direct initializer is present.
3250/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003251void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3252 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003253 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003254 SourceLocation *CommaLocs,
3255 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003256 unsigned NumExprs = Exprs.size();
3257 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003258 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003259
3260 // If there is no declaration, there was an error parsing it. Just ignore
3261 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003262 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003265 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3266 if (!VDecl) {
3267 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3268 RealDecl->setInvalidDecl();
3269 return;
3270 }
3271
Douglas Gregor83ddad32009-08-26 21:14:46 +00003272 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003273 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003274 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3275 //
3276 // Clients that want to distinguish between the two forms, can check for
3277 // direct initializer using VarDecl::hasCXXDirectInitializer().
3278 // A major benefit is that clients that don't particularly care about which
3279 // exactly form was it (like the CodeGen) can handle both cases without
3280 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003281
Douglas Gregor83ddad32009-08-26 21:14:46 +00003282 // If either the declaration has a dependent type or if any of the expressions
3283 // is type-dependent, we represent the initialization via a ParenListExpr for
3284 // later use during template instantiation.
3285 if (VDecl->getType()->isDependentType() ||
3286 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3287 // Let clients know that initialization was done with a direct initializer.
3288 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Douglas Gregor83ddad32009-08-26 21:14:46 +00003290 // Store the initialization expressions as a ParenListExpr.
3291 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003292 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003293 new (Context) ParenListExpr(Context, LParenLoc,
3294 (Expr **)Exprs.release(),
3295 NumExprs, RParenLoc));
3296 return;
3297 }
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Douglas Gregor83ddad32009-08-26 21:14:46 +00003299
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003300 // C++ 8.5p11:
3301 // The form of initialization (using parentheses or '=') is generally
3302 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003303 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003304 QualType DeclInitType = VDecl->getType();
3305 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003306 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003307
Douglas Gregor615c5d42009-03-24 16:43:20 +00003308 // FIXME: This isn't the right place to complete the type.
3309 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3310 diag::err_typecheck_decl_incomplete_type)) {
3311 VDecl->setInvalidDecl();
3312 return;
3313 }
3314
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003315 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003316 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3317
Douglas Gregor18fe5682008-11-03 20:45:27 +00003318 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003319 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003320 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003321 VDecl->getLocation(),
3322 SourceRange(VDecl->getLocation(),
3323 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003324 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003325 IK_Direct,
3326 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003327 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003328 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003329 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003330 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003331 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003332 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003333 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003334 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003335 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003336 return;
3337 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003338
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003339 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003340 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3341 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003342 RealDecl->setInvalidDecl();
3343 return;
3344 }
3345
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003346 // Let clients know that initialization was done with a direct initializer.
3347 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003348
3349 assert(NumExprs == 1 && "Expected 1 expression");
3350 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003351 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3352 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003353}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003354
Douglas Gregor39da0b82009-09-09 23:08:42 +00003355/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3356/// may occur as part of direct-initialization or copy-initialization.
3357///
3358/// \param ClassType the type of the object being initialized, which must have
3359/// class type.
3360///
3361/// \param ArgsPtr the arguments provided to initialize the object
3362///
3363/// \param Loc the source location where the initialization occurs
3364///
3365/// \param Range the source range that covers the entire initialization
3366///
3367/// \param InitEntity the name of the entity being initialized, if known
3368///
3369/// \param Kind the type of initialization being performed
3370///
3371/// \param ConvertedArgs a vector that will be filled in with the
3372/// appropriately-converted arguments to the constructor (if initialization
3373/// succeeded).
3374///
3375/// \returns the constructor used to initialize the object, if successful.
3376/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003377CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003378Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003379 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003380 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003381 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003382 InitializationKind Kind,
3383 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003384 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003385 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003386 Expr **Args = (Expr **)ArgsPtr.get();
3387 unsigned NumArgs = ArgsPtr.size();
3388
Mike Stump1eb44332009-09-09 15:08:12 +00003389 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003390 // If the initialization is direct-initialization, or if it is
3391 // copy-initialization where the cv-unqualified version of the
3392 // source type is the same class as, or a derived class of, the
3393 // class of the destination, constructors are considered. The
3394 // applicable constructors are enumerated (13.3.1.3), and the
3395 // best one is chosen through overload resolution (13.3). The
3396 // constructor so selected is called to initialize the object,
3397 // with the initializer expression(s) as its argument(s). If no
3398 // constructor applies, or the overload resolution is ambiguous,
3399 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003400 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3401 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003402
3403 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003404 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003405 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00003406 Context.getCanonicalType(ClassType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003407 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003408 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003409 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003410 // Find the constructor (which may be a template).
3411 CXXConstructorDecl *Constructor = 0;
3412 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3413 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003414 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003415 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3416 else
3417 Constructor = cast<CXXConstructorDecl>(*Con);
3418
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003419 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003420 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003421 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003422 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3423 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003424 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003425 Args, NumArgs, CandidateSet);
3426 else
3427 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3428 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003429 }
3430
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003431 // FIXME: When we decide not to synthesize the implicitly-declared
3432 // constructors, we'll need to make them appear here.
3433
Douglas Gregor18fe5682008-11-03 20:45:27 +00003434 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003435 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003436 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003437 // We found a constructor. Break out so that we can convert the arguments
3438 // appropriately.
3439 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Douglas Gregor18fe5682008-11-03 20:45:27 +00003441 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003442 if (InitEntity)
3443 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003444 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003445 else
3446 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003447 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003448 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003449 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Douglas Gregor18fe5682008-11-03 20:45:27 +00003451 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003452 if (InitEntity)
3453 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3454 else
3455 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003456 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3457 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003458
3459 case OR_Deleted:
3460 if (InitEntity)
3461 Diag(Loc, diag::err_ovl_deleted_init)
3462 << Best->Function->isDeleted()
3463 << InitEntity << Range;
3464 else
3465 Diag(Loc, diag::err_ovl_deleted_init)
3466 << Best->Function->isDeleted()
3467 << InitEntity << Range;
3468 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3469 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003470 }
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Douglas Gregor39da0b82009-09-09 23:08:42 +00003472 // Convert the arguments, fill in default arguments, etc.
3473 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3474 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3475 return 0;
3476
3477 return Constructor;
3478}
3479
3480/// \brief Given a constructor and the set of arguments provided for the
3481/// constructor, convert the arguments and add any required default arguments
3482/// to form a proper call to this constructor.
3483///
3484/// \returns true if an error occurred, false otherwise.
3485bool
3486Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3487 MultiExprArg ArgsPtr,
3488 SourceLocation Loc,
3489 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3490 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3491 unsigned NumArgs = ArgsPtr.size();
3492 Expr **Args = (Expr **)ArgsPtr.get();
3493
3494 const FunctionProtoType *Proto
3495 = Constructor->getType()->getAs<FunctionProtoType>();
3496 assert(Proto && "Constructor without a prototype?");
3497 unsigned NumArgsInProto = Proto->getNumArgs();
3498 unsigned NumArgsToCheck = NumArgs;
3499
3500 // If too few arguments are available, we'll fill in the rest with defaults.
3501 if (NumArgs < NumArgsInProto) {
3502 NumArgsToCheck = NumArgsInProto;
3503 ConvertedArgs.reserve(NumArgsInProto);
3504 } else {
3505 ConvertedArgs.reserve(NumArgs);
3506 if (NumArgs > NumArgsInProto)
3507 NumArgsToCheck = NumArgsInProto;
3508 }
3509
3510 // Convert arguments
3511 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3512 QualType ProtoArgType = Proto->getArgType(i);
3513
3514 Expr *Arg;
3515 if (i < NumArgs) {
3516 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003517
3518 // Pass the argument.
3519 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3520 return true;
3521
3522 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003523 } else {
3524 ParmVarDecl *Param = Constructor->getParamDecl(i);
3525
3526 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3527 if (DefArg.isInvalid())
3528 return true;
3529
3530 Arg = DefArg.takeAs<Expr>();
3531 }
3532
3533 ConvertedArgs.push_back(Arg);
3534 }
3535
3536 // If this is a variadic call, handle args passed through "...".
3537 if (Proto->isVariadic()) {
3538 // Promote the arguments (C99 6.5.2.2p7).
3539 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3540 Expr *Arg = Args[i];
3541 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3542 return true;
3543
3544 ConvertedArgs.push_back(Arg);
3545 Args[i] = 0;
3546 }
3547 }
3548
3549 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003550}
3551
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003552/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3553/// determine whether they are reference-related,
3554/// reference-compatible, reference-compatible with added
3555/// qualification, or incompatible, for use in C++ initialization by
3556/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3557/// type, and the first type (T1) is the pointee type of the reference
3558/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003559Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003560Sema::CompareReferenceRelationship(SourceLocation Loc,
3561 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003562 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003563 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003564 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003565 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003566
Douglas Gregor393896f2009-11-05 13:06:35 +00003567 QualType T1 = Context.getCanonicalType(OrigT1);
3568 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003569 QualType UnqualT1 = T1.getUnqualifiedType();
3570 QualType UnqualT2 = T2.getUnqualifiedType();
3571
3572 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003573 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003574 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003575 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003576 if (UnqualT1 == UnqualT2)
3577 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003578 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3579 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3580 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003581 DerivedToBase = true;
3582 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003583 return Ref_Incompatible;
3584
3585 // At this point, we know that T1 and T2 are reference-related (at
3586 // least).
3587
3588 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003589 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003590 // reference-related to T2 and cv1 is the same cv-qualification
3591 // as, or greater cv-qualification than, cv2. For purposes of
3592 // overload resolution, cases for which cv1 is greater
3593 // cv-qualification than cv2 are identified as
3594 // reference-compatible with added qualification (see 13.3.3.2).
3595 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3596 return Ref_Compatible;
3597 else if (T1.isMoreQualifiedThan(T2))
3598 return Ref_Compatible_With_Added_Qualification;
3599 else
3600 return Ref_Related;
3601}
3602
3603/// CheckReferenceInit - Check the initialization of a reference
3604/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3605/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003606/// list), and DeclType is the type of the declaration. When ICS is
3607/// non-null, this routine will compute the implicit conversion
3608/// sequence according to C++ [over.ics.ref] and will not produce any
3609/// diagnostics; when ICS is null, it will emit diagnostics when any
3610/// errors are found. Either way, a return value of true indicates
3611/// that there was a failure, a return value of false indicates that
3612/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003613///
3614/// When @p SuppressUserConversions, user-defined conversions are
3615/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003616/// When @p AllowExplicit, we also permit explicit user-defined
3617/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003618/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003619bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003620Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003621 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003622 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003623 bool AllowExplicit, bool ForceRValue,
3624 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003625 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3626
Ted Kremenek6217b802009-07-29 21:53:49 +00003627 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003628 QualType T2 = Init->getType();
3629
Douglas Gregor904eed32008-11-10 20:40:00 +00003630 // If the initializer is the address of an overloaded function, try
3631 // to resolve the overloaded function. If all goes well, T2 is the
3632 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003633 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003634 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003635 ICS != 0);
3636 if (Fn) {
3637 // Since we're performing this reference-initialization for
3638 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003639 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003640 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003641 return true;
3642
Anders Carlsson96ad5332009-10-21 17:16:23 +00003643 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003644 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003645
3646 T2 = Fn->getType();
3647 }
3648 }
3649
Douglas Gregor15da57e2008-10-29 02:00:59 +00003650 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003651 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003652 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003653 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3654 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003655 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003656 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003657
3658 // Most paths end in a failed conversion.
3659 if (ICS)
3660 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003661
3662 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003663 // A reference to type "cv1 T1" is initialized by an expression
3664 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003665
3666 // -- If the initializer expression
3667
Sebastian Redla9845802009-03-29 15:27:50 +00003668 // Rvalue references cannot bind to lvalues (N2812).
3669 // There is absolutely no situation where they can. In particular, note that
3670 // this is ill-formed, even if B has a user-defined conversion to A&&:
3671 // B b;
3672 // A&& r = b;
3673 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3674 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003675 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003676 << Init->getSourceRange();
3677 return true;
3678 }
3679
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003680 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003681 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3682 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003683 //
3684 // Note that the bit-field check is skipped if we are just computing
3685 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003686 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003687 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003688 BindsDirectly = true;
3689
Douglas Gregor15da57e2008-10-29 02:00:59 +00003690 if (ICS) {
3691 // C++ [over.ics.ref]p1:
3692 // When a parameter of reference type binds directly (8.5.3)
3693 // to an argument expression, the implicit conversion sequence
3694 // is the identity conversion, unless the argument expression
3695 // has a type that is a derived class of the parameter type,
3696 // in which case the implicit conversion sequence is a
3697 // derived-to-base Conversion (13.3.3.1).
3698 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3699 ICS->Standard.First = ICK_Identity;
3700 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3701 ICS->Standard.Third = ICK_Identity;
3702 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3703 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003704 ICS->Standard.ReferenceBinding = true;
3705 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003706 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003707 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003708
3709 // Nothing more to do: the inaccessibility/ambiguity check for
3710 // derived-to-base conversions is suppressed when we're
3711 // computing the implicit conversion sequence (C++
3712 // [over.best.ics]p2).
3713 return false;
3714 } else {
3715 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003716 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3717 if (DerivedToBase)
3718 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003719 else if(CheckExceptionSpecCompatibility(Init, T1))
3720 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003721 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003722 }
3723 }
3724
3725 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003726 // implicitly converted to an lvalue of type "cv3 T3,"
3727 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003728 // 92) (this conversion is selected by enumerating the
3729 // applicable conversion functions (13.3.1.6) and choosing
3730 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003731 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003732 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003733 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003734 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003735
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003736 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003737 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003738 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003739 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003740 = Conversions->function_begin();
3741 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003742 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003743 = dyn_cast<FunctionTemplateDecl>(*Func);
3744 CXXConversionDecl *Conv;
3745 if (ConvTemplate)
3746 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3747 else
3748 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003749
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003750 // If the conversion function doesn't return a reference type,
3751 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003752 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003753 (AllowExplicit || !Conv->isExplicit())) {
3754 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003755 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003756 CandidateSet);
3757 else
3758 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3759 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003760 }
3761
3762 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003763 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003764 case OR_Success:
3765 // This is a direct binding.
3766 BindsDirectly = true;
3767
3768 if (ICS) {
3769 // C++ [over.ics.ref]p1:
3770 //
3771 // [...] If the parameter binds directly to the result of
3772 // applying a conversion function to the argument
3773 // expression, the implicit conversion sequence is a
3774 // user-defined conversion sequence (13.3.3.1.2), with the
3775 // second standard conversion sequence either an identity
3776 // conversion or, if the conversion function returns an
3777 // entity of a type that is a derived class of the parameter
3778 // type, a derived-to-base Conversion.
3779 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3780 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3781 ICS->UserDefined.After = Best->FinalConversion;
3782 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003783 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003784 assert(ICS->UserDefined.After.ReferenceBinding &&
3785 ICS->UserDefined.After.DirectBinding &&
3786 "Expected a direct reference binding!");
3787 return false;
3788 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003789 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003790 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003791 CastExpr::CK_UserDefinedConversion,
3792 cast<CXXMethodDecl>(Best->Function),
3793 Owned(Init));
3794 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003795
3796 if (CheckExceptionSpecCompatibility(Init, T1))
3797 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003798 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3799 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003800 }
3801 break;
3802
3803 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003804 if (ICS) {
3805 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3806 Cand != CandidateSet.end(); ++Cand)
3807 if (Cand->Viable)
3808 ICS->ConversionFunctionSet.push_back(Cand->Function);
3809 break;
3810 }
3811 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3812 << Init->getSourceRange();
3813 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003814 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003815
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003816 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003817 case OR_Deleted:
3818 // There was no suitable conversion, or we found a deleted
3819 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003820 break;
3821 }
3822 }
Mike Stump1eb44332009-09-09 15:08:12 +00003823
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003824 if (BindsDirectly) {
3825 // C++ [dcl.init.ref]p4:
3826 // [...] In all cases where the reference-related or
3827 // reference-compatible relationship of two types is used to
3828 // establish the validity of a reference binding, and T1 is a
3829 // base class of T2, a program that necessitates such a binding
3830 // is ill-formed if T1 is an inaccessible (clause 11) or
3831 // ambiguous (10.2) base class of T2.
3832 //
3833 // Note that we only check this condition when we're allowed to
3834 // complain about errors, because we should not be checking for
3835 // ambiguity (or inaccessibility) unless the reference binding
3836 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003837 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003838 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003839 Init->getSourceRange());
3840 else
3841 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003842 }
3843
3844 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003845 // type (i.e., cv1 shall be const), or the reference shall be an
3846 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003847 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003848 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003849 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003850 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3851 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003852 return true;
3853 }
3854
3855 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003856 // class type, and "cv1 T1" is reference-compatible with
3857 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003858 // following ways (the choice is implementation-defined):
3859 //
3860 // -- The reference is bound to the object represented by
3861 // the rvalue (see 3.10) or to a sub-object within that
3862 // object.
3863 //
Eli Friedman33a31382009-08-05 19:21:58 +00003864 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003865 // a constructor is called to copy the entire rvalue
3866 // object into the temporary. The reference is bound to
3867 // the temporary or to a sub-object within the
3868 // temporary.
3869 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003870 // The constructor that would be used to make the copy
3871 // shall be callable whether or not the copy is actually
3872 // done.
3873 //
Sebastian Redla9845802009-03-29 15:27:50 +00003874 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003875 // freedom, so we will always take the first option and never build
3876 // a temporary in this case. FIXME: We will, however, have to check
3877 // for the presence of a copy constructor in C++98/03 mode.
3878 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003879 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3880 if (ICS) {
3881 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3882 ICS->Standard.First = ICK_Identity;
3883 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3884 ICS->Standard.Third = ICK_Identity;
3885 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3886 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003887 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003888 ICS->Standard.DirectBinding = false;
3889 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003890 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003891 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003892 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3893 if (DerivedToBase)
3894 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003895 else if(CheckExceptionSpecCompatibility(Init, T1))
3896 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003897 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003898 }
3899 return false;
3900 }
3901
Eli Friedman33a31382009-08-05 19:21:58 +00003902 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003903 // initialized from the initializer expression using the
3904 // rules for a non-reference copy initialization (8.5). The
3905 // reference is then bound to the temporary. If T1 is
3906 // reference-related to T2, cv1 must be the same
3907 // cv-qualification as, or greater cv-qualification than,
3908 // cv2; otherwise, the program is ill-formed.
3909 if (RefRelationship == Ref_Related) {
3910 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3911 // we would be reference-compatible or reference-compatible with
3912 // added qualification. But that wasn't the case, so the reference
3913 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003914 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003915 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003916 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3917 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003918 return true;
3919 }
3920
Douglas Gregor734d9862009-01-30 23:27:23 +00003921 // If at least one of the types is a class type, the types are not
3922 // related, and we aren't allowed any user conversions, the
3923 // reference binding fails. This case is important for breaking
3924 // recursion, since TryImplicitConversion below will attempt to
3925 // create a temporary through the use of a copy constructor.
3926 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3927 (T1->isRecordType() || T2->isRecordType())) {
3928 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003929 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00003930 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3931 return true;
3932 }
3933
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003934 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003935 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003936 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003937 //
Sebastian Redla9845802009-03-29 15:27:50 +00003938 // When a parameter of reference type is not bound directly to
3939 // an argument expression, the conversion sequence is the one
3940 // required to convert the argument expression to the
3941 // underlying type of the reference according to
3942 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3943 // to copy-initializing a temporary of the underlying type with
3944 // the argument expression. Any difference in top-level
3945 // cv-qualification is subsumed by the initialization itself
3946 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003947 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3948 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003949 /*ForceRValue=*/false,
3950 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Sebastian Redla9845802009-03-29 15:27:50 +00003952 // Of course, that's still a reference binding.
3953 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3954 ICS->Standard.ReferenceBinding = true;
3955 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003956 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003957 ImplicitConversionSequence::UserDefinedConversion) {
3958 ICS->UserDefined.After.ReferenceBinding = true;
3959 ICS->UserDefined.After.RRefBinding = isRValRef;
3960 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003961 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3962 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003963 ImplicitConversionSequence Conversions;
3964 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3965 false, false,
3966 Conversions);
3967 if (badConversion) {
3968 if ((Conversions.ConversionKind ==
3969 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00003970 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00003971 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003972 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3973 for (int j = Conversions.ConversionFunctionSet.size()-1;
3974 j >= 0; j--) {
3975 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3976 Diag(Func->getLocation(), diag::err_ovl_candidate);
3977 }
3978 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00003979 else {
3980 if (isRValRef)
3981 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3982 << Init->getSourceRange();
3983 else
3984 Diag(DeclLoc, diag::err_invalid_initialization)
3985 << DeclType << Init->getType() << Init->getSourceRange();
3986 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003987 }
3988 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003989 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003990}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003991
3992/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3993/// of this overloaded operator is well-formed. If so, returns false;
3994/// otherwise, emits appropriate diagnostics and returns true.
3995bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003996 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003997 "Expected an overloaded operator declaration");
3998
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003999 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4000
Mike Stump1eb44332009-09-09 15:08:12 +00004001 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004002 // The allocation and deallocation functions, operator new,
4003 // operator new[], operator delete and operator delete[], are
4004 // described completely in 3.7.3. The attributes and restrictions
4005 // found in the rest of this subclause do not apply to them unless
4006 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004007 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004008 if (Op == OO_New || Op == OO_Array_New ||
4009 Op == OO_Delete || Op == OO_Array_Delete)
4010 return false;
4011
4012 // C++ [over.oper]p6:
4013 // An operator function shall either be a non-static member
4014 // function or be a non-member function and have at least one
4015 // parameter whose type is a class, a reference to a class, an
4016 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004017 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4018 if (MethodDecl->isStatic())
4019 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004021 } else {
4022 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004023 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4024 ParamEnd = FnDecl->param_end();
4025 Param != ParamEnd; ++Param) {
4026 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004027 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4028 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004029 ClassOrEnumParam = true;
4030 break;
4031 }
4032 }
4033
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004034 if (!ClassOrEnumParam)
4035 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004036 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004037 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004038 }
4039
4040 // C++ [over.oper]p8:
4041 // An operator function cannot have default arguments (8.3.6),
4042 // except where explicitly stated below.
4043 //
Mike Stump1eb44332009-09-09 15:08:12 +00004044 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004045 // (C++ [over.call]p1).
4046 if (Op != OO_Call) {
4047 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4048 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004049 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004050 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004051 diag::err_operator_overload_default_arg)
4052 << FnDecl->getDeclName();
4053 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004054 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004055 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004056 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004057 }
4058 }
4059
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004060 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4061 { false, false, false }
4062#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4063 , { Unary, Binary, MemberOnly }
4064#include "clang/Basic/OperatorKinds.def"
4065 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004066
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004067 bool CanBeUnaryOperator = OperatorUses[Op][0];
4068 bool CanBeBinaryOperator = OperatorUses[Op][1];
4069 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004070
4071 // C++ [over.oper]p8:
4072 // [...] Operator functions cannot have more or fewer parameters
4073 // than the number required for the corresponding operator, as
4074 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004075 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004076 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004077 if (Op != OO_Call &&
4078 ((NumParams == 1 && !CanBeUnaryOperator) ||
4079 (NumParams == 2 && !CanBeBinaryOperator) ||
4080 (NumParams < 1) || (NumParams > 2))) {
4081 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004082 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004083 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004084 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004085 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004086 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004087 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004088 assert(CanBeBinaryOperator &&
4089 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004090 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004091 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004092
Chris Lattner416e46f2008-11-21 07:57:12 +00004093 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004094 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004095 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004096
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004097 // Overloaded operators other than operator() cannot be variadic.
4098 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004099 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004100 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004101 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004102 }
4103
4104 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004105 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4106 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004107 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004108 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004109 }
4110
4111 // C++ [over.inc]p1:
4112 // The user-defined function called operator++ implements the
4113 // prefix and postfix ++ operator. If this function is a member
4114 // function with no parameters, or a non-member function with one
4115 // parameter of class or enumeration type, it defines the prefix
4116 // increment operator ++ for objects of that type. If the function
4117 // is a member function with one parameter (which shall be of type
4118 // int) or a non-member function with two parameters (the second
4119 // of which shall be of type int), it defines the postfix
4120 // increment operator ++ for objects of that type.
4121 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4122 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4123 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004124 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004125 ParamIsInt = BT->getKind() == BuiltinType::Int;
4126
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004127 if (!ParamIsInt)
4128 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004129 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004130 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004131 }
4132
Sebastian Redl64b45f72009-01-05 20:52:13 +00004133 // Notify the class if it got an assignment operator.
4134 if (Op == OO_Equal) {
4135 // Would have returned earlier otherwise.
4136 assert(isa<CXXMethodDecl>(FnDecl) &&
4137 "Overloaded = not member, but not filtered.");
4138 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4139 Method->getParent()->addedAssignmentOperator(Context, Method);
4140 }
4141
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004142 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004143}
Chris Lattner5a003a42008-12-17 07:09:26 +00004144
Douglas Gregor074149e2009-01-05 19:45:36 +00004145/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4146/// linkage specification, including the language and (if present)
4147/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4148/// the location of the language string literal, which is provided
4149/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4150/// the '{' brace. Otherwise, this linkage specification does not
4151/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004152Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4153 SourceLocation ExternLoc,
4154 SourceLocation LangLoc,
4155 const char *Lang,
4156 unsigned StrSize,
4157 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004158 LinkageSpecDecl::LanguageIDs Language;
4159 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4160 Language = LinkageSpecDecl::lang_c;
4161 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4162 Language = LinkageSpecDecl::lang_cxx;
4163 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004164 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004165 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004166 }
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Chris Lattnercc98eac2008-12-17 07:13:27 +00004168 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Douglas Gregor074149e2009-01-05 19:45:36 +00004170 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004171 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004172 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004173 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004174 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004175 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004176}
4177
Douglas Gregor074149e2009-01-05 19:45:36 +00004178/// ActOnFinishLinkageSpecification - Completely the definition of
4179/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4180/// valid, it's the position of the closing '}' brace in a linkage
4181/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004182Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4183 DeclPtrTy LinkageSpec,
4184 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004185 if (LinkageSpec)
4186 PopDeclContext();
4187 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004188}
4189
Douglas Gregord308e622009-05-18 20:51:54 +00004190/// \brief Perform semantic analysis for the variable declaration that
4191/// occurs within a C++ catch clause, returning the newly-created
4192/// variable.
4193VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004194 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004195 IdentifierInfo *Name,
4196 SourceLocation Loc,
4197 SourceRange Range) {
4198 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004199
4200 // Arrays and functions decay.
4201 if (ExDeclType->isArrayType())
4202 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4203 else if (ExDeclType->isFunctionType())
4204 ExDeclType = Context.getPointerType(ExDeclType);
4205
4206 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4207 // The exception-declaration shall not denote a pointer or reference to an
4208 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004209 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004210 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004211 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004212 Invalid = true;
4213 }
Douglas Gregord308e622009-05-18 20:51:54 +00004214
Sebastian Redl4b07b292008-12-22 19:15:10 +00004215 QualType BaseType = ExDeclType;
4216 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004217 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004218 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004219 BaseType = Ptr->getPointeeType();
4220 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004221 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004222 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004223 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004224 BaseType = Ref->getPointeeType();
4225 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004226 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004227 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004228 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004229 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004230 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004231
Mike Stump1eb44332009-09-09 15:08:12 +00004232 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004233 RequireNonAbstractType(Loc, ExDeclType,
4234 diag::err_abstract_type_in_decl,
4235 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004236 Invalid = true;
4237
Douglas Gregord308e622009-05-18 20:51:54 +00004238 // FIXME: Need to test for ability to copy-construct and destroy the
4239 // exception variable.
4240
Sebastian Redl8351da02008-12-22 21:35:02 +00004241 // FIXME: Need to check for abstract classes.
4242
Mike Stump1eb44332009-09-09 15:08:12 +00004243 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004244 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004245
4246 if (Invalid)
4247 ExDecl->setInvalidDecl();
4248
4249 return ExDecl;
4250}
4251
4252/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4253/// handler.
4254Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004255 DeclaratorInfo *DInfo = 0;
4256 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004257
4258 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004259 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004260 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004261 // The scope should be freshly made just for us. There is just no way
4262 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004263 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004264 if (PrevDecl->isTemplateParameter()) {
4265 // Maybe we will complain about the shadowed template parameter.
4266 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004267 }
4268 }
4269
Chris Lattnereaaebc72009-04-25 08:06:05 +00004270 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004271 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4272 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004273 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004274 }
4275
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004276 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004277 D.getIdentifier(),
4278 D.getIdentifierLoc(),
4279 D.getDeclSpec().getSourceRange());
4280
Chris Lattnereaaebc72009-04-25 08:06:05 +00004281 if (Invalid)
4282 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004283
Sebastian Redl4b07b292008-12-22 19:15:10 +00004284 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004285 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004286 PushOnScopeChains(ExDecl, S);
4287 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004288 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004289
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004290 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004291 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004292}
Anders Carlssonfb311762009-03-14 00:25:26 +00004293
Mike Stump1eb44332009-09-09 15:08:12 +00004294Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004295 ExprArg assertexpr,
4296 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004297 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004298 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004299 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4300
Anders Carlssonc3082412009-03-14 00:33:21 +00004301 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4302 llvm::APSInt Value(32);
4303 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4304 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4305 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004306 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004307 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004308
Anders Carlssonc3082412009-03-14 00:33:21 +00004309 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004310 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004311 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004312 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004313 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004314 }
4315 }
Mike Stump1eb44332009-09-09 15:08:12 +00004316
Anders Carlsson77d81422009-03-15 17:35:16 +00004317 assertexpr.release();
4318 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004319 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004320 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004321
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004322 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004323 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004324}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004325
John McCalldd4a3b02009-09-16 22:47:08 +00004326/// Handle a friend type declaration. This works in tandem with
4327/// ActOnTag.
4328///
4329/// Notes on friend class templates:
4330///
4331/// We generally treat friend class declarations as if they were
4332/// declaring a class. So, for example, the elaborated type specifier
4333/// in a friend declaration is required to obey the restrictions of a
4334/// class-head (i.e. no typedefs in the scope chain), template
4335/// parameters are required to match up with simple template-ids, &c.
4336/// However, unlike when declaring a template specialization, it's
4337/// okay to refer to a template specialization without an empty
4338/// template parameter declaration, e.g.
4339/// friend class A<T>::B<unsigned>;
4340/// We permit this as a special case; if there are any template
4341/// parameters present at all, require proper matching, i.e.
4342/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004343Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004344 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004345 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004346
4347 assert(DS.isFriendSpecified());
4348 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4349
John McCalldd4a3b02009-09-16 22:47:08 +00004350 // Try to convert the decl specifier to a type. This works for
4351 // friend templates because ActOnTag never produces a ClassTemplateDecl
4352 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004353 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004354 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4355 if (TheDeclarator.isInvalidType())
4356 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004357
John McCalldd4a3b02009-09-16 22:47:08 +00004358 // This is definitely an error in C++98. It's probably meant to
4359 // be forbidden in C++0x, too, but the specification is just
4360 // poorly written.
4361 //
4362 // The problem is with declarations like the following:
4363 // template <T> friend A<T>::foo;
4364 // where deciding whether a class C is a friend or not now hinges
4365 // on whether there exists an instantiation of A that causes
4366 // 'foo' to equal C. There are restrictions on class-heads
4367 // (which we declare (by fiat) elaborated friend declarations to
4368 // be) that makes this tractable.
4369 //
4370 // FIXME: handle "template <> friend class A<T>;", which
4371 // is possibly well-formed? Who even knows?
4372 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4373 Diag(Loc, diag::err_tagless_friend_type_template)
4374 << DS.getSourceRange();
4375 return DeclPtrTy();
4376 }
4377
John McCall02cace72009-08-28 07:59:38 +00004378 // C++ [class.friend]p2:
4379 // An elaborated-type-specifier shall be used in a friend declaration
4380 // for a class.*
4381 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004382 // This is one of the rare places in Clang where it's legitimate to
4383 // ask about the "spelling" of the type.
4384 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4385 // If we evaluated the type to a record type, suggest putting
4386 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004387 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004388 RecordDecl *RD = RT->getDecl();
4389
4390 std::string InsertionText = std::string(" ") + RD->getKindName();
4391
John McCalle3af0232009-10-07 23:34:25 +00004392 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4393 << (unsigned) RD->getTagKind()
4394 << T
4395 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004396 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4397 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004398 return DeclPtrTy();
4399 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004400 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4401 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004402 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004403 }
4404 }
4405
John McCalle3af0232009-10-07 23:34:25 +00004406 // Enum types cannot be friends.
4407 if (T->getAs<EnumType>()) {
4408 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4409 << SourceRange(DS.getFriendSpecLoc());
4410 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004411 }
John McCall02cace72009-08-28 07:59:38 +00004412
John McCall02cace72009-08-28 07:59:38 +00004413 // C++98 [class.friend]p1: A friend of a class is a function
4414 // or class that is not a member of the class . . .
4415 // But that's a silly restriction which nobody implements for
4416 // inner classes, and C++0x removes it anyway, so we only report
4417 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004418 if (!getLangOptions().CPlusPlus0x)
4419 if (const RecordType *RT = T->getAs<RecordType>())
4420 if (RT->getDecl()->getDeclContext() == CurContext)
4421 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004422
John McCalldd4a3b02009-09-16 22:47:08 +00004423 Decl *D;
4424 if (TempParams.size())
4425 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4426 TempParams.size(),
4427 (TemplateParameterList**) TempParams.release(),
4428 T.getTypePtr(),
4429 DS.getFriendSpecLoc());
4430 else
4431 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4432 DS.getFriendSpecLoc());
4433 D->setAccess(AS_public);
4434 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004435
John McCalldd4a3b02009-09-16 22:47:08 +00004436 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004437}
4438
John McCallbbbcdd92009-09-11 21:02:39 +00004439Sema::DeclPtrTy
4440Sema::ActOnFriendFunctionDecl(Scope *S,
4441 Declarator &D,
4442 bool IsDefinition,
4443 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004444 const DeclSpec &DS = D.getDeclSpec();
4445
4446 assert(DS.isFriendSpecified());
4447 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4448
4449 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004450 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004451 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004452
4453 // C++ [class.friend]p1
4454 // A friend of a class is a function or class....
4455 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004456 // It *doesn't* see through dependent types, which is correct
4457 // according to [temp.arg.type]p3:
4458 // If a declaration acquires a function type through a
4459 // type dependent on a template-parameter and this causes
4460 // a declaration that does not use the syntactic form of a
4461 // function declarator to have a function type, the program
4462 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004463 if (!T->isFunctionType()) {
4464 Diag(Loc, diag::err_unexpected_friend);
4465
4466 // It might be worthwhile to try to recover by creating an
4467 // appropriate declaration.
4468 return DeclPtrTy();
4469 }
4470
4471 // C++ [namespace.memdef]p3
4472 // - If a friend declaration in a non-local class first declares a
4473 // class or function, the friend class or function is a member
4474 // of the innermost enclosing namespace.
4475 // - The name of the friend is not found by simple name lookup
4476 // until a matching declaration is provided in that namespace
4477 // scope (either before or after the class declaration granting
4478 // friendship).
4479 // - If a friend function is called, its name may be found by the
4480 // name lookup that considers functions from namespaces and
4481 // classes associated with the types of the function arguments.
4482 // - When looking for a prior declaration of a class or a function
4483 // declared as a friend, scopes outside the innermost enclosing
4484 // namespace scope are not considered.
4485
John McCall02cace72009-08-28 07:59:38 +00004486 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4487 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004488 assert(Name);
4489
John McCall67d1a672009-08-06 02:15:43 +00004490 // The context we found the declaration in, or in which we should
4491 // create the declaration.
4492 DeclContext *DC;
4493
4494 // FIXME: handle local classes
4495
4496 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004497 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004498 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004499 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004500 DC = computeDeclContext(ScopeQual);
4501
4502 // FIXME: handle dependent contexts
4503 if (!DC) return DeclPtrTy();
4504
John McCallf36e02d2009-10-09 21:13:30 +00004505 LookupResult R;
4506 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4507 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004508
4509 // If searching in that context implicitly found a declaration in
4510 // a different context, treat it like it wasn't found at all.
4511 // TODO: better diagnostics for this case. Suggesting the right
4512 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004513 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004514 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004515 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4516 return DeclPtrTy();
4517 }
4518
4519 // C++ [class.friend]p1: A friend of a class is a function or
4520 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004521 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004522 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4523
John McCall67d1a672009-08-06 02:15:43 +00004524 // Otherwise walk out to the nearest namespace scope looking for matches.
4525 } else {
4526 // TODO: handle local class contexts.
4527
4528 DC = CurContext;
4529 while (true) {
4530 // Skip class contexts. If someone can cite chapter and verse
4531 // for this behavior, that would be nice --- it's what GCC and
4532 // EDG do, and it seems like a reasonable intent, but the spec
4533 // really only says that checks for unqualified existing
4534 // declarations should stop at the nearest enclosing namespace,
4535 // not that they should only consider the nearest enclosing
4536 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004537 while (DC->isRecord())
4538 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004539
John McCallf36e02d2009-10-09 21:13:30 +00004540 LookupResult R;
4541 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4542 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004543
4544 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004545 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004546 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004547
John McCall67d1a672009-08-06 02:15:43 +00004548 if (DC->isFileContext()) break;
4549 DC = DC->getParent();
4550 }
4551
4552 // C++ [class.friend]p1: A friend of a class is a function or
4553 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004554 // C++0x changes this for both friend types and functions.
4555 // Most C++ 98 compilers do seem to give an error here, so
4556 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004557 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004558 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4559 }
4560
Douglas Gregor182ddf02009-09-28 00:08:27 +00004561 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004562 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004563 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4564 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4565 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004566 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004567 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4568 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004569 return DeclPtrTy();
4570 }
John McCall67d1a672009-08-06 02:15:43 +00004571 }
4572
Douglas Gregor182ddf02009-09-28 00:08:27 +00004573 bool Redeclaration = false;
4574 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004575 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004576 IsDefinition,
4577 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004578 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004579
Douglas Gregor182ddf02009-09-28 00:08:27 +00004580 assert(ND->getDeclContext() == DC);
4581 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004582
John McCallab88d972009-08-31 22:39:49 +00004583 // Add the function declaration to the appropriate lookup tables,
4584 // adjusting the redeclarations list as necessary. We don't
4585 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004586 //
John McCallab88d972009-08-31 22:39:49 +00004587 // Also update the scope-based lookup if the target context's
4588 // lookup context is in lexical scope.
4589 if (!CurContext->isDependentContext()) {
4590 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004591 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004592 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004593 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004594 }
John McCall02cace72009-08-28 07:59:38 +00004595
4596 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004597 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004598 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004599 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004600 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004601
Douglas Gregor182ddf02009-09-28 00:08:27 +00004602 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004603}
4604
Chris Lattnerb28317a2009-03-28 19:18:32 +00004605void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004606 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Chris Lattnerb28317a2009-03-28 19:18:32 +00004608 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004609 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4610 if (!Fn) {
4611 Diag(DelLoc, diag::err_deleted_non_function);
4612 return;
4613 }
4614 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4615 Diag(DelLoc, diag::err_deleted_decl_not_first);
4616 Diag(Prev->getLocation(), diag::note_previous_declaration);
4617 // If the declaration wasn't the first, we delete the function anyway for
4618 // recovery.
4619 }
4620 Fn->setDeleted();
4621}
Sebastian Redl13e88542009-04-27 21:33:24 +00004622
4623static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4624 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4625 ++CI) {
4626 Stmt *SubStmt = *CI;
4627 if (!SubStmt)
4628 continue;
4629 if (isa<ReturnStmt>(SubStmt))
4630 Self.Diag(SubStmt->getSourceRange().getBegin(),
4631 diag::err_return_in_constructor_handler);
4632 if (!isa<Expr>(SubStmt))
4633 SearchForReturnInStmt(Self, SubStmt);
4634 }
4635}
4636
4637void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4638 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4639 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4640 SearchForReturnInStmt(*this, Handler);
4641 }
4642}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004643
Mike Stump1eb44332009-09-09 15:08:12 +00004644bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004645 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004646 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4647 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004648
4649 QualType CNewTy = Context.getCanonicalType(NewTy);
4650 QualType COldTy = Context.getCanonicalType(OldTy);
4651
Mike Stump1eb44332009-09-09 15:08:12 +00004652 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004653 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4654 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004655
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004656 // Check if the return types are covariant
4657 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004658
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004659 /// Both types must be pointers or references to classes.
4660 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4661 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4662 NewClassTy = NewPT->getPointeeType();
4663 OldClassTy = OldPT->getPointeeType();
4664 }
4665 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4666 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4667 NewClassTy = NewRT->getPointeeType();
4668 OldClassTy = OldRT->getPointeeType();
4669 }
4670 }
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004672 // The return types aren't either both pointers or references to a class type.
4673 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004674 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004675 diag::err_different_return_type_for_overriding_virtual_function)
4676 << New->getDeclName() << NewTy << OldTy;
4677 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004679 return true;
4680 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004681
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004682 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4683 // Check if the new class derives from the old class.
4684 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4685 Diag(New->getLocation(),
4686 diag::err_covariant_return_not_derived)
4687 << New->getDeclName() << NewTy << OldTy;
4688 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4689 return true;
4690 }
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004692 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004693 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004694 diag::err_covariant_return_inaccessible_base,
4695 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4696 // FIXME: Should this point to the return type?
4697 New->getLocation(), SourceRange(), New->getDeclName())) {
4698 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4699 return true;
4700 }
4701 }
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004703 // The qualifiers of the return types must be the same.
4704 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4705 Diag(New->getLocation(),
4706 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004707 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004708 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4709 return true;
4710 };
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004712
4713 // The new class type must have the same or less qualifiers as the old type.
4714 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4715 Diag(New->getLocation(),
4716 diag::err_covariant_return_type_class_type_more_qualified)
4717 << New->getDeclName() << NewTy << OldTy;
4718 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4719 return true;
4720 };
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004722 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004723}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004724
4725/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4726/// initializer for the declaration 'Dcl'.
4727/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4728/// static data member of class X, names should be looked up in the scope of
4729/// class X.
4730void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004731 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004733 Decl *D = Dcl.getAs<Decl>();
4734 // If there is no declaration, there was an error parsing it.
4735 if (D == 0)
4736 return;
4737
4738 // Check whether it is a declaration with a nested name specifier like
4739 // int foo::bar;
4740 if (!D->isOutOfLine())
4741 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004743 // C++ [basic.lookup.unqual]p13
4744 //
4745 // A name used in the definition of a static data member of class X
4746 // (after the qualified-id of the static member) is looked up as if the name
4747 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004749 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004750 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004751}
4752
4753/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4754/// initializer for the declaration 'Dcl'.
4755void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004756 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004758 Decl *D = Dcl.getAs<Decl>();
4759 // If there is no declaration, there was an error parsing it.
4760 if (D == 0)
4761 return;
4762
4763 // Check whether it is a declaration with a nested name specifier like
4764 // int foo::bar;
4765 if (!D->isOutOfLine())
4766 return;
4767
4768 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004769 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004770}