blob: f040aafc2e2859ec61a798dc8338063700281daa [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"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000026#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000028#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000029#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000030
31using namespace clang;
32
Chris Lattner8123a952008-04-10 02:22:51 +000033//===----------------------------------------------------------------------===//
34// CheckDefaultArgumentVisitor
35//===----------------------------------------------------------------------===//
36
Chris Lattner9e979552008-04-12 23:52:44 +000037namespace {
38 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
39 /// the default argument of a parameter to determine whether it
40 /// contains any ill-formed subexpressions. For example, this will
41 /// diagnose the use of local variables or parameters within the
42 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000043 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000044 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000045 Expr *DefaultArg;
46 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 public:
Mike Stump1eb44332009-09-09 15:08:12 +000049 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000050 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000051
Chris Lattner9e979552008-04-12 23:52:44 +000052 bool VisitExpr(Expr *Node);
53 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000054 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000055 };
Chris Lattner8123a952008-04-10 02:22:51 +000056
Chris Lattner9e979552008-04-12 23:52:44 +000057 /// VisitExpr - Visit all of the children of this expression.
58 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
59 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000060 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000061 E = Node->child_end(); I != E; ++I)
62 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000063 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000064 }
65
Chris Lattner9e979552008-04-12 23:52:44 +000066 /// VisitDeclRefExpr - Visit a reference to a declaration, to
67 /// determine whether this declaration can be used in the default
68 /// argument expression.
69 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000070 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000071 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
72 // C++ [dcl.fct.default]p9
73 // Default arguments are evaluated each time the function is
74 // called. The order of evaluation of function arguments is
75 // unspecified. Consequently, parameters of a function shall not
76 // be used in default argument expressions, even if they are not
77 // evaluated. Parameters of a function declared before a default
78 // argument expression are in scope and can hide namespace and
79 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000080 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000081 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000082 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000083 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000084 // C++ [dcl.fct.default]p7
85 // Local variables shall not be used in default argument
86 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000087 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000090 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000091 }
Chris Lattner8123a952008-04-10 02:22:51 +000092
Douglas Gregor3996f232008-11-04 13:41:56 +000093 return false;
94 }
Chris Lattner9e979552008-04-12 23:52:44 +000095
Douglas Gregor796da182008-11-04 14:32:21 +000096 /// VisitCXXThisExpr - Visit a C++ "this" expression.
97 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
98 // C++ [dcl.fct.default]p8:
99 // The keyword this shall not be used in a default argument of a
100 // member function.
101 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_this)
103 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000104 }
Chris Lattner8123a952008-04-10 02:22:51 +0000105}
106
Anders Carlssoned961f92009-08-25 02:29:20 +0000107bool
108Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000109 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000110 QualType ParamType = Param->getType();
111
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000126 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000127 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000128 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000129
130 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Anders Carlssoned961f92009-08-25 02:29:20 +0000132 // Okay: add the default argument to the parameter
133 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Anders Carlssoned961f92009-08-25 02:29:20 +0000135 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Anders Carlsson9351c172009-08-25 03:18:48 +0000137 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000138}
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140/// ActOnParamDefaultArgument - Check whether the default argument
141/// provided for a function parameter is well-formed. If so, attach it
142/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000143void
Mike Stump1eb44332009-09-09 15:08:12 +0000144Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000145 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000146 if (!param || !defarg.get())
147 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Chris Lattnerb28317a2009-03-28 19:18:32 +0000149 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000150 UnparsedDefaultArgLocs.erase(Param);
151
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000152 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000153 QualType ParamType = Param->getType();
154
155 // Default arguments are only permitted in C++
156 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000157 Diag(EqualLoc, diag::err_param_default_argument)
158 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000159 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000160 return;
161 }
162
Anders Carlsson66e30672009-08-25 01:02:06 +0000163 // Check that the default argument is well-formed
164 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
165 if (DefaultArgChecker.Visit(DefaultArg.get())) {
166 Param->setInvalidDecl();
167 return;
168 }
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Anders Carlssoned961f92009-08-25 02:29:20 +0000170 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000171}
172
Douglas Gregor61366e92008-12-24 00:01:03 +0000173/// ActOnParamUnparsedDefaultArgument - We've seen a default
174/// argument for a function parameter, but we can't parse it yet
175/// because we're inside a class definition. Note that this default
176/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000177void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000178 SourceLocation EqualLoc,
179 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000180 if (!param)
181 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattnerb28317a2009-03-28 19:18:32 +0000183 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000184 if (Param)
185 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Anders Carlsson5e300d12009-06-12 16:51:40 +0000187 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000188}
189
Douglas Gregor72b505b2008-12-16 21:30:33 +0000190/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
191/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000192void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000193 if (!param)
194 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Anders Carlsson5e300d12009-06-12 16:51:40 +0000196 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlsson5e300d12009-06-12 16:51:40 +0000198 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000201}
202
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000203/// CheckExtraCXXDefaultArguments - Check for any extra default
204/// arguments in the declarator, which is not a function declaration
205/// or definition and therefore is not permitted to have default
206/// arguments. This routine should be invoked for every declarator
207/// that is not a function declaration or definition.
208void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
209 // C++ [dcl.fct.default]p3
210 // A default argument expression shall be specified only in the
211 // parameter-declaration-clause of a function declaration or in a
212 // template-parameter (14.1). It shall not be specified for a
213 // parameter pack. If it is specified in a
214 // parameter-declaration-clause, it shall not occur within a
215 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000216 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000217 DeclaratorChunk &chunk = D.getTypeObject(i);
218 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000219 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
220 ParmVarDecl *Param =
221 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000222 if (Param->hasUnparsedDefaultArg()) {
223 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000224 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
225 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
226 delete Toks;
227 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000228 } else if (Param->getDefaultArg()) {
229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << Param->getDefaultArg()->getSourceRange();
231 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000232 }
233 }
234 }
235 }
236}
237
Chris Lattner3d1cee32008-04-08 05:04:30 +0000238// MergeCXXFunctionDecl - Merge two declarations of the same C++
239// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000240// type. Subroutine of MergeFunctionDecl. Returns true if there was an
241// error, false otherwise.
242bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
243 bool Invalid = false;
244
Chris Lattner3d1cee32008-04-08 05:04:30 +0000245 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000257 //
258 // C++ [dcl.fct.default]p6:
259 // Except for member functions of class templates, the default arguments
260 // in a member function definition that appears outside of the class
261 // definition are added to the set of default arguments provided by the
262 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000263 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
264 ParmVarDecl *OldParam = Old->getParamDecl(p);
265 ParmVarDecl *NewParam = New->getParamDecl(p);
266
Douglas Gregor6cc15182009-09-11 18:44:32 +0000267 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000268 // FIXME: If the parameter doesn't have an identifier then the location
269 // points to the '=' which means that the fixit hint won't remove any
270 // extra spaces between the type and the '='.
271 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000272 if (NewParam->getIdentifier())
273 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000274
Mike Stump1eb44332009-09-09 15:08:12 +0000275 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000276 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000277 << NewParam->getDefaultArgRange()
278 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
279 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000280
281 // Look for the function declaration where the default argument was
282 // actually written, which may be a declaration prior to Old.
283 for (FunctionDecl *Older = Old->getPreviousDeclaration();
284 Older; Older = Older->getPreviousDeclaration()) {
285 if (!Older->getParamDecl(p)->hasDefaultArg())
286 break;
287
288 OldParam = Older->getParamDecl(p);
289 }
290
291 Diag(OldParam->getLocation(), diag::note_previous_definition)
292 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000293 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000294 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000295 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000296 if (OldParam->hasUninstantiatedDefaultArg())
297 NewParam->setUninstantiatedDefaultArg(
298 OldParam->getUninstantiatedDefaultArg());
299 else
300 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000301 } else if (NewParam->hasDefaultArg()) {
302 if (New->getDescribedFunctionTemplate()) {
303 // Paragraph 4, quoted above, only applies to non-template functions.
304 Diag(NewParam->getLocation(),
305 diag::err_param_default_argument_template_redecl)
306 << NewParam->getDefaultArgRange();
307 Diag(Old->getLocation(), diag::note_template_prev_declaration)
308 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000309 } else if (New->getTemplateSpecializationKind()
310 != TSK_ImplicitInstantiation &&
311 New->getTemplateSpecializationKind() != TSK_Undeclared) {
312 // C++ [temp.expr.spec]p21:
313 // Default function arguments shall not be specified in a declaration
314 // or a definition for one of the following explicit specializations:
315 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000316 // - the explicit specialization of a member function template;
317 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000318 // template where the class template specialization to which the
319 // member function specialization belongs is implicitly
320 // instantiated.
321 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
322 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
323 << New->getDeclName()
324 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000325 } else if (New->getDeclContext()->isDependentContext()) {
326 // C++ [dcl.fct.default]p6 (DR217):
327 // Default arguments for a member function of a class template shall
328 // be specified on the initial declaration of the member function
329 // within the class template.
330 //
331 // Reading the tea leaves a bit in DR217 and its reference to DR205
332 // leads me to the conclusion that one cannot add default function
333 // arguments for an out-of-line definition of a member function of a
334 // dependent type.
335 int WhichKind = 2;
336 if (CXXRecordDecl *Record
337 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
338 if (Record->getDescribedClassTemplate())
339 WhichKind = 0;
340 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
341 WhichKind = 1;
342 else
343 WhichKind = 2;
344 }
345
346 Diag(NewParam->getLocation(),
347 diag::err_param_default_argument_member_template_redecl)
348 << WhichKind
349 << NewParam->getDefaultArgRange();
350 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000351 }
352 }
353
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000354 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000355 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
356 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000357 Invalid = true;
358 }
359
Douglas Gregorcda9c672009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000393 else
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000416
Douglas Gregorb48fe382008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump1eb44332009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedman1d954f62009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
491
492 // C++ [dcl.init.aggr]p1:
493 // An aggregate is [...] a class with [...] no base classes [...].
494 Class->setAggregate(false);
495 Class->setPOD(false);
496
Anders Carlsson347ba892009-04-16 00:08:20 +0000497 if (Virtual) {
498 // C++ [class.ctor]p5:
499 // A constructor is trivial if its class has no virtual base classes.
500 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000501
502 // C++ [class.copy]p6:
503 // A copy constructor is trivial if its class has no virtual base classes.
504 Class->setHasTrivialCopyConstructor(false);
505
506 // C++ [class.copy]p11:
507 // A copy assignment operator is trivial if its class has no virtual
508 // base classes.
509 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000510
511 // C++0x [meta.unary.prop] is_empty:
512 // T is a class type, but not a union type, with ... no virtual base
513 // classes
514 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000515 } else {
516 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000517 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000518 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000519 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
520 Class->setHasTrivialConstructor(false);
521
522 // C++ [class.copy]p6:
523 // A copy constructor is trivial if all the direct base classes of its
524 // class have trivial copy constructors.
525 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
526 Class->setHasTrivialCopyConstructor(false);
527
528 // C++ [class.copy]p11:
529 // A copy assignment operator is trivial if all the direct base classes
530 // of its class have trivial copy assignment operators.
531 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
532 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000533 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000534
535 // C++ [class.ctor]p3:
536 // A destructor is trivial if all the direct base classes of its class
537 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
539 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor2943aed2009-03-03 04:44:36 +0000541 // Create the base specifier.
542 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000543 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
544 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000545 Access, BaseType);
546}
547
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000548/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
549/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000550/// example:
551/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000552/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000553Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000555 bool Virtual, AccessSpecifier Access,
556 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000557 if (!classdecl)
558 return true;
559
Douglas Gregor40808ce2009-03-09 23:48:35 +0000560 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000561 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000562 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
564 Virtual, Access,
565 BaseType, BaseLoc))
566 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000569}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000570
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571/// \brief Performs the actual work of attaching the given base class
572/// specifiers to a C++ class.
573bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
574 unsigned NumBases) {
575 if (NumBases == 0)
576 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000577
578 // Used to keep track of which base types we have already seen, so
579 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000580 // that the key is always the unqualified canonical type of the base
581 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000582 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
583
584 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000585 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000586 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000587 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000588 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000590 NewBaseType = NewBaseType.getUnqualifiedType();
591
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000592 if (KnownBaseTypes[NewBaseType]) {
593 // C++ [class.mi]p3:
594 // A class shall not be specified as a direct base class of a
595 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000597 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000598 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000600
601 // Delete the duplicate base class specifier; we're going to
602 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000603 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604
605 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000606 } else {
607 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608 KnownBaseTypes[NewBaseType] = Bases[idx];
609 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 }
611 }
612
613 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000614 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615
616 // Delete the remaining (good) base class specifiers, since their
617 // data has been copied into the CXXRecordDecl.
618 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000619 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620
621 return Invalid;
622}
623
624/// ActOnBaseSpecifiers - Attach the given base specifiers to the
625/// class, after checking whether there are any duplicate base
626/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000627void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628 unsigned NumBases) {
629 if (!ClassDecl || !Bases || !NumBases)
630 return;
631
632 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000633 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000634 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000635}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000636
Douglas Gregora8f32e02009-10-06 17:59:45 +0000637/// \brief Determine whether the type \p Derived is a C++ class that is
638/// derived from the type \p Base.
639bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
640 if (!getLangOptions().CPlusPlus)
641 return false;
642
643 const RecordType *DerivedRT = Derived->getAs<RecordType>();
644 if (!DerivedRT)
645 return false;
646
647 const RecordType *BaseRT = Base->getAs<RecordType>();
648 if (!BaseRT)
649 return false;
650
651 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
652 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
653 return DerivedRD->isDerivedFrom(BaseRD);
654}
655
656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
661
662 const RecordType *DerivedRT = Derived->getAs<RecordType>();
663 if (!DerivedRT)
664 return false;
665
666 const RecordType *BaseRT = Base->getAs<RecordType>();
667 if (!BaseRT)
668 return false;
669
670 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
671 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
672 return DerivedRD->isDerivedFrom(BaseRD, Paths);
673}
674
675/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
676/// conversion (where Derived and Base are class types) is
677/// well-formed, meaning that the conversion is unambiguous (and
678/// that all of the base classes are accessible). Returns true
679/// and emits a diagnostic if the code is ill-formed, returns false
680/// otherwise. Loc is the location where this routine should point to
681/// if there is an error, and Range is the source range to highlight
682/// if there is an error.
683bool
684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
685 unsigned InaccessibleBaseID,
686 unsigned AmbigiousBaseConvID,
687 SourceLocation Loc, SourceRange Range,
688 DeclarationName Name) {
689 // First, determine whether the path from Derived to Base is
690 // ambiguous. This is slightly more expensive than checking whether
691 // the Derived to Base conversion exists, because here we need to
692 // explore multiple paths to determine if there is an ambiguity.
693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
696 assert(DerivationOkay &&
697 "Can only be used with a derived-to-base conversion");
698 (void)DerivationOkay;
699
700 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
701 // Check that the base class can be accessed.
702 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
703 Name);
704 }
705
706 // We know that the derived-to-base conversion is ambiguous, and
707 // we're going to produce a diagnostic. Perform the derived-to-base
708 // search just one more time to compute all of the possible paths so
709 // that we can print them out. This is more expensive than any of
710 // the previous derived-to-base checks we've done, but at this point
711 // performance isn't as much of an issue.
712 Paths.clear();
713 Paths.setRecordingPaths(true);
714 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
715 assert(StillOkay && "Can only be used with a derived-to-base conversion");
716 (void)StillOkay;
717
718 // Build up a textual representation of the ambiguous paths, e.g.,
719 // D -> B -> A, that will be used to illustrate the ambiguous
720 // conversions in the diagnostic. We only print one of the paths
721 // to each base class subobject.
722 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
723
724 Diag(Loc, AmbigiousBaseConvID)
725 << Derived << Base << PathDisplayStr << Range << Name;
726 return true;
727}
728
729bool
730Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
731 SourceLocation Loc, SourceRange Range) {
732 return CheckDerivedToBaseConversion(Derived, Base,
733 diag::err_conv_to_inaccessible_base,
734 diag::err_ambiguous_derived_to_base_conv,
735 Loc, Range, DeclarationName());
736}
737
738
739/// @brief Builds a string representing ambiguous paths from a
740/// specific derived class to different subobjects of the same base
741/// class.
742///
743/// This function builds a string that can be used in error messages
744/// to show the different paths that one can take through the
745/// inheritance hierarchy to go from the derived class to different
746/// subobjects of a base class. The result looks something like this:
747/// @code
748/// struct D -> struct B -> struct A
749/// struct D -> struct C -> struct A
750/// @endcode
751std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
752 std::string PathDisplayStr;
753 std::set<unsigned> DisplayedPaths;
754 for (CXXBasePaths::paths_iterator Path = Paths.begin();
755 Path != Paths.end(); ++Path) {
756 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
757 // We haven't displayed a path to this particular base
758 // class subobject yet.
759 PathDisplayStr += "\n ";
760 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
761 for (CXXBasePath::const_iterator Element = Path->begin();
762 Element != Path->end(); ++Element)
763 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
764 }
765 }
766
767 return PathDisplayStr;
768}
769
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000770//===----------------------------------------------------------------------===//
771// C++ class member Handling
772//===----------------------------------------------------------------------===//
773
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000774/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
775/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
776/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000777/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000778Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000779Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000780 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000781 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000782 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000783 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000784 Expr *BitWidth = static_cast<Expr*>(BW);
785 Expr *Init = static_cast<Expr*>(InitExpr);
786 SourceLocation Loc = D.getIdentifierLoc();
787
Sebastian Redl669d5d72008-11-14 23:42:31 +0000788 bool isFunc = D.isFunctionDeclarator();
789
John McCall67d1a672009-08-06 02:15:43 +0000790 assert(!DS.isFriendSpecified());
791
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000792 // C++ 9.2p6: A member shall not be declared to have automatic storage
793 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000794 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
795 // data members and cannot be applied to names declared const or static,
796 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000797 switch (DS.getStorageClassSpec()) {
798 case DeclSpec::SCS_unspecified:
799 case DeclSpec::SCS_typedef:
800 case DeclSpec::SCS_static:
801 // FALL THROUGH.
802 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000803 case DeclSpec::SCS_mutable:
804 if (isFunc) {
805 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000806 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000807 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000808 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Sebastian Redla11f42f2008-11-17 23:24:37 +0000810 // FIXME: It would be nicer if the keyword was ignored only for this
811 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000812 D.getMutableDeclSpec().ClearStorageClassSpecs();
813 } else {
814 QualType T = GetTypeForDeclarator(D, S);
815 diag::kind err = static_cast<diag::kind>(0);
816 if (T->isReferenceType())
817 err = diag::err_mutable_reference;
818 else if (T.isConstQualified())
819 err = diag::err_mutable_const;
820 if (err != 0) {
821 if (DS.getStorageClassSpecLoc().isValid())
822 Diag(DS.getStorageClassSpecLoc(), err);
823 else
824 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000825 // FIXME: It would be nicer if the keyword was ignored only for this
826 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829 }
830 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000831 default:
832 if (DS.getStorageClassSpecLoc().isValid())
833 Diag(DS.getStorageClassSpecLoc(),
834 diag::err_storageclass_invalid_for_member);
835 else
836 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
837 D.getMutableDeclSpec().ClearStorageClassSpecs();
838 }
839
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000840 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000841 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000842 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000843 // Check also for this case:
844 //
845 // typedef int f();
846 // f a;
847 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000848 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000849 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000850 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000851
Sebastian Redl669d5d72008-11-14 23:42:31 +0000852 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
853 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000854 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855
856 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000857 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000858 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000859 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
860 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000861 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000862 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000863 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
864 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000865 if (!Member) {
866 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000867 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000868 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000869
870 // Non-instance-fields can't have a bitfield.
871 if (BitWidth) {
872 if (Member->isInvalidDecl()) {
873 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000874 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000875 // C++ 9.6p3: A bit-field shall not be a static member.
876 // "static member 'A' cannot be a bit-field"
877 Diag(Loc, diag::err_static_not_bitfield)
878 << Name << BitWidth->getSourceRange();
879 } else if (isa<TypedefDecl>(Member)) {
880 // "typedef member 'x' cannot be a bit-field"
881 Diag(Loc, diag::err_typedef_not_bitfield)
882 << Name << BitWidth->getSourceRange();
883 } else {
884 // A function typedef ("typedef int f(); f a;").
885 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
886 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000887 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000888 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000889 }
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chris Lattner8b963ef2009-03-05 23:01:03 +0000891 DeleteExpr(BitWidth);
892 BitWidth = 0;
893 Member->setInvalidDecl();
894 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000895
896 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Douglas Gregor37b372b2009-08-20 22:52:58 +0000898 // If we have declared a member function template, set the access of the
899 // templated declaration as well.
900 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
901 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000902 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000903
Douglas Gregor10bd3682008-11-17 22:58:34 +0000904 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000905
Douglas Gregor021c3b32009-03-11 23:00:04 +0000906 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000907 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000908 if (Deleted) // FIXME: Source location is not very good.
909 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000910
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000911 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000912 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000913 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000914 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000915 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916}
917
Douglas Gregor7ad83902008-11-05 04:29:56 +0000918/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000919Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000920Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000921 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000922 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000923 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000924 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000925 SourceLocation IdLoc,
926 SourceLocation LParenLoc,
927 ExprTy **Args, unsigned NumArgs,
928 SourceLocation *CommaLocs,
929 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000930 if (!ConstructorD)
931 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000933 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000934
935 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000936 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000937 if (!Constructor) {
938 // The user wrote a constructor initializer on a function that is
939 // not a C++ constructor. Ignore the error for now, because we may
940 // have more member initializers coming; we'll diagnose it just
941 // once in ActOnMemInitializers.
942 return true;
943 }
944
945 CXXRecordDecl *ClassDecl = Constructor->getParent();
946
947 // C++ [class.base.init]p2:
948 // Names in a mem-initializer-id are looked up in the scope of the
949 // constructor’s class and, if not found in that scope, are looked
950 // up in the scope containing the constructor’s
951 // definition. [Note: if the constructor’s class contains a member
952 // with the same name as a direct or virtual base class of the
953 // class, a mem-initializer-id naming the member or base class and
954 // composed of a single identifier refers to the class member. A
955 // mem-initializer-id for the hidden base class may be specified
956 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000957 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000958 // Look for a member, first.
959 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000960 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000961 = ClassDecl->lookup(MemberOrBase);
962 if (Result.first != Result.second)
963 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000964
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000965 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000966
Eli Friedman59c04372009-07-29 19:44:27 +0000967 if (Member)
968 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
969 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000970 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000971 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000972 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000973 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000974 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000975 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
976 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000978 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000979
Eli Friedman59c04372009-07-29 19:44:27 +0000980 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
981 RParenLoc, ClassDecl);
982}
983
John McCallb4190042009-11-04 23:02:40 +0000984/// Checks an initializer expression for use of uninitialized fields, such as
985/// containing the field that is being initialized. Returns true if there is an
986/// uninitialized field was used an updates the SourceLocation parameter; false
987/// otherwise.
988static bool InitExprContainsUninitializedFields(const Stmt* S,
989 const FieldDecl* LhsField,
990 SourceLocation* L) {
991 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
992 if (ME) {
993 const NamedDecl* RhsField = ME->getMemberDecl();
994 if (RhsField == LhsField) {
995 // Initializing a field with itself. Throw a warning.
996 // But wait; there are exceptions!
997 // Exception #1: The field may not belong to this record.
998 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
999 const Expr* base = ME->getBase();
1000 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1001 // Even though the field matches, it does not belong to this record.
1002 return false;
1003 }
1004 // None of the exceptions triggered; return true to indicate an
1005 // uninitialized field was used.
1006 *L = ME->getMemberLoc();
1007 return true;
1008 }
1009 }
1010 bool found = false;
1011 for (Stmt::const_child_iterator it = S->child_begin();
1012 it != S->child_end() && found == false;
1013 ++it) {
1014 if (isa<CallExpr>(S)) {
1015 // Do not descend into function calls or constructors, as the use
1016 // of an uninitialized field may be valid. One would have to inspect
1017 // the contents of the function/ctor to determine if it is safe or not.
1018 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1019 // may be safe, depending on what the function/ctor does.
1020 continue;
1021 }
1022 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1023 }
1024 return found;
1025}
1026
Eli Friedman59c04372009-07-29 19:44:27 +00001027Sema::MemInitResult
1028Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1029 unsigned NumArgs, SourceLocation IdLoc,
1030 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001031 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1032 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1033 ExprTemporaries.clear();
1034
John McCallb4190042009-11-04 23:02:40 +00001035 // Diagnose value-uses of fields to initialize themselves, e.g.
1036 // foo(foo)
1037 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001038 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001039 for (unsigned i = 0; i < NumArgs; ++i) {
1040 SourceLocation L;
1041 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1042 // FIXME: Return true in the case when other fields are used before being
1043 // uninitialized. For example, let this field be the i'th field. When
1044 // initializing the i'th field, throw a warning if any of the >= i'th
1045 // fields are used, as they are not yet initialized.
1046 // Right now we are only handling the case where the i'th field uses
1047 // itself in its initializer.
1048 Diag(L, diag::warn_field_is_uninit);
1049 }
1050 }
1051
Eli Friedman59c04372009-07-29 19:44:27 +00001052 bool HasDependentArg = false;
1053 for (unsigned i = 0; i < NumArgs; i++)
1054 HasDependentArg |= Args[i]->isTypeDependent();
1055
1056 CXXConstructorDecl *C = 0;
1057 QualType FieldType = Member->getType();
1058 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1059 FieldType = Array->getElementType();
1060 if (FieldType->isDependentType()) {
1061 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001062 } else if (FieldType->isRecordType()) {
1063 // Member is a record (struct/union/class), so pass the initializer
1064 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001065 if (!HasDependentArg) {
1066 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1067
1068 C = PerformInitializationByConstructor(FieldType,
1069 MultiExprArg(*this,
1070 (void**)Args,
1071 NumArgs),
1072 IdLoc,
1073 SourceRange(IdLoc, RParenLoc),
1074 Member->getDeclName(), IK_Direct,
1075 ConstructorArgs);
1076
1077 if (C) {
1078 // Take over the constructor arguments as our own.
1079 NumArgs = ConstructorArgs.size();
1080 Args = (Expr **)ConstructorArgs.take();
1081 }
1082 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001083 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001084 // The member type is not a record type (or an array of record
1085 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001086 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001087 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1088 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001089 Expr *NewExp;
1090 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001091 if (FieldType->isReferenceType()) {
1092 Diag(IdLoc, diag::err_null_intialized_reference_member)
1093 << Member->getDeclName();
1094 return Diag(Member->getLocation(), diag::note_declared_at);
1095 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001096 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1097 NumArgs = 1;
1098 }
1099 else
1100 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001101 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1102 return true;
1103 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001104 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001105
1106 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1107 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1108 ExprTemporaries.clear();
1109
Eli Friedman59c04372009-07-29 19:44:27 +00001110 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001111 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001112 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001113}
1114
1115Sema::MemInitResult
1116Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1117 unsigned NumArgs, SourceLocation IdLoc,
1118 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1119 bool HasDependentArg = false;
1120 for (unsigned i = 0; i < NumArgs; i++)
1121 HasDependentArg |= Args[i]->isTypeDependent();
1122
1123 if (!BaseType->isDependentType()) {
1124 if (!BaseType->isRecordType())
1125 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1126 << BaseType << SourceRange(IdLoc, RParenLoc);
1127
1128 // C++ [class.base.init]p2:
1129 // [...] Unless the mem-initializer-id names a nonstatic data
1130 // member of the constructor’s class or a direct or virtual base
1131 // of that class, the mem-initializer is ill-formed. A
1132 // mem-initializer-list can initialize a base class using any
1133 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Eli Friedman59c04372009-07-29 19:44:27 +00001135 // First, check for a direct base class.
1136 const CXXBaseSpecifier *DirectBaseSpec = 0;
1137 for (CXXRecordDecl::base_class_const_iterator Base =
1138 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001139 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +00001140 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1141 // We found a direct base of this type. That's what we're
1142 // initializing.
1143 DirectBaseSpec = &*Base;
1144 break;
1145 }
1146 }
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Eli Friedman59c04372009-07-29 19:44:27 +00001148 // Check for a virtual base class.
1149 // FIXME: We might be able to short-circuit this if we know in advance that
1150 // there are no virtual bases.
1151 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1152 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1153 // We haven't found a base yet; search the class hierarchy for a
1154 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1156 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001157 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001158 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001159 Path != Paths.end(); ++Path) {
1160 if (Path->back().Base->isVirtual()) {
1161 VirtualBaseSpec = Path->back().Base;
1162 break;
1163 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001164 }
1165 }
1166 }
Eli Friedman59c04372009-07-29 19:44:27 +00001167
1168 // C++ [base.class.init]p2:
1169 // If a mem-initializer-id is ambiguous because it designates both
1170 // a direct non-virtual base class and an inherited virtual base
1171 // class, the mem-initializer is ill-formed.
1172 if (DirectBaseSpec && VirtualBaseSpec)
1173 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1174 << BaseType << SourceRange(IdLoc, RParenLoc);
1175 // C++ [base.class.init]p2:
1176 // Unless the mem-initializer-id names a nonstatic data membeer of the
1177 // constructor's class ot a direst or virtual base of that class, the
1178 // mem-initializer is ill-formed.
1179 if (!DirectBaseSpec && !VirtualBaseSpec)
1180 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1181 << BaseType << ClassDecl->getNameAsCString()
1182 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001183 }
1184
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001185 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001186 if (!BaseType->isDependentType() && !HasDependentArg) {
1187 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001188 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001189 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1190
1191 C = PerformInitializationByConstructor(BaseType,
1192 MultiExprArg(*this,
1193 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001194 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001195 Name, IK_Direct,
1196 ConstructorArgs);
1197 if (C) {
1198 // Take over the constructor arguments as our own.
1199 NumArgs = ConstructorArgs.size();
1200 Args = (Expr **)ConstructorArgs.take();
1201 }
Eli Friedman59c04372009-07-29 19:44:27 +00001202 }
1203
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001204 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1205 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1206 ExprTemporaries.clear();
1207
Mike Stump1eb44332009-09-09 15:08:12 +00001208 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001209 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001210}
1211
Eli Friedman80c30da2009-11-09 19:20:36 +00001212bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001213Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001214 CXXBaseOrMemberInitializer **Initializers,
1215 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001216 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001217 // We need to build the initializer AST according to order of construction
1218 // and not what user specified in the Initializers list.
1219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1220 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1221 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1222 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001223 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001225 for (unsigned i = 0; i < NumInitializers; i++) {
1226 CXXBaseOrMemberInitializer *Member = Initializers[i];
1227 if (Member->isBaseInitializer()) {
1228 if (Member->getBaseClass()->isDependentType())
1229 HasDependentBaseInit = true;
1230 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1231 } else {
1232 AllBaseFields[Member->getMember()] = Member;
1233 }
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001236 if (HasDependentBaseInit) {
1237 // FIXME. This does not preserve the ordering of the initializers.
1238 // Try (with -Wreorder)
1239 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001240 // template<class X> struct B : A<X> {
1241 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001242 // int x1;
1243 // };
1244 // B<int> x;
1245 // On seeing one dependent type, we should essentially exit this routine
1246 // while preserving user-declared initializer list. When this routine is
1247 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001248 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001250 // If we have a dependent base initialization, we can't determine the
1251 // association between initializers and bases; just dump the known
1252 // initializers into the list, and don't try to deal with other bases.
1253 for (unsigned i = 0; i < NumInitializers; i++) {
1254 CXXBaseOrMemberInitializer *Member = Initializers[i];
1255 if (Member->isBaseInitializer())
1256 AllToInit.push_back(Member);
1257 }
1258 } else {
1259 // Push virtual bases before others.
1260 for (CXXRecordDecl::base_class_iterator VBase =
1261 ClassDecl->vbases_begin(),
1262 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1263 if (VBase->getType()->isDependentType())
1264 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001265 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001266 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001267 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001268 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001269 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001270 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1271 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001272 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001273 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001274 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001275 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001276 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001277 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001278 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001279 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001280 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1281 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1282 << 0 << VBase->getType();
1283 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1284 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001285 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001286 continue;
1287 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001288
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001289 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1290 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1291 Constructor->getLocation(), CtorArgs))
1292 continue;
1293
1294 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1295
Anders Carlsson8db68da2009-11-13 20:11:49 +00001296 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1297 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1298 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001299 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001300 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1301 CtorArgs.takeAs<Expr>(),
1302 CtorArgs.size(), Ctor,
1303 SourceLocation(),
1304 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001305 AllToInit.push_back(Member);
1306 }
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001309 for (CXXRecordDecl::base_class_iterator Base =
1310 ClassDecl->bases_begin(),
1311 E = ClassDecl->bases_end(); Base != E; ++Base) {
1312 // Virtuals are in the virtual base list and already constructed.
1313 if (Base->isVirtual())
1314 continue;
1315 // Skip dependent types.
1316 if (Base->getType()->isDependentType())
1317 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001318 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001319 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001320 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001321 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001322 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001323 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1324 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001325 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001326 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001327 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001328 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001329 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001330 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001331 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001332 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001333 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1334 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1335 << 0 << Base->getType();
1336 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1337 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001338 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001339 continue;
1340 }
1341
1342 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1343 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1344 Constructor->getLocation(), CtorArgs))
1345 continue;
1346
1347 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001348
Anders Carlsson8db68da2009-11-13 20:11:49 +00001349 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1350 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1351 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001352 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001353 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1354 CtorArgs.takeAs<Expr>(),
1355 CtorArgs.size(), Ctor,
1356 SourceLocation(),
1357 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001358 AllToInit.push_back(Member);
1359 }
1360 }
1361 }
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001363 // non-static data members.
1364 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1365 E = ClassDecl->field_end(); Field != E; ++Field) {
1366 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001367 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001368 Field->getType()->getAs<RecordType>()) {
1369 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001370 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001371 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001372 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1373 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1374 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1375 // set to the anonymous union data member used in the initializer
1376 // list.
1377 Value->setMember(*Field);
1378 Value->setAnonUnionMember(*FA);
1379 AllToInit.push_back(Value);
1380 break;
1381 }
1382 }
1383 }
1384 continue;
1385 }
1386 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001387 QualType FT = (*Field)->getType();
1388 if (const RecordType* RT = FT->getAs<RecordType>()) {
1389 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001390 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001391 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001392 FieldRecDecl->getDefaultConstructor(Context))
1393 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1394 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001395 AllToInit.push_back(Value);
1396 continue;
1397 }
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Eli Friedman49c16da2009-11-09 01:05:47 +00001399 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001400 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001401
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001402 QualType FT = Context.getBaseElementType((*Field)->getType());
1403 if (const RecordType* RT = FT->getAs<RecordType>()) {
1404 CXXConstructorDecl *Ctor =
1405 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001406 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001407 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1408 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1409 << 1 << (*Field)->getDeclName();
1410 Diag(Field->getLocation(), diag::note_field_decl);
1411 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1412 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001413 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001414 continue;
1415 }
1416
1417 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1418 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1419 Constructor->getLocation(), CtorArgs))
1420 continue;
1421
Anders Carlsson8db68da2009-11-13 20:11:49 +00001422 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1423 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1424 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001425 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001426 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1427 CtorArgs.size(), Ctor,
1428 SourceLocation(),
1429 SourceLocation());
1430
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001431 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001432 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1433 if (FT.isConstQualified() && Ctor->isTrivial()) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001434 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001435 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1436 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001437 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001438 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001439 }
1440 }
1441 else if (FT->isReferenceType()) {
1442 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001443 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1444 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001445 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001446 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001447 }
1448 else if (FT.isConstQualified()) {
1449 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001450 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1451 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001452 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001453 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 }
1455 }
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001457 NumInitializers = AllToInit.size();
1458 if (NumInitializers > 0) {
1459 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1460 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1461 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001463 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1464 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1465 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1466 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001467
1468 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001469}
1470
Eli Friedman6347f422009-07-21 19:28:10 +00001471static void *GetKeyForTopLevelField(FieldDecl *Field) {
1472 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001473 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001474 if (RT->getDecl()->isAnonymousStructOrUnion())
1475 return static_cast<void *>(RT->getDecl());
1476 }
1477 return static_cast<void *>(Field);
1478}
1479
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001480static void *GetKeyForBase(QualType BaseType) {
1481 if (const RecordType *RT = BaseType->getAs<RecordType>())
1482 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001484 assert(0 && "Unexpected base type!");
1485 return 0;
1486}
1487
Mike Stump1eb44332009-09-09 15:08:12 +00001488static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001489 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001490 // For fields injected into the class via declaration of an anonymous union,
1491 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001492 if (Member->isMemberInitializer()) {
1493 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Eli Friedman49c16da2009-11-09 01:05:47 +00001495 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001496 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001497 // in AnonUnionMember field.
1498 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1499 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001500 if (Field->getDeclContext()->isRecord()) {
1501 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1502 if (RD->isAnonymousStructOrUnion())
1503 return static_cast<void *>(RD);
1504 }
1505 return static_cast<void *>(Field);
1506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001508 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001509}
1510
John McCall6aee6212009-11-04 23:13:52 +00001511/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001512void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001513 SourceLocation ColonLoc,
1514 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001515 if (!ConstructorDecl)
1516 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001517
1518 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
1520 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001521 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Anders Carlssona7b35212009-03-25 02:58:17 +00001523 if (!Constructor) {
1524 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1525 return;
1526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001528 if (!Constructor->isDependentContext()) {
1529 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1530 bool err = false;
1531 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001532 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001533 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1534 void *KeyToMember = GetKeyForMember(Member);
1535 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1536 if (!PrevMember) {
1537 PrevMember = Member;
1538 continue;
1539 }
1540 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001541 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001542 diag::error_multiple_mem_initialization)
1543 << Field->getNameAsString();
1544 else {
1545 Type *BaseClass = Member->getBaseClass();
1546 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001547 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001548 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001549 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001550 }
1551 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1552 << 0;
1553 err = true;
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001556 if (err)
1557 return;
1558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Eli Friedman49c16da2009-11-09 01:05:47 +00001560 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001561 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001562 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001564 if (Constructor->isDependentContext())
1565 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001566
1567 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001568 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001569 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001570 Diagnostic::Ignored)
1571 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001573 // Also issue warning if order of ctor-initializer list does not match order
1574 // of 1) base class declarations and 2) order of non-static data members.
1575 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001577 CXXRecordDecl *ClassDecl
1578 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1579 // Push virtual bases before others.
1580 for (CXXRecordDecl::base_class_iterator VBase =
1581 ClassDecl->vbases_begin(),
1582 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001583 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001585 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1586 E = ClassDecl->bases_end(); Base != E; ++Base) {
1587 // Virtuals are alread in the virtual base list and are constructed
1588 // first.
1589 if (Base->isVirtual())
1590 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001591 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001594 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1595 E = ClassDecl->field_end(); Field != E; ++Field)
1596 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001598 int Last = AllBaseOrMembers.size();
1599 int curIndex = 0;
1600 CXXBaseOrMemberInitializer *PrevMember = 0;
1601 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001602 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001603 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1604 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001605
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001606 for (; curIndex < Last; curIndex++)
1607 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1608 break;
1609 if (curIndex == Last) {
1610 assert(PrevMember && "Member not in member list?!");
1611 // Initializer as specified in ctor-initializer list is out of order.
1612 // Issue a warning diagnostic.
1613 if (PrevMember->isBaseInitializer()) {
1614 // Diagnostics is for an initialized base class.
1615 Type *BaseClass = PrevMember->getBaseClass();
1616 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001617 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001618 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001619 } else {
1620 FieldDecl *Field = PrevMember->getMember();
1621 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001622 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001623 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001624 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001625 // Also the note!
1626 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001627 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001628 diag::note_fieldorbase_initialized_here) << 0
1629 << Field->getNameAsString();
1630 else {
1631 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001632 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001633 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001634 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001635 }
1636 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001637 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001638 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001639 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001640 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001641 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001642}
1643
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001644void
1645Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1646 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1647 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001649 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1650 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1651 if (VBase->getType()->isDependentType())
1652 continue;
1653 // Skip over virtual bases which have trivial destructors.
1654 CXXRecordDecl *BaseClassDecl
1655 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1656 if (BaseClassDecl->hasTrivialDestructor())
1657 continue;
1658 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001659 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001660 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001661
1662 uintptr_t Member =
1663 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001664 | CXXDestructorDecl::VBASE;
1665 AllToDestruct.push_back(Member);
1666 }
1667 for (CXXRecordDecl::base_class_iterator Base =
1668 ClassDecl->bases_begin(),
1669 E = ClassDecl->bases_end(); Base != E; ++Base) {
1670 if (Base->isVirtual())
1671 continue;
1672 if (Base->getType()->isDependentType())
1673 continue;
1674 // Skip over virtual bases which have trivial destructors.
1675 CXXRecordDecl *BaseClassDecl
1676 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1677 if (BaseClassDecl->hasTrivialDestructor())
1678 continue;
1679 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001680 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001681 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001682 uintptr_t Member =
1683 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001684 | CXXDestructorDecl::DRCTNONVBASE;
1685 AllToDestruct.push_back(Member);
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001688 // non-static data members.
1689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1690 E = ClassDecl->field_end(); Field != E; ++Field) {
1691 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001693 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1694 // Skip over virtual bases which have trivial destructors.
1695 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1696 if (FieldClassDecl->hasTrivialDestructor())
1697 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001698 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001699 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001700 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001701 const_cast<CXXDestructorDecl*>(Dtor));
1702 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1703 AllToDestruct.push_back(Member);
1704 }
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001707 unsigned NumDestructions = AllToDestruct.size();
1708 if (NumDestructions > 0) {
1709 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001710 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001711 new (Context) uintptr_t [NumDestructions];
1712 // Insert in reverse order.
1713 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1714 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1715 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1716 }
1717}
1718
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001719void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001720 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001721 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001723 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001724
1725 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001726 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001727 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001728}
1729
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001730namespace {
1731 /// PureVirtualMethodCollector - traverses a class and its superclasses
1732 /// and determines if it has any pure virtual methods.
1733 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1734 ASTContext &Context;
1735
Sebastian Redldfe292d2009-03-22 21:28:55 +00001736 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001737 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001738
1739 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001740 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001742 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001744 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001745 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001746 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001748 MethodList List;
1749 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001751 // Copy the temporary list to methods, and make sure to ignore any
1752 // null entries.
1753 for (size_t i = 0, e = List.size(); i != e; ++i) {
1754 if (List[i])
1755 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001756 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001759 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001761 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1762 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001763 };
Mike Stump1eb44332009-09-09 15:08:12 +00001764
1765 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001766 MethodList& Methods) {
1767 // First, collect the pure virtual methods for the base classes.
1768 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1769 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001770 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001771 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001772 if (BaseDecl && BaseDecl->isAbstract())
1773 Collect(BaseDecl, Methods);
1774 }
1775 }
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001777 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001778 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001780 MethodSetTy OverriddenMethods;
1781 size_t MethodsSize = Methods.size();
1782
Mike Stump1eb44332009-09-09 15:08:12 +00001783 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001784 i != e; ++i) {
1785 // Traverse the record, looking for methods.
1786 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001787 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001788 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001789 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Anders Carlsson27823022009-10-18 19:34:08 +00001791 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001792 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1793 E = MD->end_overridden_methods(); I != E; ++I) {
1794 // Keep track of the overridden methods.
1795 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001796 }
1797 }
1798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
1800 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001801 // overridden.
1802 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1803 if (OverriddenMethods.count(Methods[i]))
1804 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001805 }
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001807 }
1808}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001809
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001810
Mike Stump1eb44332009-09-09 15:08:12 +00001811bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001812 unsigned DiagID, AbstractDiagSelID SelID,
1813 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001814 if (SelID == -1)
1815 return RequireNonAbstractType(Loc, T,
1816 PDiag(DiagID), CurrentRD);
1817 else
1818 return RequireNonAbstractType(Loc, T,
1819 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001820}
1821
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001822bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1823 const PartialDiagnostic &PD,
1824 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001825 if (!getLangOptions().CPlusPlus)
1826 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Anders Carlsson11f21a02009-03-23 19:10:31 +00001828 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001829 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001830 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Ted Kremenek6217b802009-07-29 21:53:49 +00001832 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001833 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001834 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001835 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001837 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001838 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Ted Kremenek6217b802009-07-29 21:53:49 +00001841 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001842 if (!RT)
1843 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001845 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1846 if (!RD)
1847 return false;
1848
Anders Carlssone65a3c82009-03-24 17:23:42 +00001849 if (CurrentRD && CurrentRD != RD)
1850 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001852 if (!RD->isAbstract())
1853 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001855 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001857 // Check if we've already emitted the list of pure virtual functions for this
1858 // class.
1859 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1860 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001862 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
1864 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001865 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1866 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
1868 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001869 MD->getDeclName();
1870 }
1871
1872 if (!PureVirtualClassDiagSet)
1873 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1874 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001876 return true;
1877}
1878
Anders Carlsson8211eff2009-03-24 01:19:16 +00001879namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001880 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001881 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1882 Sema &SemaRef;
1883 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Anders Carlssone65a3c82009-03-24 17:23:42 +00001885 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001886 bool Invalid = false;
1887
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001888 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1889 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001890 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001891
Anders Carlsson8211eff2009-03-24 01:19:16 +00001892 return Invalid;
1893 }
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anders Carlssone65a3c82009-03-24 17:23:42 +00001895 public:
1896 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1897 : SemaRef(SemaRef), AbstractClass(ac) {
1898 Visit(SemaRef.Context.getTranslationUnitDecl());
1899 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001900
Anders Carlssone65a3c82009-03-24 17:23:42 +00001901 bool VisitFunctionDecl(const FunctionDecl *FD) {
1902 if (FD->isThisDeclarationADefinition()) {
1903 // No need to do the check if we're in a definition, because it requires
1904 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001905 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001906 return VisitDeclContext(FD);
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Anders Carlssone65a3c82009-03-24 17:23:42 +00001909 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001910 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001911 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001912 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1913 diag::err_abstract_type_in_decl,
1914 Sema::AbstractReturnType,
1915 AbstractClass);
1916
Mike Stump1eb44332009-09-09 15:08:12 +00001917 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001918 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001919 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001920 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001921 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001922 VD->getOriginalType(),
1923 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001924 Sema::AbstractParamType,
1925 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001926 }
1927
1928 return Invalid;
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Anders Carlssone65a3c82009-03-24 17:23:42 +00001931 bool VisitDecl(const Decl* D) {
1932 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1933 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Anders Carlssone65a3c82009-03-24 17:23:42 +00001935 return false;
1936 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001937 };
1938}
1939
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001940void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001941 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001942 SourceLocation LBrac,
1943 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001944 if (!TagDecl)
1945 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Douglas Gregor42af25f2009-05-11 19:58:34 +00001947 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001948 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001949 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001950 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001951
Chris Lattnerb28317a2009-03-28 19:18:32 +00001952 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001953 if (!RD->isAbstract()) {
1954 // Collect all the pure virtual methods and see if this is an abstract
1955 // class after all.
1956 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001957 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001958 RD->setAbstract(true);
1959 }
Mike Stump1eb44332009-09-09 15:08:12 +00001960
1961 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001962 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Douglas Gregor663b5a02009-10-14 20:14:33 +00001964 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001965 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001966}
1967
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001968/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1969/// special functions, such as the default constructor, copy
1970/// constructor, or destructor, to the given C++ class (C++
1971/// [special]p1). This routine can only be executed just before the
1972/// definition of the class is complete.
1973void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001974 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001975 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001976
Sebastian Redl465226e2009-05-27 22:11:52 +00001977 // FIXME: Implicit declarations have exception specifications, which are
1978 // the union of the specifications of the implicitly called functions.
1979
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001980 if (!ClassDecl->hasUserDeclaredConstructor()) {
1981 // C++ [class.ctor]p5:
1982 // A default constructor for a class X is a constructor of class X
1983 // that can be called without an argument. If there is no
1984 // user-declared constructor for class X, a default constructor is
1985 // implicitly declared. An implicitly-declared default constructor
1986 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001987 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001988 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001989 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001990 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001991 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001992 Context.getFunctionType(Context.VoidTy,
1993 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001994 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001995 /*isExplicit=*/false,
1996 /*isInline=*/true,
1997 /*isImplicitlyDeclared=*/true);
1998 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001999 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002000 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002001 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002002 }
2003
2004 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2005 // C++ [class.copy]p4:
2006 // If the class definition does not explicitly declare a copy
2007 // constructor, one is declared implicitly.
2008
2009 // C++ [class.copy]p5:
2010 // The implicitly-declared copy constructor for a class X will
2011 // have the form
2012 //
2013 // X::X(const X&)
2014 //
2015 // if
2016 bool HasConstCopyConstructor = true;
2017
2018 // -- each direct or virtual base class B of X has a copy
2019 // constructor whose first parameter is of type const B& or
2020 // const volatile B&, and
2021 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2022 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2023 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002024 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002025 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002026 = BaseClassDecl->hasConstCopyConstructor(Context);
2027 }
2028
2029 // -- for all the nonstatic data members of X that are of a
2030 // class type M (or array thereof), each such class type
2031 // has a copy constructor whose first parameter is of type
2032 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002033 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2034 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002035 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002036 QualType FieldType = (*Field)->getType();
2037 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2038 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002039 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002040 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002041 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002042 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002043 = FieldClassDecl->hasConstCopyConstructor(Context);
2044 }
2045 }
2046
Sebastian Redl64b45f72009-01-05 20:52:13 +00002047 // Otherwise, the implicitly declared copy constructor will have
2048 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002049 //
2050 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002051 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002052 if (HasConstCopyConstructor)
2053 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002054 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002055
Sebastian Redl64b45f72009-01-05 20:52:13 +00002056 // An implicitly-declared copy constructor is an inline public
2057 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002058 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002059 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002060 CXXConstructorDecl *CopyConstructor
2061 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002062 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002063 Context.getFunctionType(Context.VoidTy,
2064 &ArgType, 1,
2065 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002066 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002067 /*isExplicit=*/false,
2068 /*isInline=*/true,
2069 /*isImplicitlyDeclared=*/true);
2070 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002071 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002072 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002073
2074 // Add the parameter to the constructor.
2075 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2076 ClassDecl->getLocation(),
2077 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002078 ArgType, /*DInfo=*/0,
2079 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002080 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002081 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002082 }
2083
Sebastian Redl64b45f72009-01-05 20:52:13 +00002084 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2085 // Note: The following rules are largely analoguous to the copy
2086 // constructor rules. Note that virtual bases are not taken into account
2087 // for determining the argument type of the operator. Note also that
2088 // operators taking an object instead of a reference are allowed.
2089 //
2090 // C++ [class.copy]p10:
2091 // If the class definition does not explicitly declare a copy
2092 // assignment operator, one is declared implicitly.
2093 // The implicitly-defined copy assignment operator for a class X
2094 // will have the form
2095 //
2096 // X& X::operator=(const X&)
2097 //
2098 // if
2099 bool HasConstCopyAssignment = true;
2100
2101 // -- each direct base class B of X has a copy assignment operator
2102 // whose parameter is of type const B&, const volatile B& or B,
2103 // and
2104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2105 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002106 assert(!Base->getType()->isDependentType() &&
2107 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002108 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002109 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002110 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002111 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002112 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002113 }
2114
2115 // -- for all the nonstatic data members of X that are of a class
2116 // type M (or array thereof), each such class type has a copy
2117 // assignment operator whose parameter is of type const M&,
2118 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002119 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2120 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002121 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002122 QualType FieldType = (*Field)->getType();
2123 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2124 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002125 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002126 const CXXRecordDecl *FieldClassDecl
2127 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002128 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002129 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002130 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002131 }
2132 }
2133
2134 // Otherwise, the implicitly declared copy assignment operator will
2135 // have the form
2136 //
2137 // X& X::operator=(X&)
2138 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002139 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002140 if (HasConstCopyAssignment)
2141 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002142 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002143
2144 // An implicitly-declared copy assignment operator is an inline public
2145 // member of its class.
2146 DeclarationName Name =
2147 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2148 CXXMethodDecl *CopyAssignment =
2149 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2150 Context.getFunctionType(RetType, &ArgType, 1,
2151 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002152 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002153 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002154 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002155 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002156 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002157
2158 // Add the parameter to the operator.
2159 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2160 ClassDecl->getLocation(),
2161 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002162 ArgType, /*DInfo=*/0,
2163 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002164 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002165
2166 // Don't call addedAssignmentOperator. There is no way to distinguish an
2167 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002168 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002169 }
2170
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002171 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002172 // C++ [class.dtor]p2:
2173 // If a class has no user-declared destructor, a destructor is
2174 // declared implicitly. An implicitly-declared destructor is an
2175 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002176 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002177 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002178 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002179 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002180 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002181 Context.getFunctionType(Context.VoidTy,
2182 0, 0, false, 0),
2183 /*isInline=*/true,
2184 /*isImplicitlyDeclared=*/true);
2185 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002186 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002187 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002188 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002189 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002190}
2191
Douglas Gregor6569d682009-05-27 23:11:45 +00002192void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002193 Decl *D = TemplateD.getAs<Decl>();
2194 if (!D)
2195 return;
2196
2197 TemplateParameterList *Params = 0;
2198 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2199 Params = Template->getTemplateParameters();
2200 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2201 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2202 Params = PartialSpec->getTemplateParameters();
2203 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002204 return;
2205
Douglas Gregor6569d682009-05-27 23:11:45 +00002206 for (TemplateParameterList::iterator Param = Params->begin(),
2207 ParamEnd = Params->end();
2208 Param != ParamEnd; ++Param) {
2209 NamedDecl *Named = cast<NamedDecl>(*Param);
2210 if (Named->getDeclName()) {
2211 S->AddDecl(DeclPtrTy::make(Named));
2212 IdResolver.AddDecl(Named);
2213 }
2214 }
2215}
2216
Douglas Gregor72b505b2008-12-16 21:30:33 +00002217/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2218/// parsing a top-level (non-nested) C++ class, and we are now
2219/// parsing those parts of the given Method declaration that could
2220/// not be parsed earlier (C++ [class.mem]p2), such as default
2221/// arguments. This action should enter the scope of the given
2222/// Method declaration as if we had just parsed the qualified method
2223/// name. However, it should not bring the parameters into scope;
2224/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002225void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002226 if (!MethodD)
2227 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002229 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Douglas Gregor72b505b2008-12-16 21:30:33 +00002231 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002232 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002233 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002234 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2235 SS.setScopeRep(
2236 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002237 ActOnCXXEnterDeclaratorScope(S, SS);
2238}
2239
2240/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2241/// C++ method declaration. We're (re-)introducing the given
2242/// function parameter into scope for use in parsing later parts of
2243/// the method declaration. For example, we could see an
2244/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002245void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002246 if (!ParamD)
2247 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Chris Lattnerb28317a2009-03-28 19:18:32 +00002249 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002250
2251 // If this parameter has an unparsed default argument, clear it out
2252 // to make way for the parsed default argument.
2253 if (Param->hasUnparsedDefaultArg())
2254 Param->setDefaultArg(0);
2255
Chris Lattnerb28317a2009-03-28 19:18:32 +00002256 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002257 if (Param->getDeclName())
2258 IdResolver.AddDecl(Param);
2259}
2260
2261/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2262/// processing the delayed method declaration for Method. The method
2263/// declaration is now considered finished. There may be a separate
2264/// ActOnStartOfFunctionDef action later (not necessarily
2265/// immediately!) for this method, if it was also defined inside the
2266/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002267void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002268 if (!MethodD)
2269 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002271 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Chris Lattnerb28317a2009-03-28 19:18:32 +00002273 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002274 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002275 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002276 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2277 SS.setScopeRep(
2278 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002279 ActOnCXXExitDeclaratorScope(S, SS);
2280
2281 // Now that we have our default arguments, check the constructor
2282 // again. It could produce additional diagnostics or affect whether
2283 // the class has implicitly-declared destructors, among other
2284 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002285 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2286 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002287
2288 // Check the default arguments, which we may have added.
2289 if (!Method->isInvalidDecl())
2290 CheckCXXDefaultArguments(Method);
2291}
2292
Douglas Gregor42a552f2008-11-05 20:51:48 +00002293/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002294/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002295/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002296/// emit diagnostics and set the invalid bit to true. In any case, the type
2297/// will be updated to reflect a well-formed type for the constructor and
2298/// returned.
2299QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2300 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002301 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002302
2303 // C++ [class.ctor]p3:
2304 // A constructor shall not be virtual (10.3) or static (9.4). A
2305 // constructor can be invoked for a const, volatile or const
2306 // volatile object. A constructor shall not be declared const,
2307 // volatile, or const volatile (9.3.2).
2308 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002309 if (!D.isInvalidType())
2310 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2311 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2312 << SourceRange(D.getIdentifierLoc());
2313 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002314 }
2315 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002316 if (!D.isInvalidType())
2317 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2318 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2319 << SourceRange(D.getIdentifierLoc());
2320 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002321 SC = FunctionDecl::None;
2322 }
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Chris Lattner65401802009-04-25 08:28:21 +00002324 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2325 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002326 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002327 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2328 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002329 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002330 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2331 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002332 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002333 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2334 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002335 }
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Douglas Gregor42a552f2008-11-05 20:51:48 +00002337 // Rebuild the function type "R" without any type qualifiers (in
2338 // case any of the errors above fired) and with "void" as the
2339 // return type, since constructors don't have return types. We
2340 // *always* have to do this, because GetTypeForDeclarator will
2341 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002342 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002343 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2344 Proto->getNumArgs(),
2345 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002346}
2347
Douglas Gregor72b505b2008-12-16 21:30:33 +00002348/// CheckConstructor - Checks a fully-formed constructor for
2349/// well-formedness, issuing any diagnostics required. Returns true if
2350/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002351void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002352 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002353 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2354 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002355 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002356
2357 // C++ [class.copy]p3:
2358 // A declaration of a constructor for a class X is ill-formed if
2359 // its first parameter is of type (optionally cv-qualified) X and
2360 // either there are no other parameters or else all other
2361 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002362 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002363 ((Constructor->getNumParams() == 1) ||
2364 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002365 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2366 Constructor->getTemplateSpecializationKind()
2367 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002368 QualType ParamType = Constructor->getParamDecl(0)->getType();
2369 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2370 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002371 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2372 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002373 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002374
2375 // FIXME: Rather that making the constructor invalid, we should endeavor
2376 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002377 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002378 }
2379 }
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor72b505b2008-12-16 21:30:33 +00002381 // Notify the class that we've added a constructor.
2382 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002383}
2384
Mike Stump1eb44332009-09-09 15:08:12 +00002385static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002386FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2387 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2388 FTI.ArgInfo[0].Param &&
2389 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2390}
2391
Douglas Gregor42a552f2008-11-05 20:51:48 +00002392/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2393/// the well-formednes of the destructor declarator @p D with type @p
2394/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002395/// emit diagnostics and set the declarator to invalid. Even if this happens,
2396/// will be updated to reflect a well-formed type for the destructor and
2397/// returned.
2398QualType Sema::CheckDestructorDeclarator(Declarator &D,
2399 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002400 // C++ [class.dtor]p1:
2401 // [...] A typedef-name that names a class is a class-name
2402 // (7.1.3); however, a typedef-name that names a class shall not
2403 // be used as the identifier in the declarator for a destructor
2404 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002405 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002406 if (isa<TypedefType>(DeclaratorType)) {
2407 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002408 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002409 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002410 }
2411
2412 // C++ [class.dtor]p2:
2413 // A destructor is used to destroy objects of its class type. A
2414 // destructor takes no parameters, and no return type can be
2415 // specified for it (not even void). The address of a destructor
2416 // shall not be taken. A destructor shall not be static. A
2417 // destructor can be invoked for a const, volatile or const
2418 // volatile object. A destructor shall not be declared const,
2419 // volatile or const volatile (9.3.2).
2420 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002421 if (!D.isInvalidType())
2422 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2423 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2424 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002425 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002426 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002427 }
Chris Lattner65401802009-04-25 08:28:21 +00002428 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002429 // Destructors don't have return types, but the parser will
2430 // happily parse something like:
2431 //
2432 // class X {
2433 // float ~X();
2434 // };
2435 //
2436 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002437 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2438 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2439 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002440 }
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Chris Lattner65401802009-04-25 08:28:21 +00002442 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2443 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002444 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2446 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002447 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002448 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2449 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002450 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002451 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2452 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002453 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002454 }
2455
2456 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002457 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002458 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2459
2460 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002461 FTI.freeArgs();
2462 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002463 }
2464
Mike Stump1eb44332009-09-09 15:08:12 +00002465 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002466 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002467 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002468 D.setInvalidType();
2469 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002470
2471 // Rebuild the function type "R" without any type qualifiers or
2472 // parameters (in case any of the errors above fired) and with
2473 // "void" as the return type, since destructors don't have return
2474 // types. We *always* have to do this, because GetTypeForDeclarator
2475 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002476 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002477}
2478
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002479/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2480/// well-formednes of the conversion function declarator @p D with
2481/// type @p R. If there are any errors in the declarator, this routine
2482/// will emit diagnostics and return true. Otherwise, it will return
2483/// false. Either way, the type @p R will be updated to reflect a
2484/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002485void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002486 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002487 // C++ [class.conv.fct]p1:
2488 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002489 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002490 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002491 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002492 if (!D.isInvalidType())
2493 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2494 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2495 << SourceRange(D.getIdentifierLoc());
2496 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002497 SC = FunctionDecl::None;
2498 }
Chris Lattner6e475012009-04-25 08:35:12 +00002499 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002500 // Conversion functions don't have return types, but the parser will
2501 // happily parse something like:
2502 //
2503 // class X {
2504 // float operator bool();
2505 // };
2506 //
2507 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002508 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2509 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2510 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002511 }
2512
2513 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002514 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002515 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2516
2517 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002518 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002519 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002520 }
2521
Mike Stump1eb44332009-09-09 15:08:12 +00002522 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002523 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002524 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002525 D.setInvalidType();
2526 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002527
2528 // C++ [class.conv.fct]p4:
2529 // The conversion-type-id shall not represent a function type nor
2530 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002531 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002532 if (ConvType->isArrayType()) {
2533 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2534 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002535 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002536 } else if (ConvType->isFunctionType()) {
2537 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2538 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002539 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002540 }
2541
2542 // Rebuild the function type "R" without any parameters (in case any
2543 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002544 // return type.
2545 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002546 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002547
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002548 // C++0x explicit conversion operators.
2549 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002550 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002551 diag::warn_explicit_conversion_functions)
2552 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002553}
2554
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002555/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2556/// the declaration of the given C++ conversion function. This routine
2557/// is responsible for recording the conversion function in the C++
2558/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002559Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002560 assert(Conversion && "Expected to receive a conversion function declaration");
2561
Douglas Gregor9d350972008-12-12 08:25:50 +00002562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002563
2564 // Make sure we aren't redeclaring the conversion function.
2565 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002566
2567 // C++ [class.conv.fct]p1:
2568 // [...] A conversion function is never used to convert a
2569 // (possibly cv-qualified) object to the (possibly cv-qualified)
2570 // same object type (or a reference to it), to a (possibly
2571 // cv-qualified) base class of that type (or a reference to it),
2572 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002573 // FIXME: Suppress this warning if the conversion function ends up being a
2574 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002575 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002577 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002578 ConvType = ConvTypeRef->getPointeeType();
2579 if (ConvType->isRecordType()) {
2580 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2581 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002582 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002583 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002584 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002585 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002586 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002587 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002588 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002589 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002590 }
2591
Douglas Gregor70316a02008-12-26 15:00:45 +00002592 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002593 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002594 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002595 = Conversion->getDescribedFunctionTemplate())
2596 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002597 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002598 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002599 Conv = Conversions->function_begin(),
2600 ConvEnd = Conversions->function_end();
2601 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002602 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002603 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002604 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002605 }
2606 }
2607 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002608 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002609 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002610 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002611 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002612 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002613
Chris Lattnerb28317a2009-03-28 19:18:32 +00002614 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002615}
2616
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002617//===----------------------------------------------------------------------===//
2618// Namespace Handling
2619//===----------------------------------------------------------------------===//
2620
2621/// ActOnStartNamespaceDef - This is called at the start of a namespace
2622/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002623Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2624 SourceLocation IdentLoc,
2625 IdentifierInfo *II,
2626 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002627 NamespaceDecl *Namespc =
2628 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2629 Namespc->setLBracLoc(LBrace);
2630
2631 Scope *DeclRegionScope = NamespcScope->getParent();
2632
2633 if (II) {
2634 // C++ [namespace.def]p2:
2635 // The identifier in an original-namespace-definition shall not have been
2636 // previously defined in the declarative region in which the
2637 // original-namespace-definition appears. The identifier in an
2638 // original-namespace-definition is the name of the namespace. Subsequently
2639 // in that declarative region, it is treated as an original-namespace-name.
2640
John McCallf36e02d2009-10-09 21:13:30 +00002641 NamedDecl *PrevDecl
2642 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Douglas Gregor44b43212008-12-11 16:49:14 +00002644 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2645 // This is an extended namespace definition.
2646 // Attach this namespace decl to the chain of extended namespace
2647 // definitions.
2648 OrigNS->setNextNamespace(Namespc);
2649 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002650
Mike Stump1eb44332009-09-09 15:08:12 +00002651 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002652 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002653 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002654 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002655 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002656 } else if (PrevDecl) {
2657 // This is an invalid name redefinition.
2658 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2659 << Namespc->getDeclName();
2660 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2661 Namespc->setInvalidDecl();
2662 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002663 } else if (II->isStr("std") &&
2664 CurContext->getLookupContext()->isTranslationUnit()) {
2665 // This is the first "real" definition of the namespace "std", so update
2666 // our cache of the "std" namespace to point at this definition.
2667 if (StdNamespace) {
2668 // We had already defined a dummy namespace "std". Link this new
2669 // namespace definition to the dummy namespace "std".
2670 StdNamespace->setNextNamespace(Namespc);
2671 StdNamespace->setLocation(IdentLoc);
2672 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2673 }
2674
2675 // Make our StdNamespace cache point at the first real definition of the
2676 // "std" namespace.
2677 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002678 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002679
2680 PushOnScopeChains(Namespc, DeclRegionScope);
2681 } else {
John McCall9aeed322009-10-01 00:25:31 +00002682 // Anonymous namespaces.
2683
2684 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2685 // behaves as if it were replaced by
2686 // namespace unique { /* empty body */ }
2687 // using namespace unique;
2688 // namespace unique { namespace-body }
2689 // where all occurrences of 'unique' in a translation unit are
2690 // replaced by the same identifier and this identifier differs
2691 // from all other identifiers in the entire program.
2692
2693 // We just create the namespace with an empty name and then add an
2694 // implicit using declaration, just like the standard suggests.
2695 //
2696 // CodeGen enforces the "universally unique" aspect by giving all
2697 // declarations semantically contained within an anonymous
2698 // namespace internal linkage.
2699
2700 assert(Namespc->isAnonymousNamespace());
2701 CurContext->addDecl(Namespc);
2702
2703 UsingDirectiveDecl* UD
2704 = UsingDirectiveDecl::Create(Context, CurContext,
2705 /* 'using' */ LBrace,
2706 /* 'namespace' */ SourceLocation(),
2707 /* qualifier */ SourceRange(),
2708 /* NNS */ NULL,
2709 /* identifier */ SourceLocation(),
2710 Namespc,
2711 /* Ancestor */ CurContext);
2712 UD->setImplicit();
2713 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002714 }
2715
2716 // Although we could have an invalid decl (i.e. the namespace name is a
2717 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002718 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2719 // for the namespace has the declarations that showed up in that particular
2720 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002721 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002722 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002723}
2724
2725/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2726/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002727void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2728 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002729 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2730 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2731 Namespc->setRBracLoc(RBrace);
2732 PopDeclContext();
2733}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002734
Chris Lattnerb28317a2009-03-28 19:18:32 +00002735Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2736 SourceLocation UsingLoc,
2737 SourceLocation NamespcLoc,
2738 const CXXScopeSpec &SS,
2739 SourceLocation IdentLoc,
2740 IdentifierInfo *NamespcName,
2741 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002742 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2743 assert(NamespcName && "Invalid NamespcName.");
2744 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002745 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002746
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002747 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002748
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002749 // Lookup namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002750 LookupResult R;
2751 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002752 if (R.isAmbiguous()) {
2753 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002754 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002755 }
John McCallf36e02d2009-10-09 21:13:30 +00002756 if (!R.empty()) {
2757 NamedDecl *NS = R.getFoundDecl();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002758 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002759 // C++ [namespace.udir]p1:
2760 // A using-directive specifies that the names in the nominated
2761 // namespace can be used in the scope in which the
2762 // using-directive appears after the using-directive. During
2763 // unqualified name lookup (3.4.1), the names appear as if they
2764 // were declared in the nearest enclosing namespace which
2765 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002766 // namespace. [Note: in this context, "contains" means "contains
2767 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002768
2769 // Find enclosing context containing both using-directive and
2770 // nominated namespace.
2771 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2772 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2773 CommonAncestor = CommonAncestor->getParent();
2774
Mike Stump1eb44332009-09-09 15:08:12 +00002775 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002776 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002777 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002778 SS.getRange(),
2779 (NestedNameSpecifier *)SS.getScopeRep(),
2780 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002781 cast<NamespaceDecl>(NS),
2782 CommonAncestor);
2783 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002784 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002785 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002786 }
2787
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002788 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002789 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002790 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002791}
2792
2793void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2794 // If scope has associated entity, then using directive is at namespace
2795 // or translation unit scope. We add UsingDirectiveDecls, into
2796 // it's lookup structure.
2797 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002798 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002799 else
2800 // Otherwise it is block-sope. using-directives will affect lookup
2801 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002802 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002803}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002804
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002805
2806Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002807 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002808 SourceLocation UsingLoc,
2809 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002810 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002811 AttributeList *AttrList,
2812 bool IsTypeName) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002813 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregor12c118a2009-11-04 16:30:06 +00002815 switch (Name.getKind()) {
2816 case UnqualifiedId::IK_Identifier:
2817 case UnqualifiedId::IK_OperatorFunctionId:
2818 case UnqualifiedId::IK_ConversionFunctionId:
2819 break;
2820
2821 case UnqualifiedId::IK_ConstructorName:
2822 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2823 << SS.getRange();
2824 return DeclPtrTy();
2825
2826 case UnqualifiedId::IK_DestructorName:
2827 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2828 << SS.getRange();
2829 return DeclPtrTy();
2830
2831 case UnqualifiedId::IK_TemplateId:
2832 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2833 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2834 return DeclPtrTy();
2835 }
2836
2837 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2838 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2839 Name.getSourceRange().getBegin(),
2840 TargetName, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002841 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002842 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002843 UD->setAccess(AS);
2844 }
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Anders Carlssonc72160b2009-08-28 05:40:36 +00002846 return DeclPtrTy::make(UD);
2847}
2848
2849NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2850 const CXXScopeSpec &SS,
2851 SourceLocation IdentLoc,
2852 DeclarationName Name,
2853 AttributeList *AttrList,
2854 bool IsTypeName) {
2855 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2856 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002857
Anders Carlsson550b14b2009-08-28 05:49:21 +00002858 // FIXME: We ignore attributes for now.
2859 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002861 if (SS.isEmpty()) {
2862 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002863 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002864 }
Mike Stump1eb44332009-09-09 15:08:12 +00002865
2866 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002867 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2868
John McCallaf8e6ed2009-11-12 03:15:40 +00002869 DeclContext *LookupContext = computeDeclContext(SS);
2870 if (!LookupContext) {
Anders Carlsson550b14b2009-08-28 05:49:21 +00002871 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2872 SS.getRange(), NNS,
2873 IdentLoc, Name, IsTypeName);
2874 }
Mike Stump1eb44332009-09-09 15:08:12 +00002875
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002876 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2877 // C++0x N2914 [namespace.udecl]p3:
2878 // A using-declaration used as a member-declaration shall refer to a member
2879 // of a base class of the class being defined, shall refer to a member of an
2880 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002881 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002882 // a member of a base class of the class being defined.
John McCallaf8e6ed2009-11-12 03:15:40 +00002883
2884 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2885 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002886 Diag(SS.getRange().getBegin(),
2887 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2888 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002889 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002890 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002891 } else {
2892 // C++0x N2914 [namespace.udecl]p8:
2893 // A using-declaration for a class member shall be a member-declaration.
John McCallaf8e6ed2009-11-12 03:15:40 +00002894 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002895 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002896 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002897 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002898 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002899 }
2900
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002901 // Lookup target name.
John McCallf36e02d2009-10-09 21:13:30 +00002902 LookupResult R;
2903 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002904
John McCallf36e02d2009-10-09 21:13:30 +00002905 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002906 Diag(IdentLoc, diag::err_no_member)
2907 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002908 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002909 }
2910
John McCallf36e02d2009-10-09 21:13:30 +00002911 // FIXME: handle ambiguity?
2912 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002914 if (IsTypeName && !isa<TypeDecl>(ND)) {
2915 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002916 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002917 }
2918
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002919 // C++0x N2914 [namespace.udecl]p6:
2920 // A using-declaration shall not name a namespace.
2921 if (isa<NamespaceDecl>(ND)) {
2922 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2923 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002924 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002925 }
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Anders Carlssonc72160b2009-08-28 05:40:36 +00002927 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2928 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002929}
2930
Anders Carlsson81c85c42009-03-28 23:53:49 +00002931/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2932/// is a namespace alias, returns the namespace it points to.
2933static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2934 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2935 return AD->getNamespace();
2936 return dyn_cast_or_null<NamespaceDecl>(D);
2937}
2938
Mike Stump1eb44332009-09-09 15:08:12 +00002939Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002940 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002941 SourceLocation AliasLoc,
2942 IdentifierInfo *Alias,
2943 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002944 SourceLocation IdentLoc,
2945 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Anders Carlsson81c85c42009-03-28 23:53:49 +00002947 // Lookup the namespace name.
John McCallf36e02d2009-10-09 21:13:30 +00002948 LookupResult R;
2949 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlsson81c85c42009-03-28 23:53:49 +00002950
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002951 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002952 if (NamedDecl *PrevDecl
2953 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002954 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002955 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002956 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00002957 if (!R.isAmbiguous() && !R.empty() &&
2958 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00002959 return DeclPtrTy();
2960 }
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002962 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2963 diag::err_redefinition_different_kind;
2964 Diag(AliasLoc, DiagID) << Alias;
2965 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002966 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002967 }
2968
Anders Carlsson5721c682009-03-28 06:42:02 +00002969 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002970 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002971 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
John McCallf36e02d2009-10-09 21:13:30 +00002974 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00002975 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002976 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002977 }
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002979 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002980 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2981 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002982 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00002983 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002984
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002985 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002986 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002987}
2988
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002989void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2990 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002991 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2992 !Constructor->isUsed()) &&
2993 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Eli Friedman80c30da2009-11-09 19:20:36 +00002995 CXXRecordDecl *ClassDecl
2996 = cast<CXXRecordDecl>(Constructor->getDeclContext());
2997 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00002998
Eli Friedman80c30da2009-11-09 19:20:36 +00002999 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3000 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3001 << Context.getTagDeclType(ClassDecl);
3002 Constructor->setInvalidDecl();
3003 } else {
3004 Constructor->setUsed();
3005 }
Eli Friedman49c16da2009-11-09 01:05:47 +00003006 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003007}
3008
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003009void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003010 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003011 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3012 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003014 CXXRecordDecl *ClassDecl
3015 = cast<CXXRecordDecl>(Destructor->getDeclContext());
3016 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3017 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003018 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003019 // implicitly defined, all the implicitly-declared default destructors
3020 // for its base class and its non-static data members shall have been
3021 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003022 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3023 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003024 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003025 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003026 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003027 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003028 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3029 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3030 else
Mike Stump1eb44332009-09-09 15:08:12 +00003031 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003032 "DefineImplicitDestructor - missing dtor in a base class");
3033 }
3034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003036 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3037 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003038 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3039 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3040 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003041 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003042 CXXRecordDecl *FieldClassDecl
3043 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3044 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003045 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003046 const_cast<CXXDestructorDecl*>(
3047 FieldClassDecl->getDestructor(Context)))
3048 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3049 else
Mike Stump1eb44332009-09-09 15:08:12 +00003050 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003051 "DefineImplicitDestructor - missing dtor in class of a data member");
3052 }
3053 }
3054 }
3055 Destructor->setUsed();
3056}
3057
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003058void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3059 CXXMethodDecl *MethodDecl) {
3060 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3061 MethodDecl->getOverloadedOperator() == OO_Equal &&
3062 !MethodDecl->isUsed()) &&
3063 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003065 CXXRecordDecl *ClassDecl
3066 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003067
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003068 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003069 // Before the implicitly-declared copy assignment operator for a class is
3070 // implicitly defined, all implicitly-declared copy assignment operators
3071 // for its direct base classes and its nonstatic data members shall have
3072 // been implicitly defined.
3073 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3075 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003076 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003077 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003078 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003079 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3080 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3081 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3083 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003084 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3085 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3086 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003087 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003088 CXXRecordDecl *FieldClassDecl
3089 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003090 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003091 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3092 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003093 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003094 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003095 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3096 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003097 Diag(CurrentLocation, diag::note_first_required_here);
3098 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003099 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003100 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003101 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3102 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003103 Diag(CurrentLocation, diag::note_first_required_here);
3104 err = true;
3105 }
3106 }
3107 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003108 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003109}
3110
3111CXXMethodDecl *
3112Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3113 CXXRecordDecl *ClassDecl) {
3114 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3115 QualType RHSType(LHSType);
3116 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003117 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003118 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003119 RHSType = Context.getCVRQualifiedType(RHSType,
3120 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003121 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3122 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003123 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003124 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3125 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003126 SourceLocation()));
3127 Expr *Args[2] = { &*LHS, &*RHS };
3128 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003129 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003130 CandidateSet);
3131 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003132 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003133 ClassDecl->getLocation(), Best) == OR_Success)
3134 return cast<CXXMethodDecl>(Best->Function);
3135 assert(false &&
3136 "getAssignOperatorMethod - copy assignment operator method not found");
3137 return 0;
3138}
3139
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003140void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3141 CXXConstructorDecl *CopyConstructor,
3142 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003143 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003144 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3145 !CopyConstructor->isUsed()) &&
3146 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003148 CXXRecordDecl *ClassDecl
3149 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3150 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003151 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003152 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003153 // implicitly defined, all the implicitly-declared copy constructors
3154 // for its base class and its non-static data members shall have been
3155 // implicitly defined.
3156 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3157 Base != ClassDecl->bases_end(); ++Base) {
3158 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003159 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003160 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003161 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003162 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003163 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003164 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3165 FieldEnd = ClassDecl->field_end();
3166 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003167 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3168 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3169 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003170 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003171 CXXRecordDecl *FieldClassDecl
3172 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003173 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003174 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003175 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003176 }
3177 }
3178 CopyConstructor->setUsed();
3179}
3180
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003181Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003182Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003183 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003184 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003185 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Douglas Gregor39da0b82009-09-09 23:08:42 +00003187 // C++ [class.copy]p15:
3188 // Whenever a temporary class object is copied using a copy constructor, and
3189 // this object and the copy have the same cv-unqualified type, an
3190 // implementation is permitted to treat the original and the copy as two
3191 // different ways of referring to the same object and not perform a copy at
3192 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003194 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003195 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003196 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003197 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3198 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003199 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3200 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3201 E = ICE->getSubExpr();
3202
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003203 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3204 Elidable = true;
3205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
3207 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003208 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003209}
3210
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003211/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3212/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003213Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003214Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3215 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003216 MultiExprArg ExprArgs) {
3217 unsigned NumExprs = ExprArgs.size();
3218 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Douglas Gregor39da0b82009-09-09 23:08:42 +00003220 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3221 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003222}
3223
Anders Carlssone7624a72009-08-27 05:08:22 +00003224Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003225Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3226 QualType Ty,
3227 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003228 MultiExprArg Args,
3229 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003230 unsigned NumExprs = Args.size();
3231 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Douglas Gregor39da0b82009-09-09 23:08:42 +00003233 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3234 TyBeginLoc, Exprs,
3235 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003236}
3237
3238
Mike Stump1eb44332009-09-09 15:08:12 +00003239bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003240 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003241 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003242 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003243 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003244 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003245 if (TempResult.isInvalid())
3246 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003248 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003249 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003250 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003251 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Anders Carlssonfe2de492009-08-25 05:18:00 +00003253 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003254}
3255
Mike Stump1eb44332009-09-09 15:08:12 +00003256void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003257 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003258 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003259 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003260 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003261 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003262 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003263}
3264
Mike Stump1eb44332009-09-09 15:08:12 +00003265/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003266/// ActOnDeclarator, when a C++ direct initializer is present.
3267/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003268void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3269 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003270 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003271 SourceLocation *CommaLocs,
3272 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003273 unsigned NumExprs = Exprs.size();
3274 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003275 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003276
3277 // If there is no declaration, there was an error parsing it. Just ignore
3278 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003279 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003280 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003281
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003282 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3283 if (!VDecl) {
3284 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3285 RealDecl->setInvalidDecl();
3286 return;
3287 }
3288
Douglas Gregor83ddad32009-08-26 21:14:46 +00003289 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003290 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003291 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3292 //
3293 // Clients that want to distinguish between the two forms, can check for
3294 // direct initializer using VarDecl::hasCXXDirectInitializer().
3295 // A major benefit is that clients that don't particularly care about which
3296 // exactly form was it (like the CodeGen) can handle both cases without
3297 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003298
Douglas Gregor83ddad32009-08-26 21:14:46 +00003299 // If either the declaration has a dependent type or if any of the expressions
3300 // is type-dependent, we represent the initialization via a ParenListExpr for
3301 // later use during template instantiation.
3302 if (VDecl->getType()->isDependentType() ||
3303 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3304 // Let clients know that initialization was done with a direct initializer.
3305 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Douglas Gregor83ddad32009-08-26 21:14:46 +00003307 // Store the initialization expressions as a ParenListExpr.
3308 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003309 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003310 new (Context) ParenListExpr(Context, LParenLoc,
3311 (Expr **)Exprs.release(),
3312 NumExprs, RParenLoc));
3313 return;
3314 }
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Douglas Gregor83ddad32009-08-26 21:14:46 +00003316
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003317 // C++ 8.5p11:
3318 // The form of initialization (using parentheses or '=') is generally
3319 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003320 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003321 QualType DeclInitType = VDecl->getType();
3322 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003323 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003324
Douglas Gregor615c5d42009-03-24 16:43:20 +00003325 // FIXME: This isn't the right place to complete the type.
3326 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3327 diag::err_typecheck_decl_incomplete_type)) {
3328 VDecl->setInvalidDecl();
3329 return;
3330 }
3331
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003332 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003333 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3334
Douglas Gregor18fe5682008-11-03 20:45:27 +00003335 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003336 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003337 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003338 VDecl->getLocation(),
3339 SourceRange(VDecl->getLocation(),
3340 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003341 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003342 IK_Direct,
3343 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003344 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003345 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003346 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003347 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003348 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003349 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003350 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003351 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003352 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003353 return;
3354 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003355
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003356 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003357 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3358 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003359 RealDecl->setInvalidDecl();
3360 return;
3361 }
3362
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003363 // Let clients know that initialization was done with a direct initializer.
3364 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003365
3366 assert(NumExprs == 1 && "Expected 1 expression");
3367 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003368 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3369 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003370}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003371
Douglas Gregor39da0b82009-09-09 23:08:42 +00003372/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3373/// may occur as part of direct-initialization or copy-initialization.
3374///
3375/// \param ClassType the type of the object being initialized, which must have
3376/// class type.
3377///
3378/// \param ArgsPtr the arguments provided to initialize the object
3379///
3380/// \param Loc the source location where the initialization occurs
3381///
3382/// \param Range the source range that covers the entire initialization
3383///
3384/// \param InitEntity the name of the entity being initialized, if known
3385///
3386/// \param Kind the type of initialization being performed
3387///
3388/// \param ConvertedArgs a vector that will be filled in with the
3389/// appropriately-converted arguments to the constructor (if initialization
3390/// succeeded).
3391///
3392/// \returns the constructor used to initialize the object, if successful.
3393/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003394CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003395Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003396 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003397 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003398 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003399 InitializationKind Kind,
3400 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003401 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003402 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003403 Expr **Args = (Expr **)ArgsPtr.get();
3404 unsigned NumArgs = ArgsPtr.size();
3405
Mike Stump1eb44332009-09-09 15:08:12 +00003406 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003407 // If the initialization is direct-initialization, or if it is
3408 // copy-initialization where the cv-unqualified version of the
3409 // source type is the same class as, or a derived class of, the
3410 // class of the destination, constructors are considered. The
3411 // applicable constructors are enumerated (13.3.1.3), and the
3412 // best one is chosen through overload resolution (13.3). The
3413 // constructor so selected is called to initialize the object,
3414 // with the initializer expression(s) as its argument(s). If no
3415 // constructor applies, or the overload resolution is ambiguous,
3416 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003417 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3418 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003419
3420 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003421 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003422 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00003423 Context.getCanonicalType(ClassType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003424 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003425 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003426 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003427 // Find the constructor (which may be a template).
3428 CXXConstructorDecl *Constructor = 0;
3429 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3430 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003431 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003432 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3433 else
3434 Constructor = cast<CXXConstructorDecl>(*Con);
3435
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003436 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003437 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003438 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003439 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3440 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003441 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003442 Args, NumArgs, CandidateSet);
3443 else
3444 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3445 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003446 }
3447
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003448 // FIXME: When we decide not to synthesize the implicitly-declared
3449 // constructors, we'll need to make them appear here.
3450
Douglas Gregor18fe5682008-11-03 20:45:27 +00003451 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003452 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003453 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003454 // We found a constructor. Break out so that we can convert the arguments
3455 // appropriately.
3456 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Douglas Gregor18fe5682008-11-03 20:45:27 +00003458 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003459 if (InitEntity)
3460 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003461 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003462 else
3463 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003464 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003465 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003466 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Douglas Gregor18fe5682008-11-03 20:45:27 +00003468 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003469 if (InitEntity)
3470 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3471 else
3472 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003473 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3474 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003475
3476 case OR_Deleted:
3477 if (InitEntity)
3478 Diag(Loc, diag::err_ovl_deleted_init)
3479 << Best->Function->isDeleted()
3480 << InitEntity << Range;
3481 else
3482 Diag(Loc, diag::err_ovl_deleted_init)
3483 << Best->Function->isDeleted()
3484 << InitEntity << Range;
3485 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3486 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003487 }
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregor39da0b82009-09-09 23:08:42 +00003489 // Convert the arguments, fill in default arguments, etc.
3490 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3491 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3492 return 0;
3493
3494 return Constructor;
3495}
3496
3497/// \brief Given a constructor and the set of arguments provided for the
3498/// constructor, convert the arguments and add any required default arguments
3499/// to form a proper call to this constructor.
3500///
3501/// \returns true if an error occurred, false otherwise.
3502bool
3503Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3504 MultiExprArg ArgsPtr,
3505 SourceLocation Loc,
3506 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3507 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3508 unsigned NumArgs = ArgsPtr.size();
3509 Expr **Args = (Expr **)ArgsPtr.get();
3510
3511 const FunctionProtoType *Proto
3512 = Constructor->getType()->getAs<FunctionProtoType>();
3513 assert(Proto && "Constructor without a prototype?");
3514 unsigned NumArgsInProto = Proto->getNumArgs();
3515 unsigned NumArgsToCheck = NumArgs;
3516
3517 // If too few arguments are available, we'll fill in the rest with defaults.
3518 if (NumArgs < NumArgsInProto) {
3519 NumArgsToCheck = NumArgsInProto;
3520 ConvertedArgs.reserve(NumArgsInProto);
3521 } else {
3522 ConvertedArgs.reserve(NumArgs);
3523 if (NumArgs > NumArgsInProto)
3524 NumArgsToCheck = NumArgsInProto;
3525 }
3526
3527 // Convert arguments
3528 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3529 QualType ProtoArgType = Proto->getArgType(i);
3530
3531 Expr *Arg;
3532 if (i < NumArgs) {
3533 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003534
3535 // Pass the argument.
3536 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3537 return true;
3538
3539 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003540 } else {
3541 ParmVarDecl *Param = Constructor->getParamDecl(i);
3542
3543 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3544 if (DefArg.isInvalid())
3545 return true;
3546
3547 Arg = DefArg.takeAs<Expr>();
3548 }
3549
3550 ConvertedArgs.push_back(Arg);
3551 }
3552
3553 // If this is a variadic call, handle args passed through "...".
3554 if (Proto->isVariadic()) {
3555 // Promote the arguments (C99 6.5.2.2p7).
3556 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3557 Expr *Arg = Args[i];
3558 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3559 return true;
3560
3561 ConvertedArgs.push_back(Arg);
3562 Args[i] = 0;
3563 }
3564 }
3565
3566 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003567}
3568
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003569/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3570/// determine whether they are reference-related,
3571/// reference-compatible, reference-compatible with added
3572/// qualification, or incompatible, for use in C++ initialization by
3573/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3574/// type, and the first type (T1) is the pointee type of the reference
3575/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003576Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003577Sema::CompareReferenceRelationship(SourceLocation Loc,
3578 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003579 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003580 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003581 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003582 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003583
Douglas Gregor393896f2009-11-05 13:06:35 +00003584 QualType T1 = Context.getCanonicalType(OrigT1);
3585 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003586 QualType UnqualT1 = T1.getUnqualifiedType();
3587 QualType UnqualT2 = T2.getUnqualifiedType();
3588
3589 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003590 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003591 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003592 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003593 if (UnqualT1 == UnqualT2)
3594 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003595 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3596 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3597 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003598 DerivedToBase = true;
3599 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003600 return Ref_Incompatible;
3601
3602 // At this point, we know that T1 and T2 are reference-related (at
3603 // least).
3604
3605 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003606 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003607 // reference-related to T2 and cv1 is the same cv-qualification
3608 // as, or greater cv-qualification than, cv2. For purposes of
3609 // overload resolution, cases for which cv1 is greater
3610 // cv-qualification than cv2 are identified as
3611 // reference-compatible with added qualification (see 13.3.3.2).
3612 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3613 return Ref_Compatible;
3614 else if (T1.isMoreQualifiedThan(T2))
3615 return Ref_Compatible_With_Added_Qualification;
3616 else
3617 return Ref_Related;
3618}
3619
3620/// CheckReferenceInit - Check the initialization of a reference
3621/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3622/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003623/// list), and DeclType is the type of the declaration. When ICS is
3624/// non-null, this routine will compute the implicit conversion
3625/// sequence according to C++ [over.ics.ref] and will not produce any
3626/// diagnostics; when ICS is null, it will emit diagnostics when any
3627/// errors are found. Either way, a return value of true indicates
3628/// that there was a failure, a return value of false indicates that
3629/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003630///
3631/// When @p SuppressUserConversions, user-defined conversions are
3632/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003633/// When @p AllowExplicit, we also permit explicit user-defined
3634/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003635/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003636bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003637Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003638 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003639 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003640 bool AllowExplicit, bool ForceRValue,
3641 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003642 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3643
Ted Kremenek6217b802009-07-29 21:53:49 +00003644 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003645 QualType T2 = Init->getType();
3646
Douglas Gregor904eed32008-11-10 20:40:00 +00003647 // If the initializer is the address of an overloaded function, try
3648 // to resolve the overloaded function. If all goes well, T2 is the
3649 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003650 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003651 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003652 ICS != 0);
3653 if (Fn) {
3654 // Since we're performing this reference-initialization for
3655 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003656 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003657 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003658 return true;
3659
Anders Carlsson96ad5332009-10-21 17:16:23 +00003660 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003661 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003662
3663 T2 = Fn->getType();
3664 }
3665 }
3666
Douglas Gregor15da57e2008-10-29 02:00:59 +00003667 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003668 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003669 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003670 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3671 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003672 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003673 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003674
3675 // Most paths end in a failed conversion.
3676 if (ICS)
3677 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003678
3679 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003680 // A reference to type "cv1 T1" is initialized by an expression
3681 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003682
3683 // -- If the initializer expression
3684
Sebastian Redla9845802009-03-29 15:27:50 +00003685 // Rvalue references cannot bind to lvalues (N2812).
3686 // There is absolutely no situation where they can. In particular, note that
3687 // this is ill-formed, even if B has a user-defined conversion to A&&:
3688 // B b;
3689 // A&& r = b;
3690 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3691 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003692 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003693 << Init->getSourceRange();
3694 return true;
3695 }
3696
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003697 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003698 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3699 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003700 //
3701 // Note that the bit-field check is skipped if we are just computing
3702 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003703 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003704 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003705 BindsDirectly = true;
3706
Douglas Gregor15da57e2008-10-29 02:00:59 +00003707 if (ICS) {
3708 // C++ [over.ics.ref]p1:
3709 // When a parameter of reference type binds directly (8.5.3)
3710 // to an argument expression, the implicit conversion sequence
3711 // is the identity conversion, unless the argument expression
3712 // has a type that is a derived class of the parameter type,
3713 // in which case the implicit conversion sequence is a
3714 // derived-to-base Conversion (13.3.3.1).
3715 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3716 ICS->Standard.First = ICK_Identity;
3717 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3718 ICS->Standard.Third = ICK_Identity;
3719 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3720 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003721 ICS->Standard.ReferenceBinding = true;
3722 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003723 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003724 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003725
3726 // Nothing more to do: the inaccessibility/ambiguity check for
3727 // derived-to-base conversions is suppressed when we're
3728 // computing the implicit conversion sequence (C++
3729 // [over.best.ics]p2).
3730 return false;
3731 } else {
3732 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003733 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3734 if (DerivedToBase)
3735 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003736 else if(CheckExceptionSpecCompatibility(Init, T1))
3737 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003738 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003739 }
3740 }
3741
3742 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003743 // implicitly converted to an lvalue of type "cv3 T3,"
3744 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003745 // 92) (this conversion is selected by enumerating the
3746 // applicable conversion functions (13.3.1.6) and choosing
3747 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003748 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003749 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003750 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003751 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003752
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003753 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003754 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003755 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003756 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003757 = Conversions->function_begin();
3758 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003759 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003760 = dyn_cast<FunctionTemplateDecl>(*Func);
3761 CXXConversionDecl *Conv;
3762 if (ConvTemplate)
3763 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3764 else
3765 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003766
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003767 // If the conversion function doesn't return a reference type,
3768 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003769 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003770 (AllowExplicit || !Conv->isExplicit())) {
3771 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003772 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003773 CandidateSet);
3774 else
3775 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3776 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003777 }
3778
3779 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003780 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003781 case OR_Success:
3782 // This is a direct binding.
3783 BindsDirectly = true;
3784
3785 if (ICS) {
3786 // C++ [over.ics.ref]p1:
3787 //
3788 // [...] If the parameter binds directly to the result of
3789 // applying a conversion function to the argument
3790 // expression, the implicit conversion sequence is a
3791 // user-defined conversion sequence (13.3.3.1.2), with the
3792 // second standard conversion sequence either an identity
3793 // conversion or, if the conversion function returns an
3794 // entity of a type that is a derived class of the parameter
3795 // type, a derived-to-base Conversion.
3796 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3797 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3798 ICS->UserDefined.After = Best->FinalConversion;
3799 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003800 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003801 assert(ICS->UserDefined.After.ReferenceBinding &&
3802 ICS->UserDefined.After.DirectBinding &&
3803 "Expected a direct reference binding!");
3804 return false;
3805 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003806 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003807 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003808 CastExpr::CK_UserDefinedConversion,
3809 cast<CXXMethodDecl>(Best->Function),
3810 Owned(Init));
3811 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003812
3813 if (CheckExceptionSpecCompatibility(Init, T1))
3814 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003815 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3816 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003817 }
3818 break;
3819
3820 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003821 if (ICS) {
3822 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3823 Cand != CandidateSet.end(); ++Cand)
3824 if (Cand->Viable)
3825 ICS->ConversionFunctionSet.push_back(Cand->Function);
3826 break;
3827 }
3828 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3829 << Init->getSourceRange();
3830 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003831 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003833 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003834 case OR_Deleted:
3835 // There was no suitable conversion, or we found a deleted
3836 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003837 break;
3838 }
3839 }
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003841 if (BindsDirectly) {
3842 // C++ [dcl.init.ref]p4:
3843 // [...] In all cases where the reference-related or
3844 // reference-compatible relationship of two types is used to
3845 // establish the validity of a reference binding, and T1 is a
3846 // base class of T2, a program that necessitates such a binding
3847 // is ill-formed if T1 is an inaccessible (clause 11) or
3848 // ambiguous (10.2) base class of T2.
3849 //
3850 // Note that we only check this condition when we're allowed to
3851 // complain about errors, because we should not be checking for
3852 // ambiguity (or inaccessibility) unless the reference binding
3853 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003854 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003855 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003856 Init->getSourceRange());
3857 else
3858 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003859 }
3860
3861 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003862 // type (i.e., cv1 shall be const), or the reference shall be an
3863 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00003864 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003865 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003866 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003867 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3868 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003869 return true;
3870 }
3871
3872 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003873 // class type, and "cv1 T1" is reference-compatible with
3874 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003875 // following ways (the choice is implementation-defined):
3876 //
3877 // -- The reference is bound to the object represented by
3878 // the rvalue (see 3.10) or to a sub-object within that
3879 // object.
3880 //
Eli Friedman33a31382009-08-05 19:21:58 +00003881 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003882 // a constructor is called to copy the entire rvalue
3883 // object into the temporary. The reference is bound to
3884 // the temporary or to a sub-object within the
3885 // temporary.
3886 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003887 // The constructor that would be used to make the copy
3888 // shall be callable whether or not the copy is actually
3889 // done.
3890 //
Sebastian Redla9845802009-03-29 15:27:50 +00003891 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003892 // freedom, so we will always take the first option and never build
3893 // a temporary in this case. FIXME: We will, however, have to check
3894 // for the presence of a copy constructor in C++98/03 mode.
3895 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003896 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3897 if (ICS) {
3898 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3899 ICS->Standard.First = ICK_Identity;
3900 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3901 ICS->Standard.Third = ICK_Identity;
3902 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3903 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003904 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003905 ICS->Standard.DirectBinding = false;
3906 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003907 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003908 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003909 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3910 if (DerivedToBase)
3911 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003912 else if(CheckExceptionSpecCompatibility(Init, T1))
3913 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003914 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003915 }
3916 return false;
3917 }
3918
Eli Friedman33a31382009-08-05 19:21:58 +00003919 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003920 // initialized from the initializer expression using the
3921 // rules for a non-reference copy initialization (8.5). The
3922 // reference is then bound to the temporary. If T1 is
3923 // reference-related to T2, cv1 must be the same
3924 // cv-qualification as, or greater cv-qualification than,
3925 // cv2; otherwise, the program is ill-formed.
3926 if (RefRelationship == Ref_Related) {
3927 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3928 // we would be reference-compatible or reference-compatible with
3929 // added qualification. But that wasn't the case, so the reference
3930 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003931 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003932 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003933 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3934 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003935 return true;
3936 }
3937
Douglas Gregor734d9862009-01-30 23:27:23 +00003938 // If at least one of the types is a class type, the types are not
3939 // related, and we aren't allowed any user conversions, the
3940 // reference binding fails. This case is important for breaking
3941 // recursion, since TryImplicitConversion below will attempt to
3942 // create a temporary through the use of a copy constructor.
3943 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3944 (T1->isRecordType() || T2->isRecordType())) {
3945 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003946 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00003947 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3948 return true;
3949 }
3950
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003951 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003952 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003953 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003954 //
Sebastian Redla9845802009-03-29 15:27:50 +00003955 // When a parameter of reference type is not bound directly to
3956 // an argument expression, the conversion sequence is the one
3957 // required to convert the argument expression to the
3958 // underlying type of the reference according to
3959 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3960 // to copy-initializing a temporary of the underlying type with
3961 // the argument expression. Any difference in top-level
3962 // cv-qualification is subsumed by the initialization itself
3963 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003964 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3965 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003966 /*ForceRValue=*/false,
3967 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Sebastian Redla9845802009-03-29 15:27:50 +00003969 // Of course, that's still a reference binding.
3970 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3971 ICS->Standard.ReferenceBinding = true;
3972 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003973 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003974 ImplicitConversionSequence::UserDefinedConversion) {
3975 ICS->UserDefined.After.ReferenceBinding = true;
3976 ICS->UserDefined.After.RRefBinding = isRValRef;
3977 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003978 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3979 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003980 ImplicitConversionSequence Conversions;
3981 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3982 false, false,
3983 Conversions);
3984 if (badConversion) {
3985 if ((Conversions.ConversionKind ==
3986 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00003987 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00003988 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003989 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3990 for (int j = Conversions.ConversionFunctionSet.size()-1;
3991 j >= 0; j--) {
3992 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3993 Diag(Func->getLocation(), diag::err_ovl_candidate);
3994 }
3995 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00003996 else {
3997 if (isRValRef)
3998 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3999 << Init->getSourceRange();
4000 else
4001 Diag(DeclLoc, diag::err_invalid_initialization)
4002 << DeclType << Init->getType() << Init->getSourceRange();
4003 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004004 }
4005 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004006 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004007}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004008
4009/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4010/// of this overloaded operator is well-formed. If so, returns false;
4011/// otherwise, emits appropriate diagnostics and returns true.
4012bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004013 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004014 "Expected an overloaded operator declaration");
4015
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004016 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4017
Mike Stump1eb44332009-09-09 15:08:12 +00004018 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004019 // The allocation and deallocation functions, operator new,
4020 // operator new[], operator delete and operator delete[], are
4021 // described completely in 3.7.3. The attributes and restrictions
4022 // found in the rest of this subclause do not apply to them unless
4023 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004024 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004025 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004026 return false;
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004027
4028 if (Op == OO_New || Op == OO_Array_New) {
4029 bool ret = false;
4030 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4031 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4032 QualType T = Context.getCanonicalType((*Param)->getType());
4033 if (!T->isDependentType() && SizeTy != T) {
4034 Diag(FnDecl->getLocation(),
4035 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4036 << SizeTy;
4037 ret = true;
4038 }
4039 }
4040 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4041 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4042 return Diag(FnDecl->getLocation(),
4043 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregorcffecd02009-11-12 16:49:45 +00004044 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004045 return ret;
4046 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004047
4048 // C++ [over.oper]p6:
4049 // An operator function shall either be a non-static member
4050 // function or be a non-member function and have at least one
4051 // parameter whose type is a class, a reference to a class, an
4052 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004053 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4054 if (MethodDecl->isStatic())
4055 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004056 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004057 } else {
4058 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004059 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4060 ParamEnd = FnDecl->param_end();
4061 Param != ParamEnd; ++Param) {
4062 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004063 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4064 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004065 ClassOrEnumParam = true;
4066 break;
4067 }
4068 }
4069
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004070 if (!ClassOrEnumParam)
4071 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004072 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004073 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004074 }
4075
4076 // C++ [over.oper]p8:
4077 // An operator function cannot have default arguments (8.3.6),
4078 // except where explicitly stated below.
4079 //
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004081 // (C++ [over.call]p1).
4082 if (Op != OO_Call) {
4083 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4084 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004085 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004086 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004087 diag::err_operator_overload_default_arg)
4088 << FnDecl->getDeclName();
4089 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004090 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004091 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004092 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004093 }
4094 }
4095
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004096 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4097 { false, false, false }
4098#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4099 , { Unary, Binary, MemberOnly }
4100#include "clang/Basic/OperatorKinds.def"
4101 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004102
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004103 bool CanBeUnaryOperator = OperatorUses[Op][0];
4104 bool CanBeBinaryOperator = OperatorUses[Op][1];
4105 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004106
4107 // C++ [over.oper]p8:
4108 // [...] Operator functions cannot have more or fewer parameters
4109 // than the number required for the corresponding operator, as
4110 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004111 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004112 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004113 if (Op != OO_Call &&
4114 ((NumParams == 1 && !CanBeUnaryOperator) ||
4115 (NumParams == 2 && !CanBeBinaryOperator) ||
4116 (NumParams < 1) || (NumParams > 2))) {
4117 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004118 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004119 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004120 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004121 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004122 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004123 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004124 assert(CanBeBinaryOperator &&
4125 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004126 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004127 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004128
Chris Lattner416e46f2008-11-21 07:57:12 +00004129 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004130 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004131 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004132
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004133 // Overloaded operators other than operator() cannot be variadic.
4134 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004135 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004136 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004137 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004138 }
4139
4140 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004141 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4142 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004143 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004144 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004145 }
4146
4147 // C++ [over.inc]p1:
4148 // The user-defined function called operator++ implements the
4149 // prefix and postfix ++ operator. If this function is a member
4150 // function with no parameters, or a non-member function with one
4151 // parameter of class or enumeration type, it defines the prefix
4152 // increment operator ++ for objects of that type. If the function
4153 // is a member function with one parameter (which shall be of type
4154 // int) or a non-member function with two parameters (the second
4155 // of which shall be of type int), it defines the postfix
4156 // increment operator ++ for objects of that type.
4157 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4158 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4159 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004160 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004161 ParamIsInt = BT->getKind() == BuiltinType::Int;
4162
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004163 if (!ParamIsInt)
4164 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004165 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004166 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004167 }
4168
Sebastian Redl64b45f72009-01-05 20:52:13 +00004169 // Notify the class if it got an assignment operator.
4170 if (Op == OO_Equal) {
4171 // Would have returned earlier otherwise.
4172 assert(isa<CXXMethodDecl>(FnDecl) &&
4173 "Overloaded = not member, but not filtered.");
4174 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4175 Method->getParent()->addedAssignmentOperator(Context, Method);
4176 }
4177
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004178 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004179}
Chris Lattner5a003a42008-12-17 07:09:26 +00004180
Douglas Gregor074149e2009-01-05 19:45:36 +00004181/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4182/// linkage specification, including the language and (if present)
4183/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4184/// the location of the language string literal, which is provided
4185/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4186/// the '{' brace. Otherwise, this linkage specification does not
4187/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004188Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4189 SourceLocation ExternLoc,
4190 SourceLocation LangLoc,
4191 const char *Lang,
4192 unsigned StrSize,
4193 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004194 LinkageSpecDecl::LanguageIDs Language;
4195 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4196 Language = LinkageSpecDecl::lang_c;
4197 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4198 Language = LinkageSpecDecl::lang_cxx;
4199 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004200 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004201 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004202 }
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Chris Lattnercc98eac2008-12-17 07:13:27 +00004204 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004205
Douglas Gregor074149e2009-01-05 19:45:36 +00004206 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004207 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004208 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004209 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004210 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004211 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004212}
4213
Douglas Gregor074149e2009-01-05 19:45:36 +00004214/// ActOnFinishLinkageSpecification - Completely the definition of
4215/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4216/// valid, it's the position of the closing '}' brace in a linkage
4217/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004218Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4219 DeclPtrTy LinkageSpec,
4220 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004221 if (LinkageSpec)
4222 PopDeclContext();
4223 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004224}
4225
Douglas Gregord308e622009-05-18 20:51:54 +00004226/// \brief Perform semantic analysis for the variable declaration that
4227/// occurs within a C++ catch clause, returning the newly-created
4228/// variable.
4229VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004230 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004231 IdentifierInfo *Name,
4232 SourceLocation Loc,
4233 SourceRange Range) {
4234 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004235
4236 // Arrays and functions decay.
4237 if (ExDeclType->isArrayType())
4238 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4239 else if (ExDeclType->isFunctionType())
4240 ExDeclType = Context.getPointerType(ExDeclType);
4241
4242 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4243 // The exception-declaration shall not denote a pointer or reference to an
4244 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004245 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004246 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004247 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004248 Invalid = true;
4249 }
Douglas Gregord308e622009-05-18 20:51:54 +00004250
Sebastian Redl4b07b292008-12-22 19:15:10 +00004251 QualType BaseType = ExDeclType;
4252 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004253 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004254 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004255 BaseType = Ptr->getPointeeType();
4256 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004257 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004258 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004259 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004260 BaseType = Ref->getPointeeType();
4261 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004262 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004263 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004264 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004265 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004266 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004267
Mike Stump1eb44332009-09-09 15:08:12 +00004268 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004269 RequireNonAbstractType(Loc, ExDeclType,
4270 diag::err_abstract_type_in_decl,
4271 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004272 Invalid = true;
4273
Douglas Gregord308e622009-05-18 20:51:54 +00004274 // FIXME: Need to test for ability to copy-construct and destroy the
4275 // exception variable.
4276
Sebastian Redl8351da02008-12-22 21:35:02 +00004277 // FIXME: Need to check for abstract classes.
4278
Mike Stump1eb44332009-09-09 15:08:12 +00004279 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004280 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004281
4282 if (Invalid)
4283 ExDecl->setInvalidDecl();
4284
4285 return ExDecl;
4286}
4287
4288/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4289/// handler.
4290Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004291 DeclaratorInfo *DInfo = 0;
4292 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004293
4294 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004295 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004296 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004297 // The scope should be freshly made just for us. There is just no way
4298 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004299 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004300 if (PrevDecl->isTemplateParameter()) {
4301 // Maybe we will complain about the shadowed template parameter.
4302 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004303 }
4304 }
4305
Chris Lattnereaaebc72009-04-25 08:06:05 +00004306 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004307 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4308 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004309 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004310 }
4311
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004312 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004313 D.getIdentifier(),
4314 D.getIdentifierLoc(),
4315 D.getDeclSpec().getSourceRange());
4316
Chris Lattnereaaebc72009-04-25 08:06:05 +00004317 if (Invalid)
4318 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Sebastian Redl4b07b292008-12-22 19:15:10 +00004320 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004321 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004322 PushOnScopeChains(ExDecl, S);
4323 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004324 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004325
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004326 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004327 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004328}
Anders Carlssonfb311762009-03-14 00:25:26 +00004329
Mike Stump1eb44332009-09-09 15:08:12 +00004330Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004331 ExprArg assertexpr,
4332 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004333 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004334 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004335 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4336
Anders Carlssonc3082412009-03-14 00:33:21 +00004337 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4338 llvm::APSInt Value(32);
4339 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4340 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4341 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004342 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004343 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004344
Anders Carlssonc3082412009-03-14 00:33:21 +00004345 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004346 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004347 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004348 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004349 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004350 }
4351 }
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Anders Carlsson77d81422009-03-15 17:35:16 +00004353 assertexpr.release();
4354 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004355 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004356 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004358 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004359 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004360}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004361
John McCalldd4a3b02009-09-16 22:47:08 +00004362/// Handle a friend type declaration. This works in tandem with
4363/// ActOnTag.
4364///
4365/// Notes on friend class templates:
4366///
4367/// We generally treat friend class declarations as if they were
4368/// declaring a class. So, for example, the elaborated type specifier
4369/// in a friend declaration is required to obey the restrictions of a
4370/// class-head (i.e. no typedefs in the scope chain), template
4371/// parameters are required to match up with simple template-ids, &c.
4372/// However, unlike when declaring a template specialization, it's
4373/// okay to refer to a template specialization without an empty
4374/// template parameter declaration, e.g.
4375/// friend class A<T>::B<unsigned>;
4376/// We permit this as a special case; if there are any template
4377/// parameters present at all, require proper matching, i.e.
4378/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004379Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004380 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004381 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004382
4383 assert(DS.isFriendSpecified());
4384 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4385
John McCalldd4a3b02009-09-16 22:47:08 +00004386 // Try to convert the decl specifier to a type. This works for
4387 // friend templates because ActOnTag never produces a ClassTemplateDecl
4388 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004389 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004390 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4391 if (TheDeclarator.isInvalidType())
4392 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004393
John McCalldd4a3b02009-09-16 22:47:08 +00004394 // This is definitely an error in C++98. It's probably meant to
4395 // be forbidden in C++0x, too, but the specification is just
4396 // poorly written.
4397 //
4398 // The problem is with declarations like the following:
4399 // template <T> friend A<T>::foo;
4400 // where deciding whether a class C is a friend or not now hinges
4401 // on whether there exists an instantiation of A that causes
4402 // 'foo' to equal C. There are restrictions on class-heads
4403 // (which we declare (by fiat) elaborated friend declarations to
4404 // be) that makes this tractable.
4405 //
4406 // FIXME: handle "template <> friend class A<T>;", which
4407 // is possibly well-formed? Who even knows?
4408 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4409 Diag(Loc, diag::err_tagless_friend_type_template)
4410 << DS.getSourceRange();
4411 return DeclPtrTy();
4412 }
4413
John McCall02cace72009-08-28 07:59:38 +00004414 // C++ [class.friend]p2:
4415 // An elaborated-type-specifier shall be used in a friend declaration
4416 // for a class.*
4417 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004418 // This is one of the rare places in Clang where it's legitimate to
4419 // ask about the "spelling" of the type.
4420 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4421 // If we evaluated the type to a record type, suggest putting
4422 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004423 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004424 RecordDecl *RD = RT->getDecl();
4425
4426 std::string InsertionText = std::string(" ") + RD->getKindName();
4427
John McCalle3af0232009-10-07 23:34:25 +00004428 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4429 << (unsigned) RD->getTagKind()
4430 << T
4431 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004432 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4433 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004434 return DeclPtrTy();
4435 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004436 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4437 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004438 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004439 }
4440 }
4441
John McCalle3af0232009-10-07 23:34:25 +00004442 // Enum types cannot be friends.
4443 if (T->getAs<EnumType>()) {
4444 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4445 << SourceRange(DS.getFriendSpecLoc());
4446 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004447 }
John McCall02cace72009-08-28 07:59:38 +00004448
John McCall02cace72009-08-28 07:59:38 +00004449 // C++98 [class.friend]p1: A friend of a class is a function
4450 // or class that is not a member of the class . . .
4451 // But that's a silly restriction which nobody implements for
4452 // inner classes, and C++0x removes it anyway, so we only report
4453 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004454 if (!getLangOptions().CPlusPlus0x)
4455 if (const RecordType *RT = T->getAs<RecordType>())
4456 if (RT->getDecl()->getDeclContext() == CurContext)
4457 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004458
John McCalldd4a3b02009-09-16 22:47:08 +00004459 Decl *D;
4460 if (TempParams.size())
4461 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4462 TempParams.size(),
4463 (TemplateParameterList**) TempParams.release(),
4464 T.getTypePtr(),
4465 DS.getFriendSpecLoc());
4466 else
4467 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4468 DS.getFriendSpecLoc());
4469 D->setAccess(AS_public);
4470 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004471
John McCalldd4a3b02009-09-16 22:47:08 +00004472 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004473}
4474
John McCallbbbcdd92009-09-11 21:02:39 +00004475Sema::DeclPtrTy
4476Sema::ActOnFriendFunctionDecl(Scope *S,
4477 Declarator &D,
4478 bool IsDefinition,
4479 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004480 const DeclSpec &DS = D.getDeclSpec();
4481
4482 assert(DS.isFriendSpecified());
4483 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4484
4485 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004486 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004487 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004488
4489 // C++ [class.friend]p1
4490 // A friend of a class is a function or class....
4491 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004492 // It *doesn't* see through dependent types, which is correct
4493 // according to [temp.arg.type]p3:
4494 // If a declaration acquires a function type through a
4495 // type dependent on a template-parameter and this causes
4496 // a declaration that does not use the syntactic form of a
4497 // function declarator to have a function type, the program
4498 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004499 if (!T->isFunctionType()) {
4500 Diag(Loc, diag::err_unexpected_friend);
4501
4502 // It might be worthwhile to try to recover by creating an
4503 // appropriate declaration.
4504 return DeclPtrTy();
4505 }
4506
4507 // C++ [namespace.memdef]p3
4508 // - If a friend declaration in a non-local class first declares a
4509 // class or function, the friend class or function is a member
4510 // of the innermost enclosing namespace.
4511 // - The name of the friend is not found by simple name lookup
4512 // until a matching declaration is provided in that namespace
4513 // scope (either before or after the class declaration granting
4514 // friendship).
4515 // - If a friend function is called, its name may be found by the
4516 // name lookup that considers functions from namespaces and
4517 // classes associated with the types of the function arguments.
4518 // - When looking for a prior declaration of a class or a function
4519 // declared as a friend, scopes outside the innermost enclosing
4520 // namespace scope are not considered.
4521
John McCall02cace72009-08-28 07:59:38 +00004522 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4523 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004524 assert(Name);
4525
John McCall67d1a672009-08-06 02:15:43 +00004526 // The context we found the declaration in, or in which we should
4527 // create the declaration.
4528 DeclContext *DC;
4529
4530 // FIXME: handle local classes
4531
4532 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004533 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004534 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004535 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004536 DC = computeDeclContext(ScopeQual);
4537
4538 // FIXME: handle dependent contexts
4539 if (!DC) return DeclPtrTy();
4540
John McCallf36e02d2009-10-09 21:13:30 +00004541 LookupResult R;
4542 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4543 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004544
4545 // If searching in that context implicitly found a declaration in
4546 // a different context, treat it like it wasn't found at all.
4547 // TODO: better diagnostics for this case. Suggesting the right
4548 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004549 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004550 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004551 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4552 return DeclPtrTy();
4553 }
4554
4555 // C++ [class.friend]p1: A friend of a class is a function or
4556 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004557 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004558 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4559
John McCall67d1a672009-08-06 02:15:43 +00004560 // Otherwise walk out to the nearest namespace scope looking for matches.
4561 } else {
4562 // TODO: handle local class contexts.
4563
4564 DC = CurContext;
4565 while (true) {
4566 // Skip class contexts. If someone can cite chapter and verse
4567 // for this behavior, that would be nice --- it's what GCC and
4568 // EDG do, and it seems like a reasonable intent, but the spec
4569 // really only says that checks for unqualified existing
4570 // declarations should stop at the nearest enclosing namespace,
4571 // not that they should only consider the nearest enclosing
4572 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004573 while (DC->isRecord())
4574 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004575
John McCallf36e02d2009-10-09 21:13:30 +00004576 LookupResult R;
4577 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4578 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004579
4580 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004581 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004582 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004583
John McCall67d1a672009-08-06 02:15:43 +00004584 if (DC->isFileContext()) break;
4585 DC = DC->getParent();
4586 }
4587
4588 // C++ [class.friend]p1: A friend of a class is a function or
4589 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004590 // C++0x changes this for both friend types and functions.
4591 // Most C++ 98 compilers do seem to give an error here, so
4592 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004593 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004594 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4595 }
4596
Douglas Gregor182ddf02009-09-28 00:08:27 +00004597 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004598 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004599 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4600 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4601 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004602 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004603 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4604 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004605 return DeclPtrTy();
4606 }
John McCall67d1a672009-08-06 02:15:43 +00004607 }
4608
Douglas Gregor182ddf02009-09-28 00:08:27 +00004609 bool Redeclaration = false;
4610 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004611 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004612 IsDefinition,
4613 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004614 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004615
Douglas Gregor182ddf02009-09-28 00:08:27 +00004616 assert(ND->getDeclContext() == DC);
4617 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004618
John McCallab88d972009-08-31 22:39:49 +00004619 // Add the function declaration to the appropriate lookup tables,
4620 // adjusting the redeclarations list as necessary. We don't
4621 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004622 //
John McCallab88d972009-08-31 22:39:49 +00004623 // Also update the scope-based lookup if the target context's
4624 // lookup context is in lexical scope.
4625 if (!CurContext->isDependentContext()) {
4626 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004627 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004628 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004629 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004630 }
John McCall02cace72009-08-28 07:59:38 +00004631
4632 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004633 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004634 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004635 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004636 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004637
Douglas Gregor182ddf02009-09-28 00:08:27 +00004638 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004639}
4640
Chris Lattnerb28317a2009-03-28 19:18:32 +00004641void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004642 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004643
Chris Lattnerb28317a2009-03-28 19:18:32 +00004644 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004645 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4646 if (!Fn) {
4647 Diag(DelLoc, diag::err_deleted_non_function);
4648 return;
4649 }
4650 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4651 Diag(DelLoc, diag::err_deleted_decl_not_first);
4652 Diag(Prev->getLocation(), diag::note_previous_declaration);
4653 // If the declaration wasn't the first, we delete the function anyway for
4654 // recovery.
4655 }
4656 Fn->setDeleted();
4657}
Sebastian Redl13e88542009-04-27 21:33:24 +00004658
4659static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4660 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4661 ++CI) {
4662 Stmt *SubStmt = *CI;
4663 if (!SubStmt)
4664 continue;
4665 if (isa<ReturnStmt>(SubStmt))
4666 Self.Diag(SubStmt->getSourceRange().getBegin(),
4667 diag::err_return_in_constructor_handler);
4668 if (!isa<Expr>(SubStmt))
4669 SearchForReturnInStmt(Self, SubStmt);
4670 }
4671}
4672
4673void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4674 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4675 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4676 SearchForReturnInStmt(*this, Handler);
4677 }
4678}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004679
Mike Stump1eb44332009-09-09 15:08:12 +00004680bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004681 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004682 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4683 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004684
4685 QualType CNewTy = Context.getCanonicalType(NewTy);
4686 QualType COldTy = Context.getCanonicalType(OldTy);
4687
Mike Stump1eb44332009-09-09 15:08:12 +00004688 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004689 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4690 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004692 // Check if the return types are covariant
4693 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004694
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004695 /// Both types must be pointers or references to classes.
4696 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4697 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4698 NewClassTy = NewPT->getPointeeType();
4699 OldClassTy = OldPT->getPointeeType();
4700 }
4701 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4702 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4703 NewClassTy = NewRT->getPointeeType();
4704 OldClassTy = OldRT->getPointeeType();
4705 }
4706 }
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004708 // The return types aren't either both pointers or references to a class type.
4709 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004710 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004711 diag::err_different_return_type_for_overriding_virtual_function)
4712 << New->getDeclName() << NewTy << OldTy;
4713 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004715 return true;
4716 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004717
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004718 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4719 // Check if the new class derives from the old class.
4720 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4721 Diag(New->getLocation(),
4722 diag::err_covariant_return_not_derived)
4723 << New->getDeclName() << NewTy << OldTy;
4724 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4725 return true;
4726 }
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004728 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004729 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004730 diag::err_covariant_return_inaccessible_base,
4731 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4732 // FIXME: Should this point to the return type?
4733 New->getLocation(), SourceRange(), New->getDeclName())) {
4734 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4735 return true;
4736 }
4737 }
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004739 // The qualifiers of the return types must be the same.
4740 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4741 Diag(New->getLocation(),
4742 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004743 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004744 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4745 return true;
4746 };
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004748
4749 // The new class type must have the same or less qualifiers as the old type.
4750 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4751 Diag(New->getLocation(),
4752 diag::err_covariant_return_type_class_type_more_qualified)
4753 << New->getDeclName() << NewTy << OldTy;
4754 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4755 return true;
4756 };
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004758 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004759}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004760
4761/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4762/// initializer for the declaration 'Dcl'.
4763/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4764/// static data member of class X, names should be looked up in the scope of
4765/// class X.
4766void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004767 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004769 Decl *D = Dcl.getAs<Decl>();
4770 // If there is no declaration, there was an error parsing it.
4771 if (D == 0)
4772 return;
4773
4774 // Check whether it is a declaration with a nested name specifier like
4775 // int foo::bar;
4776 if (!D->isOutOfLine())
4777 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004778
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004779 // C++ [basic.lookup.unqual]p13
4780 //
4781 // A name used in the definition of a static data member of class X
4782 // (after the qualified-id of the static member) is looked up as if the name
4783 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004785 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004786 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004787}
4788
4789/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4790/// initializer for the declaration 'Dcl'.
4791void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004792 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004793
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004794 Decl *D = Dcl.getAs<Decl>();
4795 // If there is no declaration, there was an error parsing it.
4796 if (D == 0)
4797 return;
4798
4799 // Check whether it is a declaration with a nested name specifier like
4800 // int foo::bar;
4801 if (!D->isOutOfLine())
4802 return;
4803
4804 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004805 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004806}