blob: fdbd554e0348b945a021949148ab3b9978f039d9 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssond624e162009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar34fb6722008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000027#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000028#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner58258242008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattnerb0d38442008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000046
Chris Lattnerb0d38442008-04-12 23:52:44 +000047 public:
Mike Stump11289f42009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000050
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 };
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000063 }
64
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 }
Chris Lattner58258242008-04-10 02:22:51 +000091
Douglas Gregor8e12c382008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000094
Douglas Gregor97a9c812008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000103 }
Chris Lattner58258242008-04-10 02:22:51 +0000104}
105
Anders Carlssonc80a1272009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson114056f2009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssonc80a1272009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000118
Anders Carlssonc80a1272009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000127 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000130
Anders Carlssonc80a1272009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000133
Anders Carlssonc80a1272009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000137}
138
Chris Lattner58258242008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000142void
Mike Stump11289f42009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump11289f42009-09-09 15:08:12 +0000147
Chris Lattner83f095c2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlssonf1c26952009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
Anders Carlssonc80a1272009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000170}
171
Douglas Gregor58354032008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner83f095c2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000185
Anders Carlsson84613c42009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000187}
188
Douglas Gregor4d87df52008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Anders Carlsson84613c42009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000196
Anders Carlsson84613c42009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000198
Anders Carlsson84613c42009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000200}
201
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner199abbc2008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner199abbc2008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregorc732aba2009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump11289f42009-09-09 15:08:12 +0000267 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000268 diag::err_param_default_argument_redefinition)
Douglas Gregorc732aba2009-09-11 18:44:32 +0000269 << NewParam->getDefaultArgRange();
270
271 // Look for the function declaration where the default argument was
272 // actually written, which may be a declaration prior to Old.
273 for (FunctionDecl *Older = Old->getPreviousDeclaration();
274 Older; Older = Older->getPreviousDeclaration()) {
275 if (!Older->getParamDecl(p)->hasDefaultArg())
276 break;
277
278 OldParam = Older->getParamDecl(p);
279 }
280
281 Diag(OldParam->getLocation(), diag::note_previous_definition)
282 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000283 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000284 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000285 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000286 if (OldParam->hasUninstantiatedDefaultArg())
287 NewParam->setUninstantiatedDefaultArg(
288 OldParam->getUninstantiatedDefaultArg());
289 else
290 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000291 } else if (NewParam->hasDefaultArg()) {
292 if (New->getDescribedFunctionTemplate()) {
293 // Paragraph 4, quoted above, only applies to non-template functions.
294 Diag(NewParam->getLocation(),
295 diag::err_param_default_argument_template_redecl)
296 << NewParam->getDefaultArgRange();
297 Diag(Old->getLocation(), diag::note_template_prev_declaration)
298 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000299 } else if (New->getTemplateSpecializationKind()
300 != TSK_ImplicitInstantiation &&
301 New->getTemplateSpecializationKind() != TSK_Undeclared) {
302 // C++ [temp.expr.spec]p21:
303 // Default function arguments shall not be specified in a declaration
304 // or a definition for one of the following explicit specializations:
305 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000306 // - the explicit specialization of a member function template;
307 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000308 // template where the class template specialization to which the
309 // member function specialization belongs is implicitly
310 // instantiated.
311 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
312 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
313 << New->getDeclName()
314 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000315 } else if (New->getDeclContext()->isDependentContext()) {
316 // C++ [dcl.fct.default]p6 (DR217):
317 // Default arguments for a member function of a class template shall
318 // be specified on the initial declaration of the member function
319 // within the class template.
320 //
321 // Reading the tea leaves a bit in DR217 and its reference to DR205
322 // leads me to the conclusion that one cannot add default function
323 // arguments for an out-of-line definition of a member function of a
324 // dependent type.
325 int WhichKind = 2;
326 if (CXXRecordDecl *Record
327 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
328 if (Record->getDescribedClassTemplate())
329 WhichKind = 0;
330 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
331 WhichKind = 1;
332 else
333 WhichKind = 2;
334 }
335
336 Diag(NewParam->getLocation(),
337 diag::err_param_default_argument_member_template_redecl)
338 << WhichKind
339 << NewParam->getDefaultArgRange();
340 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000341 }
342 }
343
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000344 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000345 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
346 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000347 Invalid = true;
348 }
349
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000350 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000351}
352
353/// CheckCXXDefaultArguments - Verify that the default arguments for a
354/// function declaration are well-formed according to C++
355/// [dcl.fct.default].
356void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
357 unsigned NumParams = FD->getNumParams();
358 unsigned p;
359
360 // Find first parameter with a default argument
361 for (p = 0; p < NumParams; ++p) {
362 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000363 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000364 break;
365 }
366
367 // C++ [dcl.fct.default]p4:
368 // In a given function declaration, all parameters
369 // subsequent to a parameter with a default argument shall
370 // have default arguments supplied in this or previous
371 // declarations. A default argument shall not be redefined
372 // by a later declaration (not even to the same value).
373 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000374 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000376 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000377 if (Param->isInvalidDecl())
378 /* We already complained about this parameter. */;
379 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000380 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000381 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000382 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000383 else
Mike Stump11289f42009-09-09 15:08:12 +0000384 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattner199abbc2008-04-08 05:04:30 +0000387 LastMissingDefaultArg = p;
388 }
389 }
390
391 if (LastMissingDefaultArg > 0) {
392 // Some default arguments were missing. Clear out all of the
393 // default arguments up to (and including) the last missing
394 // default argument, so that we leave the function parameters
395 // in a semantically valid state.
396 for (p = 0; p <= LastMissingDefaultArg; ++p) {
397 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000398 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000399 if (!Param->hasUnparsedDefaultArg())
400 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 Param->setDefaultArg(0);
402 }
403 }
404 }
405}
Douglas Gregor556877c2008-04-13 21:30:24 +0000406
Douglas Gregor61956c42008-10-31 09:07:45 +0000407/// isCurrentClassName - Determine whether the identifier II is the
408/// name of the class type currently being defined. In the case of
409/// nested classes, this will only return true if II is the name of
410/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000411bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
412 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000413 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000414 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000415 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
417 } else
418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
419
420 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000421 return &II == CurDecl->getIdentifier();
422 else
423 return false;
424}
425
Mike Stump11289f42009-09-09 15:08:12 +0000426/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000427///
428/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
429/// and returns NULL otherwise.
430CXXBaseSpecifier *
431Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
432 SourceRange SpecifierRange,
433 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000434 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000435 SourceLocation BaseLoc) {
436 // C++ [class.union]p1:
437 // A union shall not have base classes.
438 if (Class->isUnion()) {
439 Diag(Class->getLocation(), diag::err_base_clause_on_union)
440 << SpecifierRange;
441 return 0;
442 }
443
444 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000445 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000446 Class->getTagKind() == RecordDecl::TK_class,
447 Access, BaseType);
448
449 // Base specifiers must be record types.
450 if (!BaseType->isRecordType()) {
451 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
452 return 0;
453 }
454
455 // C++ [class.union]p1:
456 // A union shall not be used as a base class.
457 if (BaseType->isUnionType()) {
458 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
459 return 0;
460 }
461
462 // C++ [class.derived]p2:
463 // The class-name in a base-specifier shall not be an incompletely
464 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000465 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000466 PDiag(diag::err_incomplete_base_class)
467 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000468 return 0;
469
Eli Friedmanc96d4962009-08-15 21:55:26 +0000470 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000471 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000472 assert(BaseDecl && "Record type has no declaration");
473 BaseDecl = BaseDecl->getDefinition(Context);
474 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000475 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
476 assert(CXXBaseDecl && "Base type is not a C++ type");
477 if (!CXXBaseDecl->isEmpty())
478 Class->setEmpty(false);
479 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000480 Class->setPolymorphic(true);
481
482 // C++ [dcl.init.aggr]p1:
483 // An aggregate is [...] a class with [...] no base classes [...].
484 Class->setAggregate(false);
485 Class->setPOD(false);
486
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000487 if (Virtual) {
488 // C++ [class.ctor]p5:
489 // A constructor is trivial if its class has no virtual base classes.
490 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000491
492 // C++ [class.copy]p6:
493 // A copy constructor is trivial if its class has no virtual base classes.
494 Class->setHasTrivialCopyConstructor(false);
495
496 // C++ [class.copy]p11:
497 // A copy assignment operator is trivial if its class has no virtual
498 // base classes.
499 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000500
501 // C++0x [meta.unary.prop] is_empty:
502 // T is a class type, but not a union type, with ... no virtual base
503 // classes
504 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000505 } else {
506 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000507 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000508 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000509 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
510 Class->setHasTrivialConstructor(false);
511
512 // C++ [class.copy]p6:
513 // A copy constructor is trivial if all the direct base classes of its
514 // class have trivial copy constructors.
515 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
516 Class->setHasTrivialCopyConstructor(false);
517
518 // C++ [class.copy]p11:
519 // A copy assignment operator is trivial if all the direct base classes
520 // of its class have trivial copy assignment operators.
521 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
522 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000523 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000524
525 // C++ [class.ctor]p3:
526 // A destructor is trivial if all the direct base classes of its class
527 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000528 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
529 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregor463421d2009-03-03 04:44:36 +0000531 // Create the base specifier.
532 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000533 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
534 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000535 Access, BaseType);
536}
537
Douglas Gregor556877c2008-04-13 21:30:24 +0000538/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
539/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000540/// example:
541/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000542/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000543Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000544Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000545 bool Virtual, AccessSpecifier Access,
546 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000547 if (!classdecl)
548 return true;
549
Douglas Gregorc40290e2009-03-09 23:48:35 +0000550 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000551 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000552 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000553 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
554 Virtual, Access,
555 BaseType, BaseLoc))
556 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000557
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000559}
Douglas Gregor556877c2008-04-13 21:30:24 +0000560
Douglas Gregor463421d2009-03-03 04:44:36 +0000561/// \brief Performs the actual work of attaching the given base class
562/// specifiers to a C++ class.
563bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
564 unsigned NumBases) {
565 if (NumBases == 0)
566 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000567
568 // Used to keep track of which base types we have already seen, so
569 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000570 // that the key is always the unqualified canonical type of the base
571 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000572 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
573
574 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000575 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000577 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000578 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000579 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000580 NewBaseType = NewBaseType.getUnqualifiedType();
581
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 if (KnownBaseTypes[NewBaseType]) {
583 // C++ [class.mi]p3:
584 // A class shall not be specified as a direct base class of a
585 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000587 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000588 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000590
591 // Delete the duplicate base class specifier; we're going to
592 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000593 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000594
595 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000596 } else {
597 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000598 KnownBaseTypes[NewBaseType] = Bases[idx];
599 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000600 }
601 }
602
603 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000604 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000605
606 // Delete the remaining (good) base class specifiers, since their
607 // data has been copied into the CXXRecordDecl.
608 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000609 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000610
611 return Invalid;
612}
613
614/// ActOnBaseSpecifiers - Attach the given base specifiers to the
615/// class, after checking whether there are any duplicate base
616/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000617void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 unsigned NumBases) {
619 if (!ClassDecl || !Bases || !NumBases)
620 return;
621
622 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000623 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000625}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000626
Douglas Gregor36d1b142009-10-06 17:59:45 +0000627/// \brief Determine whether the type \p Derived is a C++ class that is
628/// derived from the type \p Base.
629bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
630 if (!getLangOptions().CPlusPlus)
631 return false;
632
633 const RecordType *DerivedRT = Derived->getAs<RecordType>();
634 if (!DerivedRT)
635 return false;
636
637 const RecordType *BaseRT = Base->getAs<RecordType>();
638 if (!BaseRT)
639 return false;
640
641 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
642 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
643 return DerivedRD->isDerivedFrom(BaseRD);
644}
645
646/// \brief Determine whether the type \p Derived is a C++ class that is
647/// derived from the type \p Base.
648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
649 if (!getLangOptions().CPlusPlus)
650 return false;
651
652 const RecordType *DerivedRT = Derived->getAs<RecordType>();
653 if (!DerivedRT)
654 return false;
655
656 const RecordType *BaseRT = Base->getAs<RecordType>();
657 if (!BaseRT)
658 return false;
659
660 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
661 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
662 return DerivedRD->isDerivedFrom(BaseRD, Paths);
663}
664
665/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
666/// conversion (where Derived and Base are class types) is
667/// well-formed, meaning that the conversion is unambiguous (and
668/// that all of the base classes are accessible). Returns true
669/// and emits a diagnostic if the code is ill-formed, returns false
670/// otherwise. Loc is the location where this routine should point to
671/// if there is an error, and Range is the source range to highlight
672/// if there is an error.
673bool
674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
675 unsigned InaccessibleBaseID,
676 unsigned AmbigiousBaseConvID,
677 SourceLocation Loc, SourceRange Range,
678 DeclarationName Name) {
679 // First, determine whether the path from Derived to Base is
680 // ambiguous. This is slightly more expensive than checking whether
681 // the Derived to Base conversion exists, because here we need to
682 // explore multiple paths to determine if there is an ambiguity.
683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
684 /*DetectVirtual=*/false);
685 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
686 assert(DerivationOkay &&
687 "Can only be used with a derived-to-base conversion");
688 (void)DerivationOkay;
689
690 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
691 // Check that the base class can be accessed.
692 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
693 Name);
694 }
695
696 // We know that the derived-to-base conversion is ambiguous, and
697 // we're going to produce a diagnostic. Perform the derived-to-base
698 // search just one more time to compute all of the possible paths so
699 // that we can print them out. This is more expensive than any of
700 // the previous derived-to-base checks we've done, but at this point
701 // performance isn't as much of an issue.
702 Paths.clear();
703 Paths.setRecordingPaths(true);
704 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
705 assert(StillOkay && "Can only be used with a derived-to-base conversion");
706 (void)StillOkay;
707
708 // Build up a textual representation of the ambiguous paths, e.g.,
709 // D -> B -> A, that will be used to illustrate the ambiguous
710 // conversions in the diagnostic. We only print one of the paths
711 // to each base class subobject.
712 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
713
714 Diag(Loc, AmbigiousBaseConvID)
715 << Derived << Base << PathDisplayStr << Range << Name;
716 return true;
717}
718
719bool
720Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
721 SourceLocation Loc, SourceRange Range) {
722 return CheckDerivedToBaseConversion(Derived, Base,
723 diag::err_conv_to_inaccessible_base,
724 diag::err_ambiguous_derived_to_base_conv,
725 Loc, Range, DeclarationName());
726}
727
728
729/// @brief Builds a string representing ambiguous paths from a
730/// specific derived class to different subobjects of the same base
731/// class.
732///
733/// This function builds a string that can be used in error messages
734/// to show the different paths that one can take through the
735/// inheritance hierarchy to go from the derived class to different
736/// subobjects of a base class. The result looks something like this:
737/// @code
738/// struct D -> struct B -> struct A
739/// struct D -> struct C -> struct A
740/// @endcode
741std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
742 std::string PathDisplayStr;
743 std::set<unsigned> DisplayedPaths;
744 for (CXXBasePaths::paths_iterator Path = Paths.begin();
745 Path != Paths.end(); ++Path) {
746 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
747 // We haven't displayed a path to this particular base
748 // class subobject yet.
749 PathDisplayStr += "\n ";
750 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
751 for (CXXBasePath::const_iterator Element = Path->begin();
752 Element != Path->end(); ++Element)
753 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
754 }
755 }
756
757 return PathDisplayStr;
758}
759
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000760//===----------------------------------------------------------------------===//
761// C++ class member Handling
762//===----------------------------------------------------------------------===//
763
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000764/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
765/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
766/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000767/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000768Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000769Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000770 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000771 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000772 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000773 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000774 Expr *BitWidth = static_cast<Expr*>(BW);
775 Expr *Init = static_cast<Expr*>(InitExpr);
776 SourceLocation Loc = D.getIdentifierLoc();
777
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000778 bool isFunc = D.isFunctionDeclarator();
779
John McCall07e91c02009-08-06 02:15:43 +0000780 assert(!DS.isFriendSpecified());
781
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000782 // C++ 9.2p6: A member shall not be declared to have automatic storage
783 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000784 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
785 // data members and cannot be applied to names declared const or static,
786 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000787 switch (DS.getStorageClassSpec()) {
788 case DeclSpec::SCS_unspecified:
789 case DeclSpec::SCS_typedef:
790 case DeclSpec::SCS_static:
791 // FALL THROUGH.
792 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000793 case DeclSpec::SCS_mutable:
794 if (isFunc) {
795 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000796 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000797 else
Chris Lattner3b054132008-11-19 05:08:23 +0000798 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Sebastian Redl8071edb2008-11-17 23:24:37 +0000800 // FIXME: It would be nicer if the keyword was ignored only for this
801 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000802 D.getMutableDeclSpec().ClearStorageClassSpecs();
803 } else {
804 QualType T = GetTypeForDeclarator(D, S);
805 diag::kind err = static_cast<diag::kind>(0);
806 if (T->isReferenceType())
807 err = diag::err_mutable_reference;
808 else if (T.isConstQualified())
809 err = diag::err_mutable_const;
810 if (err != 0) {
811 if (DS.getStorageClassSpecLoc().isValid())
812 Diag(DS.getStorageClassSpecLoc(), err);
813 else
814 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000815 // FIXME: It would be nicer if the keyword was ignored only for this
816 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000817 D.getMutableDeclSpec().ClearStorageClassSpecs();
818 }
819 }
820 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000821 default:
822 if (DS.getStorageClassSpecLoc().isValid())
823 Diag(DS.getStorageClassSpecLoc(),
824 diag::err_storageclass_invalid_for_member);
825 else
826 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000830 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000831 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000832 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000833 // Check also for this case:
834 //
835 // typedef int f();
836 // f a;
837 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000838 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000839 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000840 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000841
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000842 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
843 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000844 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000845
846 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000847 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000848 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000849 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
850 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000851 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000852 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000853 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
854 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000855 if (!Member) {
856 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000857 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000858 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000859
860 // Non-instance-fields can't have a bitfield.
861 if (BitWidth) {
862 if (Member->isInvalidDecl()) {
863 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000864 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000865 // C++ 9.6p3: A bit-field shall not be a static member.
866 // "static member 'A' cannot be a bit-field"
867 Diag(Loc, diag::err_static_not_bitfield)
868 << Name << BitWidth->getSourceRange();
869 } else if (isa<TypedefDecl>(Member)) {
870 // "typedef member 'x' cannot be a bit-field"
871 Diag(Loc, diag::err_typedef_not_bitfield)
872 << Name << BitWidth->getSourceRange();
873 } else {
874 // A function typedef ("typedef int f(); f a;").
875 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
876 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000877 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000878 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000879 }
Mike Stump11289f42009-09-09 15:08:12 +0000880
Chris Lattnerd26760a2009-03-05 23:01:03 +0000881 DeleteExpr(BitWidth);
882 BitWidth = 0;
883 Member->setInvalidDecl();
884 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000885
886 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor3447e762009-08-20 22:52:58 +0000888 // If we have declared a member function template, set the access of the
889 // templated declaration as well.
890 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
891 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000892 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893
Douglas Gregor92751d42008-11-17 22:58:34 +0000894 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000895
Douglas Gregor0c880302009-03-11 23:00:04 +0000896 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000897 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000898 if (Deleted) // FIXME: Source location is not very good.
899 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000902 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000903 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000904 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000905 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000906}
907
Douglas Gregore8381c02008-11-05 04:29:56 +0000908/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000909Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000910Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000911 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000912 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000913 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000914 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000915 SourceLocation IdLoc,
916 SourceLocation LParenLoc,
917 ExprTy **Args, unsigned NumArgs,
918 SourceLocation *CommaLocs,
919 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000920 if (!ConstructorD)
921 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000923 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000924
925 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000926 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000927 if (!Constructor) {
928 // The user wrote a constructor initializer on a function that is
929 // not a C++ constructor. Ignore the error for now, because we may
930 // have more member initializers coming; we'll diagnose it just
931 // once in ActOnMemInitializers.
932 return true;
933 }
934
935 CXXRecordDecl *ClassDecl = Constructor->getParent();
936
937 // C++ [class.base.init]p2:
938 // Names in a mem-initializer-id are looked up in the scope of the
939 // constructor’s class and, if not found in that scope, are looked
940 // up in the scope containing the constructor’s
941 // definition. [Note: if the constructor’s class contains a member
942 // with the same name as a direct or virtual base class of the
943 // class, a mem-initializer-id naming the member or base class and
944 // composed of a single identifier refers to the class member. A
945 // mem-initializer-id for the hidden base class may be specified
946 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000947 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000948 // Look for a member, first.
949 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000950 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000951 = ClassDecl->lookup(MemberOrBase);
952 if (Result.first != Result.second)
953 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000954
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000955 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000956
Eli Friedman8e1433b2009-07-29 19:44:27 +0000957 if (Member)
958 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
959 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000960 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000961 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000962 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000963 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000964 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000965 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
966 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000968 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000969
Eli Friedman8e1433b2009-07-29 19:44:27 +0000970 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
971 RParenLoc, ClassDecl);
972}
973
John McCalle22a04a2009-11-04 23:02:40 +0000974/// Checks an initializer expression for use of uninitialized fields, such as
975/// containing the field that is being initialized. Returns true if there is an
976/// uninitialized field was used an updates the SourceLocation parameter; false
977/// otherwise.
978static bool InitExprContainsUninitializedFields(const Stmt* S,
979 const FieldDecl* LhsField,
980 SourceLocation* L) {
981 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
982 if (ME) {
983 const NamedDecl* RhsField = ME->getMemberDecl();
984 if (RhsField == LhsField) {
985 // Initializing a field with itself. Throw a warning.
986 // But wait; there are exceptions!
987 // Exception #1: The field may not belong to this record.
988 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
989 const Expr* base = ME->getBase();
990 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
991 // Even though the field matches, it does not belong to this record.
992 return false;
993 }
994 // None of the exceptions triggered; return true to indicate an
995 // uninitialized field was used.
996 *L = ME->getMemberLoc();
997 return true;
998 }
999 }
1000 bool found = false;
1001 for (Stmt::const_child_iterator it = S->child_begin();
1002 it != S->child_end() && found == false;
1003 ++it) {
1004 if (isa<CallExpr>(S)) {
1005 // Do not descend into function calls or constructors, as the use
1006 // of an uninitialized field may be valid. One would have to inspect
1007 // the contents of the function/ctor to determine if it is safe or not.
1008 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1009 // may be safe, depending on what the function/ctor does.
1010 continue;
1011 }
1012 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1013 }
1014 return found;
1015}
1016
Eli Friedman8e1433b2009-07-29 19:44:27 +00001017Sema::MemInitResult
1018Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1019 unsigned NumArgs, SourceLocation IdLoc,
1020 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001021 // Diagnose value-uses of fields to initialize themselves, e.g.
1022 // foo(foo)
1023 // where foo is not also a parameter to the constructor.
1024 for (unsigned i = 0; i < NumArgs; ++i) {
1025 SourceLocation L;
1026 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1027 // FIXME: Return true in the case when other fields are used before being
1028 // uninitialized. For example, let this field be the i'th field. When
1029 // initializing the i'th field, throw a warning if any of the >= i'th
1030 // fields are used, as they are not yet initialized.
1031 // Right now we are only handling the case where the i'th field uses
1032 // itself in its initializer.
1033 Diag(L, diag::warn_field_is_uninit);
1034 }
1035 }
1036
Eli Friedman8e1433b2009-07-29 19:44:27 +00001037 bool HasDependentArg = false;
1038 for (unsigned i = 0; i < NumArgs; i++)
1039 HasDependentArg |= Args[i]->isTypeDependent();
1040
1041 CXXConstructorDecl *C = 0;
1042 QualType FieldType = Member->getType();
1043 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1044 FieldType = Array->getElementType();
1045 if (FieldType->isDependentType()) {
1046 // Can't check init for dependent type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001048 if (!HasDependentArg) {
1049 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1050
1051 C = PerformInitializationByConstructor(FieldType,
1052 MultiExprArg(*this,
1053 (void**)Args,
1054 NumArgs),
1055 IdLoc,
1056 SourceRange(IdLoc, RParenLoc),
1057 Member->getDeclName(), IK_Direct,
1058 ConstructorArgs);
1059
1060 if (C) {
1061 // Take over the constructor arguments as our own.
1062 NumArgs = ConstructorArgs.size();
1063 Args = (Expr **)ConstructorArgs.take();
1064 }
1065 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001066 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump11289f42009-09-09 15:08:12 +00001067 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001068 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1069 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001070 Expr *NewExp;
1071 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001072 if (FieldType->isReferenceType()) {
1073 Diag(IdLoc, diag::err_null_intialized_reference_member)
1074 << Member->getDeclName();
1075 return Diag(Member->getLocation(), diag::note_declared_at);
1076 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001077 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1078 NumArgs = 1;
1079 }
1080 else
1081 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001082 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1083 return true;
1084 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001085 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001086 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001087 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001088 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001089}
1090
1091Sema::MemInitResult
1092Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1093 unsigned NumArgs, SourceLocation IdLoc,
1094 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1095 bool HasDependentArg = false;
1096 for (unsigned i = 0; i < NumArgs; i++)
1097 HasDependentArg |= Args[i]->isTypeDependent();
1098
1099 if (!BaseType->isDependentType()) {
1100 if (!BaseType->isRecordType())
1101 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1102 << BaseType << SourceRange(IdLoc, RParenLoc);
1103
1104 // C++ [class.base.init]p2:
1105 // [...] Unless the mem-initializer-id names a nonstatic data
1106 // member of the constructor’s class or a direct or virtual base
1107 // of that class, the mem-initializer is ill-formed. A
1108 // mem-initializer-list can initialize a base class using any
1109 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001110
Eli Friedman8e1433b2009-07-29 19:44:27 +00001111 // First, check for a direct base class.
1112 const CXXBaseSpecifier *DirectBaseSpec = 0;
1113 for (CXXRecordDecl::base_class_const_iterator Base =
1114 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +00001115 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +00001116 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1117 // We found a direct base of this type. That's what we're
1118 // initializing.
1119 DirectBaseSpec = &*Base;
1120 break;
1121 }
1122 }
Mike Stump11289f42009-09-09 15:08:12 +00001123
Eli Friedman8e1433b2009-07-29 19:44:27 +00001124 // Check for a virtual base class.
1125 // FIXME: We might be able to short-circuit this if we know in advance that
1126 // there are no virtual bases.
1127 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1128 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1129 // We haven't found a base yet; search the class hierarchy for a
1130 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001131 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1132 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001133 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001134 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001135 Path != Paths.end(); ++Path) {
1136 if (Path->back().Base->isVirtual()) {
1137 VirtualBaseSpec = Path->back().Base;
1138 break;
1139 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001140 }
1141 }
1142 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001143
1144 // C++ [base.class.init]p2:
1145 // If a mem-initializer-id is ambiguous because it designates both
1146 // a direct non-virtual base class and an inherited virtual base
1147 // class, the mem-initializer is ill-formed.
1148 if (DirectBaseSpec && VirtualBaseSpec)
1149 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1150 << BaseType << SourceRange(IdLoc, RParenLoc);
1151 // C++ [base.class.init]p2:
1152 // Unless the mem-initializer-id names a nonstatic data membeer of the
1153 // constructor's class ot a direst or virtual base of that class, the
1154 // mem-initializer is ill-formed.
1155 if (!DirectBaseSpec && !VirtualBaseSpec)
1156 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1157 << BaseType << ClassDecl->getNameAsCString()
1158 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001159 }
1160
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001161 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001162 if (!BaseType->isDependentType() && !HasDependentArg) {
1163 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
1164 Context.getCanonicalType(BaseType));
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001165 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1166
1167 C = PerformInitializationByConstructor(BaseType,
1168 MultiExprArg(*this,
1169 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001170 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001171 Name, IK_Direct,
1172 ConstructorArgs);
1173 if (C) {
1174 // Take over the constructor arguments as our own.
1175 NumArgs = ConstructorArgs.size();
1176 Args = (Expr **)ConstructorArgs.take();
1177 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001178 }
1179
Mike Stump11289f42009-09-09 15:08:12 +00001180 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001181 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001182}
1183
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001184void
Anders Carlsson561f7932009-10-29 15:46:07 +00001185Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001186 CXXBaseOrMemberInitializer **Initializers,
1187 unsigned NumInitializers,
Mike Stump11289f42009-09-09 15:08:12 +00001188 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001189 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
1190 // We need to build the initializer AST according to order of construction
1191 // and not what user specified in the Initializers list.
1192 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1193 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1194 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1195 bool HasDependentBaseInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001196
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001197 for (unsigned i = 0; i < NumInitializers; i++) {
1198 CXXBaseOrMemberInitializer *Member = Initializers[i];
1199 if (Member->isBaseInitializer()) {
1200 if (Member->getBaseClass()->isDependentType())
1201 HasDependentBaseInit = true;
1202 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1203 } else {
1204 AllBaseFields[Member->getMember()] = Member;
1205 }
1206 }
Mike Stump11289f42009-09-09 15:08:12 +00001207
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001208 if (HasDependentBaseInit) {
1209 // FIXME. This does not preserve the ordering of the initializers.
1210 // Try (with -Wreorder)
1211 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001212 // template<class X> struct B : A<X> {
1213 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001214 // int x1;
1215 // };
1216 // B<int> x;
1217 // On seeing one dependent type, we should essentially exit this routine
1218 // while preserving user-declared initializer list. When this routine is
1219 // called during instantiatiation process, this routine will rebuild the
1220 // oderdered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001221
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001222 // If we have a dependent base initialization, we can't determine the
1223 // association between initializers and bases; just dump the known
1224 // initializers into the list, and don't try to deal with other bases.
1225 for (unsigned i = 0; i < NumInitializers; i++) {
1226 CXXBaseOrMemberInitializer *Member = Initializers[i];
1227 if (Member->isBaseInitializer())
1228 AllToInit.push_back(Member);
1229 }
1230 } else {
1231 // Push virtual bases before others.
1232 for (CXXRecordDecl::base_class_iterator VBase =
1233 ClassDecl->vbases_begin(),
1234 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1235 if (VBase->getType()->isDependentType())
1236 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001237 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001238 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001239 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001240 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001241 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001242 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1243 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001244 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001245 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001246 else {
Mike Stump11289f42009-09-09 15:08:12 +00001247 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001248 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001249 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001250 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001251 if (!Ctor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001252 Bases.push_back(VBase);
Anders Carlsson561f7932009-10-29 15:46:07 +00001253 continue;
1254 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001255
Anders Carlsson561f7932009-10-29 15:46:07 +00001256 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1257 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1258 Constructor->getLocation(), CtorArgs))
1259 continue;
1260
1261 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1262
Mike Stump11289f42009-09-09 15:08:12 +00001263 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001264 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1265 CtorArgs.takeAs<Expr>(),
1266 CtorArgs.size(), Ctor,
1267 SourceLocation(),
1268 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001269 AllToInit.push_back(Member);
1270 }
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001273 for (CXXRecordDecl::base_class_iterator Base =
1274 ClassDecl->bases_begin(),
1275 E = ClassDecl->bases_end(); Base != E; ++Base) {
1276 // Virtuals are in the virtual base list and already constructed.
1277 if (Base->isVirtual())
1278 continue;
1279 // Skip dependent types.
1280 if (Base->getType()->isDependentType())
1281 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001282 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001283 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001284 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001285 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001286 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001287 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1288 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001289 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001290 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001291 else {
Mike Stump11289f42009-09-09 15:08:12 +00001292 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001293 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001294 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001295 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001296 if (!Ctor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001297 Bases.push_back(Base);
Anders Carlsson561f7932009-10-29 15:46:07 +00001298 continue;
1299 }
1300
1301 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1302 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1303 Constructor->getLocation(), CtorArgs))
1304 continue;
1305
1306 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001307
Mike Stump11289f42009-09-09 15:08:12 +00001308 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001309 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1310 CtorArgs.takeAs<Expr>(),
1311 CtorArgs.size(), Ctor,
1312 SourceLocation(),
1313 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001314 AllToInit.push_back(Member);
1315 }
1316 }
1317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001319 // non-static data members.
1320 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1321 E = ClassDecl->field_end(); Field != E; ++Field) {
1322 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001323 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001324 Field->getType()->getAs<RecordType>()) {
1325 CXXRecordDecl *FieldClassDecl
1326 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001327 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001328 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1329 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1330 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1331 // set to the anonymous union data member used in the initializer
1332 // list.
1333 Value->setMember(*Field);
1334 Value->setAnonUnionMember(*FA);
1335 AllToInit.push_back(Value);
1336 break;
1337 }
1338 }
1339 }
1340 continue;
1341 }
1342 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001343 QualType FT = (*Field)->getType();
1344 if (const RecordType* RT = FT->getAs<RecordType>()) {
1345 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001346 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump11289f42009-09-09 15:08:12 +00001347 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001348 FieldRecDecl->getDefaultConstructor(Context))
1349 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1350 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001351 AllToInit.push_back(Value);
1352 continue;
1353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregor2de8f412009-11-04 17:16:11 +00001355 if ((*Field)->getType()->isDependentType()) {
1356 Fields.push_back(*Field);
1357 continue;
1358 }
1359
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001360 QualType FT = Context.getBaseElementType((*Field)->getType());
1361 if (const RecordType* RT = FT->getAs<RecordType>()) {
1362 CXXConstructorDecl *Ctor =
1363 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001364 if (!Ctor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001365 Fields.push_back(*Field);
Anders Carlsson561f7932009-10-29 15:46:07 +00001366 continue;
1367 }
1368
1369 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1370 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1371 Constructor->getLocation(), CtorArgs))
1372 continue;
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001375 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1376 CtorArgs.size(), Ctor,
1377 SourceLocation(),
1378 SourceLocation());
1379
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001380 AllToInit.push_back(Member);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001381 if (Ctor)
1382 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001383 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1384 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1385 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1386 Diag((*Field)->getLocation(), diag::note_declared_at);
1387 }
1388 }
1389 else if (FT->isReferenceType()) {
1390 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1391 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1392 Diag((*Field)->getLocation(), diag::note_declared_at);
1393 }
1394 else if (FT.isConstQualified()) {
1395 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1396 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1397 Diag((*Field)->getLocation(), diag::note_declared_at);
1398 }
1399 }
Mike Stump11289f42009-09-09 15:08:12 +00001400
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001401 NumInitializers = AllToInit.size();
1402 if (NumInitializers > 0) {
1403 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1404 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1405 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001406
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001407 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1408 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1409 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1410 }
1411}
1412
1413void
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001414Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1415 CXXConstructorDecl *Constructor,
1416 CXXBaseOrMemberInitializer **Initializers,
1417 unsigned NumInitializers
1418 ) {
Anders Carlsson561f7932009-10-29 15:46:07 +00001419 llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1420 llvm::SmallVector<FieldDecl *, 4> Members;
Mike Stump11289f42009-09-09 15:08:12 +00001421
Anders Carlsson561f7932009-10-29 15:46:07 +00001422 SetBaseOrMemberInitializers(Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001423 Initializers, NumInitializers, Bases, Members);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001424 for (unsigned int i = 0; i < Bases.size(); i++) {
1425 if (!Bases[i]->getType()->isDependentType())
1426 Diag(Bases[i]->getSourceRange().getBegin(),
1427 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1428 }
1429 for (unsigned int i = 0; i < Members.size(); i++) {
1430 if (!Members[i]->getType()->isDependentType())
1431 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
1432 << 1 << Members[i]->getType();
1433 }
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001434}
1435
Eli Friedman952c15d2009-07-21 19:28:10 +00001436static void *GetKeyForTopLevelField(FieldDecl *Field) {
1437 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001438 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001439 if (RT->getDecl()->isAnonymousStructOrUnion())
1440 return static_cast<void *>(RT->getDecl());
1441 }
1442 return static_cast<void *>(Field);
1443}
1444
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001445static void *GetKeyForBase(QualType BaseType) {
1446 if (const RecordType *RT = BaseType->getAs<RecordType>())
1447 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001448
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001449 assert(0 && "Unexpected base type!");
1450 return 0;
1451}
1452
Mike Stump11289f42009-09-09 15:08:12 +00001453static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001454 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001455 // For fields injected into the class via declaration of an anonymous union,
1456 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001457 if (Member->isMemberInitializer()) {
1458 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001459
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001460 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001461 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001462 // in AnonUnionMember field.
1463 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1464 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001465 if (Field->getDeclContext()->isRecord()) {
1466 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1467 if (RD->isAnonymousStructOrUnion())
1468 return static_cast<void *>(RD);
1469 }
1470 return static_cast<void *>(Field);
1471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001473 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001474}
1475
Mike Stump11289f42009-09-09 15:08:12 +00001476void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001477 SourceLocation ColonLoc,
1478 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001479 if (!ConstructorDecl)
1480 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001481
1482 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001483
1484 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001485 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001486
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001487 if (!Constructor) {
1488 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1489 return;
1490 }
Mike Stump11289f42009-09-09 15:08:12 +00001491
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001492 if (!Constructor->isDependentContext()) {
1493 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1494 bool err = false;
1495 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001496 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001497 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1498 void *KeyToMember = GetKeyForMember(Member);
1499 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1500 if (!PrevMember) {
1501 PrevMember = Member;
1502 continue;
1503 }
1504 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001505 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001506 diag::error_multiple_mem_initialization)
1507 << Field->getNameAsString();
1508 else {
1509 Type *BaseClass = Member->getBaseClass();
1510 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001511 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001512 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001513 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001514 }
1515 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1516 << 0;
1517 err = true;
1518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001520 if (err)
1521 return;
1522 }
Mike Stump11289f42009-09-09 15:08:12 +00001523
Anders Carlssone0eebb32009-08-27 05:45:01 +00001524 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001525 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001526 NumMemInits);
Mike Stump11289f42009-09-09 15:08:12 +00001527
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001528 if (Constructor->isDependentContext())
1529 return;
Mike Stump11289f42009-09-09 15:08:12 +00001530
1531 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001532 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001533 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001534 Diagnostic::Ignored)
1535 return;
Mike Stump11289f42009-09-09 15:08:12 +00001536
Anders Carlssone0eebb32009-08-27 05:45:01 +00001537 // Also issue warning if order of ctor-initializer list does not match order
1538 // of 1) base class declarations and 2) order of non-static data members.
1539 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001540
Anders Carlssone0eebb32009-08-27 05:45:01 +00001541 CXXRecordDecl *ClassDecl
1542 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1543 // Push virtual bases before others.
1544 for (CXXRecordDecl::base_class_iterator VBase =
1545 ClassDecl->vbases_begin(),
1546 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001547 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001548
Anders Carlssone0eebb32009-08-27 05:45:01 +00001549 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1550 E = ClassDecl->bases_end(); Base != E; ++Base) {
1551 // Virtuals are alread in the virtual base list and are constructed
1552 // first.
1553 if (Base->isVirtual())
1554 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001555 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001556 }
Mike Stump11289f42009-09-09 15:08:12 +00001557
Anders Carlssone0eebb32009-08-27 05:45:01 +00001558 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1559 E = ClassDecl->field_end(); Field != E; ++Field)
1560 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001561
Anders Carlssone0eebb32009-08-27 05:45:01 +00001562 int Last = AllBaseOrMembers.size();
1563 int curIndex = 0;
1564 CXXBaseOrMemberInitializer *PrevMember = 0;
1565 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001566 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001567 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1568 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001569
Anders Carlssone0eebb32009-08-27 05:45:01 +00001570 for (; curIndex < Last; curIndex++)
1571 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1572 break;
1573 if (curIndex == Last) {
1574 assert(PrevMember && "Member not in member list?!");
1575 // Initializer as specified in ctor-initializer list is out of order.
1576 // Issue a warning diagnostic.
1577 if (PrevMember->isBaseInitializer()) {
1578 // Diagnostics is for an initialized base class.
1579 Type *BaseClass = PrevMember->getBaseClass();
1580 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001581 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001582 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001583 } else {
1584 FieldDecl *Field = PrevMember->getMember();
1585 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001586 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001587 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001588 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001589 // Also the note!
1590 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001591 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001592 diag::note_fieldorbase_initialized_here) << 0
1593 << Field->getNameAsString();
1594 else {
1595 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001596 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001597 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001598 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001599 }
1600 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001601 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001602 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001603 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001604 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001605 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001606}
1607
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001608void
1609Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1610 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1611 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001612
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001613 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1614 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1615 if (VBase->getType()->isDependentType())
1616 continue;
1617 // Skip over virtual bases which have trivial destructors.
1618 CXXRecordDecl *BaseClassDecl
1619 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1620 if (BaseClassDecl->hasTrivialDestructor())
1621 continue;
1622 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001623 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001624 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001625
1626 uintptr_t Member =
1627 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001628 | CXXDestructorDecl::VBASE;
1629 AllToDestruct.push_back(Member);
1630 }
1631 for (CXXRecordDecl::base_class_iterator Base =
1632 ClassDecl->bases_begin(),
1633 E = ClassDecl->bases_end(); Base != E; ++Base) {
1634 if (Base->isVirtual())
1635 continue;
1636 if (Base->getType()->isDependentType())
1637 continue;
1638 // Skip over virtual bases which have trivial destructors.
1639 CXXRecordDecl *BaseClassDecl
1640 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1641 if (BaseClassDecl->hasTrivialDestructor())
1642 continue;
1643 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001644 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001645 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001646 uintptr_t Member =
1647 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001648 | CXXDestructorDecl::DRCTNONVBASE;
1649 AllToDestruct.push_back(Member);
1650 }
Mike Stump11289f42009-09-09 15:08:12 +00001651
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001652 // non-static data members.
1653 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1654 E = ClassDecl->field_end(); Field != E; ++Field) {
1655 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001656
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001657 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1658 // Skip over virtual bases which have trivial destructors.
1659 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1660 if (FieldClassDecl->hasTrivialDestructor())
1661 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001662 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001663 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001664 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001665 const_cast<CXXDestructorDecl*>(Dtor));
1666 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1667 AllToDestruct.push_back(Member);
1668 }
1669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001671 unsigned NumDestructions = AllToDestruct.size();
1672 if (NumDestructions > 0) {
1673 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001674 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001675 new (Context) uintptr_t [NumDestructions];
1676 // Insert in reverse order.
1677 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1678 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1679 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1680 }
1681}
1682
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001683void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001684 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001685 return;
Mike Stump11289f42009-09-09 15:08:12 +00001686
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001687 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001688
1689 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001690 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001691 BuildBaseOrMemberInitializers(Context,
1692 Constructor,
1693 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001694}
1695
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001696namespace {
1697 /// PureVirtualMethodCollector - traverses a class and its superclasses
1698 /// and determines if it has any pure virtual methods.
1699 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1700 ASTContext &Context;
1701
Sebastian Redlb7d64912009-03-22 21:28:55 +00001702 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001703 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001704
1705 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001706 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001707
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001708 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001710 public:
Mike Stump11289f42009-09-09 15:08:12 +00001711 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001712 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001713
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001714 MethodList List;
1715 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001716
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001717 // Copy the temporary list to methods, and make sure to ignore any
1718 // null entries.
1719 for (size_t i = 0, e = List.size(); i != e; ++i) {
1720 if (List[i])
1721 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001722 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001723 }
Mike Stump11289f42009-09-09 15:08:12 +00001724
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001725 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001727 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1728 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001729 };
Mike Stump11289f42009-09-09 15:08:12 +00001730
1731 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001732 MethodList& Methods) {
1733 // First, collect the pure virtual methods for the base classes.
1734 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1735 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001736 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001737 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001738 if (BaseDecl && BaseDecl->isAbstract())
1739 Collect(BaseDecl, Methods);
1740 }
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001743 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001744 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Anders Carlsson3c012712009-05-17 00:00:05 +00001746 MethodSetTy OverriddenMethods;
1747 size_t MethodsSize = Methods.size();
1748
Mike Stump11289f42009-09-09 15:08:12 +00001749 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001750 i != e; ++i) {
1751 // Traverse the record, looking for methods.
1752 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001753 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001754 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001755 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001756
Anders Carlsson700179432009-10-18 19:34:08 +00001757 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001758 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1759 E = MD->end_overridden_methods(); I != E; ++I) {
1760 // Keep track of the overridden methods.
1761 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001762 }
1763 }
1764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
1766 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001767 // overridden.
1768 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1769 if (OverriddenMethods.count(Methods[i]))
1770 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001771 }
Mike Stump11289f42009-09-09 15:08:12 +00001772
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001773 }
1774}
Douglas Gregore8381c02008-11-05 04:29:56 +00001775
Anders Carlssoneabf7702009-08-27 00:13:57 +00001776
Mike Stump11289f42009-09-09 15:08:12 +00001777bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001778 unsigned DiagID, AbstractDiagSelID SelID,
1779 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001780 if (SelID == -1)
1781 return RequireNonAbstractType(Loc, T,
1782 PDiag(DiagID), CurrentRD);
1783 else
1784 return RequireNonAbstractType(Loc, T,
1785 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001786}
1787
Anders Carlssoneabf7702009-08-27 00:13:57 +00001788bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1789 const PartialDiagnostic &PD,
1790 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001791 if (!getLangOptions().CPlusPlus)
1792 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001794 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001795 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001796 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001797
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001798 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001799 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001800 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001801 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001802
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001803 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001804 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001807 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001808 if (!RT)
1809 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001810
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001811 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1812 if (!RD)
1813 return false;
1814
Anders Carlssonb57738b2009-03-24 17:23:42 +00001815 if (CurrentRD && CurrentRD != RD)
1816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001817
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001818 if (!RD->isAbstract())
1819 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Anders Carlssoneabf7702009-08-27 00:13:57 +00001821 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001822
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001823 // Check if we've already emitted the list of pure virtual functions for this
1824 // class.
1825 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1826 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001827
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001828 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001829
1830 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001831 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1832 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001833
1834 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001835 MD->getDeclName();
1836 }
1837
1838 if (!PureVirtualClassDiagSet)
1839 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1840 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001841
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001842 return true;
1843}
1844
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001845namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001846 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001847 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1848 Sema &SemaRef;
1849 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001850
Anders Carlssonb57738b2009-03-24 17:23:42 +00001851 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001852 bool Invalid = false;
1853
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001854 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1855 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001856 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001857
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001858 return Invalid;
1859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Anders Carlssonb57738b2009-03-24 17:23:42 +00001861 public:
1862 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1863 : SemaRef(SemaRef), AbstractClass(ac) {
1864 Visit(SemaRef.Context.getTranslationUnitDecl());
1865 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001866
Anders Carlssonb57738b2009-03-24 17:23:42 +00001867 bool VisitFunctionDecl(const FunctionDecl *FD) {
1868 if (FD->isThisDeclarationADefinition()) {
1869 // No need to do the check if we're in a definition, because it requires
1870 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001871 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001872 return VisitDeclContext(FD);
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Anders Carlssonb57738b2009-03-24 17:23:42 +00001875 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001876 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001877 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001878 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1879 diag::err_abstract_type_in_decl,
1880 Sema::AbstractReturnType,
1881 AbstractClass);
1882
Mike Stump11289f42009-09-09 15:08:12 +00001883 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001884 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001885 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001886 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001887 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001888 VD->getOriginalType(),
1889 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001890 Sema::AbstractParamType,
1891 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001892 }
1893
1894 return Invalid;
1895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Anders Carlssonb57738b2009-03-24 17:23:42 +00001897 bool VisitDecl(const Decl* D) {
1898 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1899 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001900
Anders Carlssonb57738b2009-03-24 17:23:42 +00001901 return false;
1902 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001903 };
1904}
1905
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001906void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001907 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001908 SourceLocation LBrac,
1909 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001910 if (!TagDecl)
1911 return;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001913 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001914 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001915 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001916 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001917
Chris Lattner83f095c2009-03-28 19:18:32 +00001918 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001919 if (!RD->isAbstract()) {
1920 // Collect all the pure virtual methods and see if this is an abstract
1921 // class after all.
1922 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001923 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001924 RD->setAbstract(true);
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
1927 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001928 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregor3c74d412009-10-14 20:14:33 +00001930 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001931 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932}
1933
Douglas Gregor05379422008-11-03 17:51:48 +00001934/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1935/// special functions, such as the default constructor, copy
1936/// constructor, or destructor, to the given C++ class (C++
1937/// [special]p1). This routine can only be executed just before the
1938/// definition of the class is complete.
1939void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001941 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001942
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001943 // FIXME: Implicit declarations have exception specifications, which are
1944 // the union of the specifications of the implicitly called functions.
1945
Douglas Gregor05379422008-11-03 17:51:48 +00001946 if (!ClassDecl->hasUserDeclaredConstructor()) {
1947 // C++ [class.ctor]p5:
1948 // A default constructor for a class X is a constructor of class X
1949 // that can be called without an argument. If there is no
1950 // user-declared constructor for class X, a default constructor is
1951 // implicitly declared. An implicitly-declared default constructor
1952 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001953 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001954 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001955 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001956 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001957 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001958 Context.getFunctionType(Context.VoidTy,
1959 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001960 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001961 /*isExplicit=*/false,
1962 /*isInline=*/true,
1963 /*isImplicitlyDeclared=*/true);
1964 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001965 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001966 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001967 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001968 }
1969
1970 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1971 // C++ [class.copy]p4:
1972 // If the class definition does not explicitly declare a copy
1973 // constructor, one is declared implicitly.
1974
1975 // C++ [class.copy]p5:
1976 // The implicitly-declared copy constructor for a class X will
1977 // have the form
1978 //
1979 // X::X(const X&)
1980 //
1981 // if
1982 bool HasConstCopyConstructor = true;
1983
1984 // -- each direct or virtual base class B of X has a copy
1985 // constructor whose first parameter is of type const B& or
1986 // const volatile B&, and
1987 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1988 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1989 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001990 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001991 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001992 = BaseClassDecl->hasConstCopyConstructor(Context);
1993 }
1994
1995 // -- for all the nonstatic data members of X that are of a
1996 // class type M (or array thereof), each such class type
1997 // has a copy constructor whose first parameter is of type
1998 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001999 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2000 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002001 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002002 QualType FieldType = (*Field)->getType();
2003 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2004 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002005 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002006 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002007 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002008 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002009 = FieldClassDecl->hasConstCopyConstructor(Context);
2010 }
2011 }
2012
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002013 // Otherwise, the implicitly declared copy constructor will have
2014 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002015 //
2016 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002017 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002018 if (HasConstCopyConstructor)
2019 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002020 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002021
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002022 // An implicitly-declared copy constructor is an inline public
2023 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002024 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002025 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002026 CXXConstructorDecl *CopyConstructor
2027 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002028 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002029 Context.getFunctionType(Context.VoidTy,
2030 &ArgType, 1,
2031 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002032 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002033 /*isExplicit=*/false,
2034 /*isInline=*/true,
2035 /*isImplicitlyDeclared=*/true);
2036 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002037 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002038 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002039
2040 // Add the parameter to the constructor.
2041 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2042 ClassDecl->getLocation(),
2043 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002044 ArgType, /*DInfo=*/0,
2045 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002046 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002047 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002048 }
2049
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002050 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2051 // Note: The following rules are largely analoguous to the copy
2052 // constructor rules. Note that virtual bases are not taken into account
2053 // for determining the argument type of the operator. Note also that
2054 // operators taking an object instead of a reference are allowed.
2055 //
2056 // C++ [class.copy]p10:
2057 // If the class definition does not explicitly declare a copy
2058 // assignment operator, one is declared implicitly.
2059 // The implicitly-defined copy assignment operator for a class X
2060 // will have the form
2061 //
2062 // X& X::operator=(const X&)
2063 //
2064 // if
2065 bool HasConstCopyAssignment = true;
2066
2067 // -- each direct base class B of X has a copy assignment operator
2068 // whose parameter is of type const B&, const volatile B& or B,
2069 // and
2070 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2071 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002072 assert(!Base->getType()->isDependentType() &&
2073 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002074 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002075 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002076 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002077 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002078 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002079 }
2080
2081 // -- for all the nonstatic data members of X that are of a class
2082 // type M (or array thereof), each such class type has a copy
2083 // assignment operator whose parameter is of type const M&,
2084 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002085 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2086 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002087 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002088 QualType FieldType = (*Field)->getType();
2089 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2090 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002091 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002092 const CXXRecordDecl *FieldClassDecl
2093 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002094 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002095 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002096 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002097 }
2098 }
2099
2100 // Otherwise, the implicitly declared copy assignment operator will
2101 // have the form
2102 //
2103 // X& X::operator=(X&)
2104 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002105 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002106 if (HasConstCopyAssignment)
2107 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002108 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002109
2110 // An implicitly-declared copy assignment operator is an inline public
2111 // member of its class.
2112 DeclarationName Name =
2113 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2114 CXXMethodDecl *CopyAssignment =
2115 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2116 Context.getFunctionType(RetType, &ArgType, 1,
2117 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002118 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002119 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002120 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002121 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002122 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002123
2124 // Add the parameter to the operator.
2125 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2126 ClassDecl->getLocation(),
2127 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002128 ArgType, /*DInfo=*/0,
2129 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002130 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002131
2132 // Don't call addedAssignmentOperator. There is no way to distinguish an
2133 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002134 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002135 }
2136
Douglas Gregor1349b452008-12-15 21:24:18 +00002137 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002138 // C++ [class.dtor]p2:
2139 // If a class has no user-declared destructor, a destructor is
2140 // declared implicitly. An implicitly-declared destructor is an
2141 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002142 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002143 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002144 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002145 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002146 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002147 Context.getFunctionType(Context.VoidTy,
2148 0, 0, false, 0),
2149 /*isInline=*/true,
2150 /*isImplicitlyDeclared=*/true);
2151 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002152 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002153 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002154 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002155 }
Douglas Gregor05379422008-11-03 17:51:48 +00002156}
2157
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002158void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002159 Decl *D = TemplateD.getAs<Decl>();
2160 if (!D)
2161 return;
2162
2163 TemplateParameterList *Params = 0;
2164 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2165 Params = Template->getTemplateParameters();
2166 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2167 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2168 Params = PartialSpec->getTemplateParameters();
2169 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002170 return;
2171
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002172 for (TemplateParameterList::iterator Param = Params->begin(),
2173 ParamEnd = Params->end();
2174 Param != ParamEnd; ++Param) {
2175 NamedDecl *Named = cast<NamedDecl>(*Param);
2176 if (Named->getDeclName()) {
2177 S->AddDecl(DeclPtrTy::make(Named));
2178 IdResolver.AddDecl(Named);
2179 }
2180 }
2181}
2182
Douglas Gregor4d87df52008-12-16 21:30:33 +00002183/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2184/// parsing a top-level (non-nested) C++ class, and we are now
2185/// parsing those parts of the given Method declaration that could
2186/// not be parsed earlier (C++ [class.mem]p2), such as default
2187/// arguments. This action should enter the scope of the given
2188/// Method declaration as if we had just parsed the qualified method
2189/// name. However, it should not bring the parameters into scope;
2190/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002191void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002192 if (!MethodD)
2193 return;
Mike Stump11289f42009-09-09 15:08:12 +00002194
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002195 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor4d87df52008-12-16 21:30:33 +00002197 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002198 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002199 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002200 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2201 SS.setScopeRep(
2202 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002203 ActOnCXXEnterDeclaratorScope(S, SS);
2204}
2205
2206/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2207/// C++ method declaration. We're (re-)introducing the given
2208/// function parameter into scope for use in parsing later parts of
2209/// the method declaration. For example, we could see an
2210/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002211void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002212 if (!ParamD)
2213 return;
Mike Stump11289f42009-09-09 15:08:12 +00002214
Chris Lattner83f095c2009-03-28 19:18:32 +00002215 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002216
2217 // If this parameter has an unparsed default argument, clear it out
2218 // to make way for the parsed default argument.
2219 if (Param->hasUnparsedDefaultArg())
2220 Param->setDefaultArg(0);
2221
Chris Lattner83f095c2009-03-28 19:18:32 +00002222 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002223 if (Param->getDeclName())
2224 IdResolver.AddDecl(Param);
2225}
2226
2227/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2228/// processing the delayed method declaration for Method. The method
2229/// declaration is now considered finished. There may be a separate
2230/// ActOnStartOfFunctionDef action later (not necessarily
2231/// immediately!) for this method, if it was also defined inside the
2232/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002233void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002234 if (!MethodD)
2235 return;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002237 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002238
Chris Lattner83f095c2009-03-28 19:18:32 +00002239 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002240 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002241 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002242 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2243 SS.setScopeRep(
2244 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002245 ActOnCXXExitDeclaratorScope(S, SS);
2246
2247 // Now that we have our default arguments, check the constructor
2248 // again. It could produce additional diagnostics or affect whether
2249 // the class has implicitly-declared destructors, among other
2250 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002251 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2252 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002253
2254 // Check the default arguments, which we may have added.
2255 if (!Method->isInvalidDecl())
2256 CheckCXXDefaultArguments(Method);
2257}
2258
Douglas Gregor831c93f2008-11-05 20:51:48 +00002259/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002260/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002261/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002262/// emit diagnostics and set the invalid bit to true. In any case, the type
2263/// will be updated to reflect a well-formed type for the constructor and
2264/// returned.
2265QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2266 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002267 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002268
2269 // C++ [class.ctor]p3:
2270 // A constructor shall not be virtual (10.3) or static (9.4). A
2271 // constructor can be invoked for a const, volatile or const
2272 // volatile object. A constructor shall not be declared const,
2273 // volatile, or const volatile (9.3.2).
2274 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002275 if (!D.isInvalidType())
2276 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2277 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2278 << SourceRange(D.getIdentifierLoc());
2279 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002280 }
2281 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002282 if (!D.isInvalidType())
2283 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2284 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2285 << SourceRange(D.getIdentifierLoc());
2286 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002287 SC = FunctionDecl::None;
2288 }
Mike Stump11289f42009-09-09 15:08:12 +00002289
Chris Lattner38378bf2009-04-25 08:28:21 +00002290 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2291 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002292 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002293 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2294 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002295 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002296 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2297 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002298 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002299 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2300 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002301 }
Mike Stump11289f42009-09-09 15:08:12 +00002302
Douglas Gregor831c93f2008-11-05 20:51:48 +00002303 // Rebuild the function type "R" without any type qualifiers (in
2304 // case any of the errors above fired) and with "void" as the
2305 // return type, since constructors don't have return types. We
2306 // *always* have to do this, because GetTypeForDeclarator will
2307 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002308 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002309 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2310 Proto->getNumArgs(),
2311 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002312}
2313
Douglas Gregor4d87df52008-12-16 21:30:33 +00002314/// CheckConstructor - Checks a fully-formed constructor for
2315/// well-formedness, issuing any diagnostics required. Returns true if
2316/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002317void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002318 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002319 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2320 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002321 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002322
2323 // C++ [class.copy]p3:
2324 // A declaration of a constructor for a class X is ill-formed if
2325 // its first parameter is of type (optionally cv-qualified) X and
2326 // either there are no other parameters or else all other
2327 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002328 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002329 ((Constructor->getNumParams() == 1) ||
2330 (Constructor->getNumParams() > 1 &&
Anders Carlsson85446472009-06-06 04:14:07 +00002331 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002332 QualType ParamType = Constructor->getParamDecl(0)->getType();
2333 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2334 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002335 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2336 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002337 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002338 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002339 }
2340 }
Mike Stump11289f42009-09-09 15:08:12 +00002341
Douglas Gregor4d87df52008-12-16 21:30:33 +00002342 // Notify the class that we've added a constructor.
2343 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002344}
2345
Mike Stump11289f42009-09-09 15:08:12 +00002346static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002347FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2348 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2349 FTI.ArgInfo[0].Param &&
2350 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2351}
2352
Douglas Gregor831c93f2008-11-05 20:51:48 +00002353/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2354/// the well-formednes of the destructor declarator @p D with type @p
2355/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002356/// emit diagnostics and set the declarator to invalid. Even if this happens,
2357/// will be updated to reflect a well-formed type for the destructor and
2358/// returned.
2359QualType Sema::CheckDestructorDeclarator(Declarator &D,
2360 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002361 // C++ [class.dtor]p1:
2362 // [...] A typedef-name that names a class is a class-name
2363 // (7.1.3); however, a typedef-name that names a class shall not
2364 // be used as the identifier in the declarator for a destructor
2365 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002366 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002367 if (isa<TypedefType>(DeclaratorType)) {
2368 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002369 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002370 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002371 }
2372
2373 // C++ [class.dtor]p2:
2374 // A destructor is used to destroy objects of its class type. A
2375 // destructor takes no parameters, and no return type can be
2376 // specified for it (not even void). The address of a destructor
2377 // shall not be taken. A destructor shall not be static. A
2378 // destructor can be invoked for a const, volatile or const
2379 // volatile object. A destructor shall not be declared const,
2380 // volatile or const volatile (9.3.2).
2381 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002382 if (!D.isInvalidType())
2383 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2384 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2385 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002386 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002387 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002388 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002389 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002390 // Destructors don't have return types, but the parser will
2391 // happily parse something like:
2392 //
2393 // class X {
2394 // float ~X();
2395 // };
2396 //
2397 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002398 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2399 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2400 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Chris Lattner38378bf2009-04-25 08:28:21 +00002403 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2404 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002405 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002406 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2407 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002408 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002409 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2410 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002411 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002412 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2413 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002414 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002415 }
2416
2417 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002418 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002419 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2420
2421 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002422 FTI.freeArgs();
2423 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002424 }
2425
Mike Stump11289f42009-09-09 15:08:12 +00002426 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002427 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002428 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002429 D.setInvalidType();
2430 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002431
2432 // Rebuild the function type "R" without any type qualifiers or
2433 // parameters (in case any of the errors above fired) and with
2434 // "void" as the return type, since destructors don't have return
2435 // types. We *always* have to do this, because GetTypeForDeclarator
2436 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002437 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002438}
2439
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002440/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2441/// well-formednes of the conversion function declarator @p D with
2442/// type @p R. If there are any errors in the declarator, this routine
2443/// will emit diagnostics and return true. Otherwise, it will return
2444/// false. Either way, the type @p R will be updated to reflect a
2445/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002446void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002447 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002448 // C++ [class.conv.fct]p1:
2449 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002450 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002451 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002452 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002453 if (!D.isInvalidType())
2454 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2455 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2456 << SourceRange(D.getIdentifierLoc());
2457 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002458 SC = FunctionDecl::None;
2459 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002460 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002461 // Conversion functions don't have return types, but the parser will
2462 // happily parse something like:
2463 //
2464 // class X {
2465 // float operator bool();
2466 // };
2467 //
2468 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002469 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2470 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2471 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002472 }
2473
2474 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002475 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002476 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2477
2478 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002479 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002480 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002481 }
2482
Mike Stump11289f42009-09-09 15:08:12 +00002483 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002484 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002485 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002486 D.setInvalidType();
2487 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002488
2489 // C++ [class.conv.fct]p4:
2490 // The conversion-type-id shall not represent a function type nor
2491 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002492 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002493 if (ConvType->isArrayType()) {
2494 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2495 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002496 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002497 } else if (ConvType->isFunctionType()) {
2498 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2499 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002500 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002501 }
2502
2503 // Rebuild the function type "R" without any parameters (in case any
2504 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002505 // return type.
2506 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002507 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002508
Douglas Gregor5fb53972009-01-14 15:45:31 +00002509 // C++0x explicit conversion operators.
2510 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002511 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002512 diag::warn_explicit_conversion_functions)
2513 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002514}
2515
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002516/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2517/// the declaration of the given C++ conversion function. This routine
2518/// is responsible for recording the conversion function in the C++
2519/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002520Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002521 assert(Conversion && "Expected to receive a conversion function declaration");
2522
Douglas Gregor4287b372008-12-12 08:25:50 +00002523 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002524
2525 // Make sure we aren't redeclaring the conversion function.
2526 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002527
2528 // C++ [class.conv.fct]p1:
2529 // [...] A conversion function is never used to convert a
2530 // (possibly cv-qualified) object to the (possibly cv-qualified)
2531 // same object type (or a reference to it), to a (possibly
2532 // cv-qualified) base class of that type (or a reference to it),
2533 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002534 // FIXME: Suppress this warning if the conversion function ends up being a
2535 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002536 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002537 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002538 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539 ConvType = ConvTypeRef->getPointeeType();
2540 if (ConvType->isRecordType()) {
2541 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2542 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002543 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002544 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002545 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002546 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002547 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002548 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002549 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002550 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002551 }
2552
Douglas Gregor1dc98262008-12-26 15:00:45 +00002553 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002554 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002555 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002556 = Conversion->getDescribedFunctionTemplate())
2557 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002558 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002559 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002560 Conv = Conversions->function_begin(),
2561 ConvEnd = Conversions->function_end();
2562 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002563 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002564 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002565 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002566 }
2567 }
2568 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002569 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002570 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002571 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002572 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002573 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002574
Chris Lattner83f095c2009-03-28 19:18:32 +00002575 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002576}
2577
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002578//===----------------------------------------------------------------------===//
2579// Namespace Handling
2580//===----------------------------------------------------------------------===//
2581
2582/// ActOnStartNamespaceDef - This is called at the start of a namespace
2583/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002584Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2585 SourceLocation IdentLoc,
2586 IdentifierInfo *II,
2587 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002588 NamespaceDecl *Namespc =
2589 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2590 Namespc->setLBracLoc(LBrace);
2591
2592 Scope *DeclRegionScope = NamespcScope->getParent();
2593
2594 if (II) {
2595 // C++ [namespace.def]p2:
2596 // The identifier in an original-namespace-definition shall not have been
2597 // previously defined in the declarative region in which the
2598 // original-namespace-definition appears. The identifier in an
2599 // original-namespace-definition is the name of the namespace. Subsequently
2600 // in that declarative region, it is treated as an original-namespace-name.
2601
John McCall9f3059a2009-10-09 21:13:30 +00002602 NamedDecl *PrevDecl
2603 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump11289f42009-09-09 15:08:12 +00002604
Douglas Gregor91f84212008-12-11 16:49:14 +00002605 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2606 // This is an extended namespace definition.
2607 // Attach this namespace decl to the chain of extended namespace
2608 // definitions.
2609 OrigNS->setNextNamespace(Namespc);
2610 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002611
Mike Stump11289f42009-09-09 15:08:12 +00002612 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002613 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002614 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002615 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002616 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002617 } else if (PrevDecl) {
2618 // This is an invalid name redefinition.
2619 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2620 << Namespc->getDeclName();
2621 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2622 Namespc->setInvalidDecl();
2623 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002624 } else if (II->isStr("std") &&
2625 CurContext->getLookupContext()->isTranslationUnit()) {
2626 // This is the first "real" definition of the namespace "std", so update
2627 // our cache of the "std" namespace to point at this definition.
2628 if (StdNamespace) {
2629 // We had already defined a dummy namespace "std". Link this new
2630 // namespace definition to the dummy namespace "std".
2631 StdNamespace->setNextNamespace(Namespc);
2632 StdNamespace->setLocation(IdentLoc);
2633 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2634 }
2635
2636 // Make our StdNamespace cache point at the first real definition of the
2637 // "std" namespace.
2638 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002639 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002640
2641 PushOnScopeChains(Namespc, DeclRegionScope);
2642 } else {
John McCall4fa53422009-10-01 00:25:31 +00002643 // Anonymous namespaces.
2644
2645 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2646 // behaves as if it were replaced by
2647 // namespace unique { /* empty body */ }
2648 // using namespace unique;
2649 // namespace unique { namespace-body }
2650 // where all occurrences of 'unique' in a translation unit are
2651 // replaced by the same identifier and this identifier differs
2652 // from all other identifiers in the entire program.
2653
2654 // We just create the namespace with an empty name and then add an
2655 // implicit using declaration, just like the standard suggests.
2656 //
2657 // CodeGen enforces the "universally unique" aspect by giving all
2658 // declarations semantically contained within an anonymous
2659 // namespace internal linkage.
2660
2661 assert(Namespc->isAnonymousNamespace());
2662 CurContext->addDecl(Namespc);
2663
2664 UsingDirectiveDecl* UD
2665 = UsingDirectiveDecl::Create(Context, CurContext,
2666 /* 'using' */ LBrace,
2667 /* 'namespace' */ SourceLocation(),
2668 /* qualifier */ SourceRange(),
2669 /* NNS */ NULL,
2670 /* identifier */ SourceLocation(),
2671 Namespc,
2672 /* Ancestor */ CurContext);
2673 UD->setImplicit();
2674 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002675 }
2676
2677 // Although we could have an invalid decl (i.e. the namespace name is a
2678 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002679 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2680 // for the namespace has the declarations that showed up in that particular
2681 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002682 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002683 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002684}
2685
2686/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2687/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002688void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2689 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002690 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2691 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2692 Namespc->setRBracLoc(RBrace);
2693 PopDeclContext();
2694}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002695
Chris Lattner83f095c2009-03-28 19:18:32 +00002696Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2697 SourceLocation UsingLoc,
2698 SourceLocation NamespcLoc,
2699 const CXXScopeSpec &SS,
2700 SourceLocation IdentLoc,
2701 IdentifierInfo *NamespcName,
2702 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002703 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2704 assert(NamespcName && "Invalid NamespcName.");
2705 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002706 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002707
Douglas Gregor889ceb72009-02-03 19:21:40 +00002708 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002709
Douglas Gregor34074322009-01-14 22:20:51 +00002710 // Lookup namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002711 LookupResult R;
2712 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002713 if (R.isAmbiguous()) {
2714 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002715 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002716 }
John McCall9f3059a2009-10-09 21:13:30 +00002717 if (!R.empty()) {
2718 NamedDecl *NS = R.getFoundDecl();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002719 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002720 // C++ [namespace.udir]p1:
2721 // A using-directive specifies that the names in the nominated
2722 // namespace can be used in the scope in which the
2723 // using-directive appears after the using-directive. During
2724 // unqualified name lookup (3.4.1), the names appear as if they
2725 // were declared in the nearest enclosing namespace which
2726 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002727 // namespace. [Note: in this context, "contains" means "contains
2728 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002729
2730 // Find enclosing context containing both using-directive and
2731 // nominated namespace.
2732 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2733 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2734 CommonAncestor = CommonAncestor->getParent();
2735
Mike Stump11289f42009-09-09 15:08:12 +00002736 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002737 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002738 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002739 SS.getRange(),
2740 (NestedNameSpecifier *)SS.getScopeRep(),
2741 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002742 cast<NamespaceDecl>(NS),
2743 CommonAncestor);
2744 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002745 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002746 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002747 }
2748
Douglas Gregor889ceb72009-02-03 19:21:40 +00002749 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002750 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002751 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002752}
2753
2754void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2755 // If scope has associated entity, then using directive is at namespace
2756 // or translation unit scope. We add UsingDirectiveDecls, into
2757 // it's lookup structure.
2758 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002759 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002760 else
2761 // Otherwise it is block-sope. using-directives will affect lookup
2762 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002763 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002764}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002765
Douglas Gregorfec52632009-06-20 00:51:54 +00002766
2767Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002768 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002769 SourceLocation UsingLoc,
2770 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002771 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002772 AttributeList *AttrList,
2773 bool IsTypeName) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002774 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002775
Douglas Gregor220f4272009-11-04 16:30:06 +00002776 switch (Name.getKind()) {
2777 case UnqualifiedId::IK_Identifier:
2778 case UnqualifiedId::IK_OperatorFunctionId:
2779 case UnqualifiedId::IK_ConversionFunctionId:
2780 break;
2781
2782 case UnqualifiedId::IK_ConstructorName:
2783 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2784 << SS.getRange();
2785 return DeclPtrTy();
2786
2787 case UnqualifiedId::IK_DestructorName:
2788 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2789 << SS.getRange();
2790 return DeclPtrTy();
2791
2792 case UnqualifiedId::IK_TemplateId:
2793 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2794 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2795 return DeclPtrTy();
2796 }
2797
2798 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2799 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2800 Name.getSourceRange().getBegin(),
2801 TargetName, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002802 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002803 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002804 UD->setAccess(AS);
2805 }
Mike Stump11289f42009-09-09 15:08:12 +00002806
Anders Carlsson696a3f12009-08-28 05:40:36 +00002807 return DeclPtrTy::make(UD);
2808}
2809
2810NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2811 const CXXScopeSpec &SS,
2812 SourceLocation IdentLoc,
2813 DeclarationName Name,
2814 AttributeList *AttrList,
2815 bool IsTypeName) {
2816 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2817 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002818
Anders Carlssonf038fc22009-08-28 05:49:21 +00002819 // FIXME: We ignore attributes for now.
2820 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002821
Anders Carlsson59140b32009-08-28 03:16:11 +00002822 if (SS.isEmpty()) {
2823 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002824 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002825 }
Mike Stump11289f42009-09-09 15:08:12 +00002826
2827 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002828 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2829
Anders Carlssonf038fc22009-08-28 05:49:21 +00002830 if (isUnknownSpecialization(SS)) {
2831 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2832 SS.getRange(), NNS,
2833 IdentLoc, Name, IsTypeName);
2834 }
Mike Stump11289f42009-09-09 15:08:12 +00002835
Anders Carlsson59140b32009-08-28 03:16:11 +00002836 DeclContext *LookupContext = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002837
Anders Carlsson59140b32009-08-28 03:16:11 +00002838 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2839 // C++0x N2914 [namespace.udecl]p3:
2840 // A using-declaration used as a member-declaration shall refer to a member
2841 // of a base class of the class being defined, shall refer to a member of an
2842 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002843 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002844 // a member of a base class of the class being defined.
2845 const Type *Ty = NNS->getAsType();
2846 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2847 Diag(SS.getRange().getBegin(),
2848 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2849 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002850 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002851 }
Anders Carlsson4bd78752009-08-28 15:18:15 +00002852
2853 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2854 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlsson59140b32009-08-28 03:16:11 +00002855 } else {
2856 // C++0x N2914 [namespace.udecl]p8:
2857 // A using-declaration for a class member shall be a member-declaration.
2858 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002859 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002860 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002861 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002862 }
Mike Stump11289f42009-09-09 15:08:12 +00002863
Anders Carlsson59140b32009-08-28 03:16:11 +00002864 // C++0x N2914 [namespace.udecl]p9:
2865 // In a using-declaration, a prefix :: refers to the global namespace.
2866 if (NNS->getKind() == NestedNameSpecifier::Global)
2867 LookupContext = Context.getTranslationUnitDecl();
2868 else
2869 LookupContext = NNS->getAsNamespace();
2870 }
2871
2872
Douglas Gregorfec52632009-06-20 00:51:54 +00002873 // Lookup target name.
John McCall9f3059a2009-10-09 21:13:30 +00002874 LookupResult R;
2875 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002876
John McCall9f3059a2009-10-09 21:13:30 +00002877 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002878 Diag(IdentLoc, diag::err_no_member)
2879 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002880 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002881 }
2882
John McCall9f3059a2009-10-09 21:13:30 +00002883 // FIXME: handle ambiguity?
2884 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002885
Anders Carlsson59140b32009-08-28 03:16:11 +00002886 if (IsTypeName && !isa<TypeDecl>(ND)) {
2887 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002888 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002889 }
2890
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002891 // C++0x N2914 [namespace.udecl]p6:
2892 // A using-declaration shall not name a namespace.
2893 if (isa<NamespaceDecl>(ND)) {
2894 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2895 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002896 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002897 }
Mike Stump11289f42009-09-09 15:08:12 +00002898
Anders Carlsson696a3f12009-08-28 05:40:36 +00002899 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2900 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002901}
2902
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002903/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2904/// is a namespace alias, returns the namespace it points to.
2905static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2906 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2907 return AD->getNamespace();
2908 return dyn_cast_or_null<NamespaceDecl>(D);
2909}
2910
Mike Stump11289f42009-09-09 15:08:12 +00002911Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002912 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002913 SourceLocation AliasLoc,
2914 IdentifierInfo *Alias,
2915 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002916 SourceLocation IdentLoc,
2917 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002918
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002919 // Lookup the namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002920 LookupResult R;
2921 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002922
Anders Carlssondca83c42009-03-28 06:23:46 +00002923 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002924 if (NamedDecl *PrevDecl
2925 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002926 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002927 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002928 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00002929 if (!R.isAmbiguous() && !R.empty() &&
2930 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002931 return DeclPtrTy();
2932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933
Anders Carlssondca83c42009-03-28 06:23:46 +00002934 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2935 diag::err_redefinition_different_kind;
2936 Diag(AliasLoc, DiagID) << Alias;
2937 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002938 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002939 }
2940
Anders Carlssonac2c9652009-03-28 06:42:02 +00002941 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002942 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002943 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
John McCall9f3059a2009-10-09 21:13:30 +00002946 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00002947 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002948 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002951 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002952 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2953 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002954 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00002955 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002956
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002957 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002958 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002959}
2960
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002961void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2962 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002963 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2964 !Constructor->isUsed()) &&
2965 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002966
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002967 CXXRecordDecl *ClassDecl
2968 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian477d2422009-06-22 23:34:40 +00002969 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump11289f42009-09-09 15:08:12 +00002970 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002971 // implicitly defined, all the implicitly-declared default constructors
2972 // for its base class and its non-static data members shall have been
2973 // implicitly defined.
2974 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002975 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2976 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002977 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002978 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002979 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002980 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00002981 BaseClassDecl->getDefaultConstructor(Context))
2982 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002983 else {
Mike Stump11289f42009-09-09 15:08:12 +00002984 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian8ae5b0a2009-10-08 22:15:49 +00002985 << Context.getTagDeclType(ClassDecl) << 0
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002986 << Context.getTagDeclType(BaseClassDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002987 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00002988 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002989 err = true;
2990 }
2991 }
2992 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002993 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2994 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002995 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2996 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2997 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002998 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002999 CXXRecordDecl *FieldClassDecl
3000 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands323fc2a2009-06-25 09:03:06 +00003001 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003002 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003003 FieldClassDecl->getDefaultConstructor(Context))
3004 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003005 else {
Mike Stump11289f42009-09-09 15:08:12 +00003006 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian8ae5b0a2009-10-08 22:15:49 +00003007 << Context.getTagDeclType(ClassDecl) << 1 <<
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00003008 Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian8ae5b0a2009-10-08 22:15:49 +00003009 Diag((*Field)->getLocation(), diag::note_field_decl);
Mike Stump11289f42009-09-09 15:08:12 +00003010 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian1c9d5d92009-06-20 20:23:38 +00003011 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003012 err = true;
3013 }
3014 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003015 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003016 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00003017 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003018 Diag((*Field)->getLocation(), diag::note_declared_at);
3019 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003020 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003021 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson52b91802009-07-09 17:37:12 +00003022 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003023 Diag((*Field)->getLocation(), diag::note_declared_at);
3024 err = true;
3025 }
3026 }
3027 if (!err)
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003028 Constructor->setUsed();
3029 else
3030 Constructor->setInvalidDecl();
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003031}
3032
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003033void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003034 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003035 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3036 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00003037
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003038 CXXRecordDecl *ClassDecl
3039 = cast<CXXRecordDecl>(Destructor->getDeclContext());
3040 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3041 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003042 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003043 // implicitly defined, all the implicitly-declared default destructors
3044 // for its base class and its non-static data members shall have been
3045 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003046 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3047 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003048 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003049 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003050 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003051 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003052 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3053 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3054 else
Mike Stump11289f42009-09-09 15:08:12 +00003055 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003056 "DefineImplicitDestructor - missing dtor in a base class");
3057 }
3058 }
Mike Stump11289f42009-09-09 15:08:12 +00003059
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003060 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3061 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003062 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3063 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3064 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003065 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003066 CXXRecordDecl *FieldClassDecl
3067 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3068 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003069 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003070 const_cast<CXXDestructorDecl*>(
3071 FieldClassDecl->getDestructor(Context)))
3072 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3073 else
Mike Stump11289f42009-09-09 15:08:12 +00003074 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003075 "DefineImplicitDestructor - missing dtor in class of a data member");
3076 }
3077 }
3078 }
3079 Destructor->setUsed();
3080}
3081
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003082void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3083 CXXMethodDecl *MethodDecl) {
3084 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3085 MethodDecl->getOverloadedOperator() == OO_Equal &&
3086 !MethodDecl->isUsed()) &&
3087 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003088
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003089 CXXRecordDecl *ClassDecl
3090 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003091
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003092 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003093 // Before the implicitly-declared copy assignment operator for a class is
3094 // implicitly defined, all implicitly-declared copy assignment operators
3095 // for its direct base classes and its nonstatic data members shall have
3096 // been implicitly defined.
3097 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003098 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3099 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003100 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003101 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003102 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003103 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3104 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3105 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003106 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3107 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003108 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3109 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3110 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003111 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003112 CXXRecordDecl *FieldClassDecl
3113 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003114 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003115 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3116 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003117 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003118 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003119 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3120 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003121 Diag(CurrentLocation, diag::note_first_required_here);
3122 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003123 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003124 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003125 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3126 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003127 Diag(CurrentLocation, diag::note_first_required_here);
3128 err = true;
3129 }
3130 }
3131 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003132 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003133}
3134
3135CXXMethodDecl *
3136Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3137 CXXRecordDecl *ClassDecl) {
3138 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3139 QualType RHSType(LHSType);
3140 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003141 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003142 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003143 RHSType = Context.getCVRQualifiedType(RHSType,
3144 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003145 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3146 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003147 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003148 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3149 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003150 SourceLocation()));
3151 Expr *Args[2] = { &*LHS, &*RHS };
3152 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003153 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003154 CandidateSet);
3155 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003156 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003157 ClassDecl->getLocation(), Best) == OR_Success)
3158 return cast<CXXMethodDecl>(Best->Function);
3159 assert(false &&
3160 "getAssignOperatorMethod - copy assignment operator method not found");
3161 return 0;
3162}
3163
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003164void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3165 CXXConstructorDecl *CopyConstructor,
3166 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003167 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003168 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3169 !CopyConstructor->isUsed()) &&
3170 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003171
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003172 CXXRecordDecl *ClassDecl
3173 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3174 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003175 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003176 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003177 // implicitly defined, all the implicitly-declared copy constructors
3178 // for its base class and its non-static data members shall have been
3179 // implicitly defined.
3180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3181 Base != ClassDecl->bases_end(); ++Base) {
3182 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003183 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003184 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003185 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003186 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003187 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3189 FieldEnd = ClassDecl->field_end();
3190 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003191 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3192 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3193 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003194 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003195 CXXRecordDecl *FieldClassDecl
3196 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003197 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003198 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003199 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003200 }
3201 }
3202 CopyConstructor->setUsed();
3203}
3204
Anders Carlsson6eb55572009-08-25 05:12:04 +00003205Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003206Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003207 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003208 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003209 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003210
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003211 // C++ [class.copy]p15:
3212 // Whenever a temporary class object is copied using a copy constructor, and
3213 // this object and the copy have the same cv-unqualified type, an
3214 // implementation is permitted to treat the original and the copy as two
3215 // different ways of referring to the same object and not perform a copy at
3216 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003217
Anders Carlsson250aada2009-08-16 05:13:48 +00003218 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003219 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003220 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003221 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3222 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3224 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3225 E = ICE->getSubExpr();
3226
Anders Carlsson250aada2009-08-16 05:13:48 +00003227 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3228 Elidable = true;
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230
3231 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003232 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003233}
3234
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003235/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3236/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003237Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003238Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3239 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003240 MultiExprArg ExprArgs) {
3241 unsigned NumExprs = ExprArgs.size();
3242 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003243
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003244 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3245 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003246}
3247
Anders Carlsson574315a2009-08-27 05:08:22 +00003248Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003249Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3250 QualType Ty,
3251 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003252 MultiExprArg Args,
3253 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003254 unsigned NumExprs = Args.size();
3255 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003256
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003257 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3258 TyBeginLoc, Exprs,
3259 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003260}
3261
3262
Mike Stump11289f42009-09-09 15:08:12 +00003263bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003264 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003265 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003266 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003267 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003268 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003269 if (TempResult.isInvalid())
3270 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003271
Anders Carlsson6eb55572009-08-25 05:12:04 +00003272 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003273 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003274 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003275 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003276
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003277 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003278}
3279
Mike Stump11289f42009-09-09 15:08:12 +00003280void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003281 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003282 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003283 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003284 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003285 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003286 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003287}
3288
Mike Stump11289f42009-09-09 15:08:12 +00003289/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003290/// ActOnDeclarator, when a C++ direct initializer is present.
3291/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003292void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3293 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003294 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003295 SourceLocation *CommaLocs,
3296 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003297 unsigned NumExprs = Exprs.size();
3298 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003299 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003300
3301 // If there is no declaration, there was an error parsing it. Just ignore
3302 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003303 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003304 return;
Mike Stump11289f42009-09-09 15:08:12 +00003305
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003306 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3307 if (!VDecl) {
3308 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3309 RealDecl->setInvalidDecl();
3310 return;
3311 }
3312
Douglas Gregor402250f2009-08-26 21:14:46 +00003313 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003314 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003315 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3316 //
3317 // Clients that want to distinguish between the two forms, can check for
3318 // direct initializer using VarDecl::hasCXXDirectInitializer().
3319 // A major benefit is that clients that don't particularly care about which
3320 // exactly form was it (like the CodeGen) can handle both cases without
3321 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003322
Douglas Gregor402250f2009-08-26 21:14:46 +00003323 // If either the declaration has a dependent type or if any of the expressions
3324 // is type-dependent, we represent the initialization via a ParenListExpr for
3325 // later use during template instantiation.
3326 if (VDecl->getType()->isDependentType() ||
3327 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3328 // Let clients know that initialization was done with a direct initializer.
3329 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003330
Douglas Gregor402250f2009-08-26 21:14:46 +00003331 // Store the initialization expressions as a ParenListExpr.
3332 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003333 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003334 new (Context) ParenListExpr(Context, LParenLoc,
3335 (Expr **)Exprs.release(),
3336 NumExprs, RParenLoc));
3337 return;
3338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor402250f2009-08-26 21:14:46 +00003340
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003341 // C++ 8.5p11:
3342 // The form of initialization (using parentheses or '=') is generally
3343 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003344 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003345 QualType DeclInitType = VDecl->getType();
3346 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003347 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003348
Douglas Gregor4044d992009-03-24 16:43:20 +00003349 // FIXME: This isn't the right place to complete the type.
3350 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3351 diag::err_typecheck_decl_incomplete_type)) {
3352 VDecl->setInvalidDecl();
3353 return;
3354 }
3355
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003356 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003357 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3358
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003359 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003360 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003361 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003362 VDecl->getLocation(),
3363 SourceRange(VDecl->getLocation(),
3364 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003365 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003366 IK_Direct,
3367 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003368 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003369 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003370 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003371 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003372 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003373 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003374 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003375 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003376 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003377 return;
3378 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003379
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003380 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003381 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3382 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003383 RealDecl->setInvalidDecl();
3384 return;
3385 }
3386
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003387 // Let clients know that initialization was done with a direct initializer.
3388 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003389
3390 assert(NumExprs == 1 && "Expected 1 expression");
3391 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003392 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3393 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003394}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003395
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003396/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3397/// may occur as part of direct-initialization or copy-initialization.
3398///
3399/// \param ClassType the type of the object being initialized, which must have
3400/// class type.
3401///
3402/// \param ArgsPtr the arguments provided to initialize the object
3403///
3404/// \param Loc the source location where the initialization occurs
3405///
3406/// \param Range the source range that covers the entire initialization
3407///
3408/// \param InitEntity the name of the entity being initialized, if known
3409///
3410/// \param Kind the type of initialization being performed
3411///
3412/// \param ConvertedArgs a vector that will be filled in with the
3413/// appropriately-converted arguments to the constructor (if initialization
3414/// succeeded).
3415///
3416/// \returns the constructor used to initialize the object, if successful.
3417/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003418CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003419Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003420 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003421 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003422 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003423 InitializationKind Kind,
3424 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003425 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003426 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003427 Expr **Args = (Expr **)ArgsPtr.get();
3428 unsigned NumArgs = ArgsPtr.size();
3429
Mike Stump11289f42009-09-09 15:08:12 +00003430 // C++ [dcl.init]p14:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003431 // If the initialization is direct-initialization, or if it is
3432 // copy-initialization where the cv-unqualified version of the
3433 // source type is the same class as, or a derived class of, the
3434 // class of the destination, constructors are considered. The
3435 // applicable constructors are enumerated (13.3.1.3), and the
3436 // best one is chosen through overload resolution (13.3). The
3437 // constructor so selected is called to initialize the object,
3438 // with the initializer expression(s) as its argument(s). If no
3439 // constructor applies, or the overload resolution is ambiguous,
3440 // the initialization is ill-formed.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003441 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3442 OverloadCandidateSet CandidateSet;
Douglas Gregor6f543152008-11-05 15:29:30 +00003443
3444 // Add constructors to the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00003445 DeclarationName ConstructorName
Douglas Gregor1349b452008-12-15 21:24:18 +00003446 = Context.DeclarationNames.getCXXConstructorName(
3447 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor55297ac2008-12-23 00:26:44 +00003448 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003449 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00003450 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003451 // Find the constructor (which may be a template).
3452 CXXConstructorDecl *Constructor = 0;
3453 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3454 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003455 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003456 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3457 else
3458 Constructor = cast<CXXConstructorDecl>(*Con);
3459
Douglas Gregor6f543152008-11-05 15:29:30 +00003460 if ((Kind == IK_Direct) ||
Mike Stump11289f42009-09-09 15:08:12 +00003461 (Kind == IK_Copy &&
Anders Carlssond20e7952009-08-28 16:57:08 +00003462 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003463 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3464 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003465 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003466 Args, NumArgs, CandidateSet);
3467 else
3468 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3469 }
Douglas Gregor6f543152008-11-05 15:29:30 +00003470 }
3471
Douglas Gregor1349b452008-12-15 21:24:18 +00003472 // FIXME: When we decide not to synthesize the implicitly-declared
3473 // constructors, we'll need to make them appear here.
3474
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003475 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003476 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003477 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003478 // We found a constructor. Break out so that we can convert the arguments
3479 // appropriately.
3480 break;
Mike Stump11289f42009-09-09 15:08:12 +00003481
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003482 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003483 if (InitEntity)
3484 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003485 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003486 else
3487 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003488 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003489 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003490 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003492 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003493 if (InitEntity)
3494 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3495 else
3496 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003497 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3498 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003499
3500 case OR_Deleted:
3501 if (InitEntity)
3502 Diag(Loc, diag::err_ovl_deleted_init)
3503 << Best->Function->isDeleted()
3504 << InitEntity << Range;
3505 else
3506 Diag(Loc, diag::err_ovl_deleted_init)
3507 << Best->Function->isDeleted()
3508 << InitEntity << Range;
3509 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3510 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003511 }
Mike Stump11289f42009-09-09 15:08:12 +00003512
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003513 // Convert the arguments, fill in default arguments, etc.
3514 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3515 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3516 return 0;
3517
3518 return Constructor;
3519}
3520
3521/// \brief Given a constructor and the set of arguments provided for the
3522/// constructor, convert the arguments and add any required default arguments
3523/// to form a proper call to this constructor.
3524///
3525/// \returns true if an error occurred, false otherwise.
3526bool
3527Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3528 MultiExprArg ArgsPtr,
3529 SourceLocation Loc,
3530 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3531 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3532 unsigned NumArgs = ArgsPtr.size();
3533 Expr **Args = (Expr **)ArgsPtr.get();
3534
3535 const FunctionProtoType *Proto
3536 = Constructor->getType()->getAs<FunctionProtoType>();
3537 assert(Proto && "Constructor without a prototype?");
3538 unsigned NumArgsInProto = Proto->getNumArgs();
3539 unsigned NumArgsToCheck = NumArgs;
3540
3541 // If too few arguments are available, we'll fill in the rest with defaults.
3542 if (NumArgs < NumArgsInProto) {
3543 NumArgsToCheck = NumArgsInProto;
3544 ConvertedArgs.reserve(NumArgsInProto);
3545 } else {
3546 ConvertedArgs.reserve(NumArgs);
3547 if (NumArgs > NumArgsInProto)
3548 NumArgsToCheck = NumArgsInProto;
3549 }
3550
3551 // Convert arguments
3552 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3553 QualType ProtoArgType = Proto->getArgType(i);
3554
3555 Expr *Arg;
3556 if (i < NumArgs) {
3557 Arg = Args[i];
Anders Carlssonc8bfc462009-09-15 21:14:33 +00003558
3559 // Pass the argument.
3560 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3561 return true;
3562
3563 Args[i] = 0;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003564 } else {
3565 ParmVarDecl *Param = Constructor->getParamDecl(i);
3566
3567 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3568 if (DefArg.isInvalid())
3569 return true;
3570
3571 Arg = DefArg.takeAs<Expr>();
3572 }
3573
3574 ConvertedArgs.push_back(Arg);
3575 }
3576
3577 // If this is a variadic call, handle args passed through "...".
3578 if (Proto->isVariadic()) {
3579 // Promote the arguments (C99 6.5.2.2p7).
3580 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3581 Expr *Arg = Args[i];
3582 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3583 return true;
3584
3585 ConvertedArgs.push_back(Arg);
3586 Args[i] = 0;
3587 }
3588 }
3589
3590 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003591}
3592
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003593/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3594/// determine whether they are reference-related,
3595/// reference-compatible, reference-compatible with added
3596/// qualification, or incompatible, for use in C++ initialization by
3597/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3598/// type, and the first type (T1) is the pointee type of the reference
3599/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003600Sema::ReferenceCompareResult
3601Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003602 bool& DerivedToBase) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003603 assert(!T1->isReferenceType() &&
3604 "T1 must be the pointee type of the reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003605 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3606
3607 T1 = Context.getCanonicalType(T1);
3608 T2 = Context.getCanonicalType(T2);
3609 QualType UnqualT1 = T1.getUnqualifiedType();
3610 QualType UnqualT2 = T2.getUnqualifiedType();
3611
3612 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003613 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003614 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003615 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003616 if (UnqualT1 == UnqualT2)
3617 DerivedToBase = false;
3618 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3619 DerivedToBase = true;
3620 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003621 return Ref_Incompatible;
3622
3623 // At this point, we know that T1 and T2 are reference-related (at
3624 // least).
3625
3626 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003627 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003628 // reference-related to T2 and cv1 is the same cv-qualification
3629 // as, or greater cv-qualification than, cv2. For purposes of
3630 // overload resolution, cases for which cv1 is greater
3631 // cv-qualification than cv2 are identified as
3632 // reference-compatible with added qualification (see 13.3.3.2).
3633 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3634 return Ref_Compatible;
3635 else if (T1.isMoreQualifiedThan(T2))
3636 return Ref_Compatible_With_Added_Qualification;
3637 else
3638 return Ref_Related;
3639}
3640
3641/// CheckReferenceInit - Check the initialization of a reference
3642/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3643/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003644/// list), and DeclType is the type of the declaration. When ICS is
3645/// non-null, this routine will compute the implicit conversion
3646/// sequence according to C++ [over.ics.ref] and will not produce any
3647/// diagnostics; when ICS is null, it will emit diagnostics when any
3648/// errors are found. Either way, a return value of true indicates
3649/// that there was a failure, a return value of false indicates that
3650/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003651///
3652/// When @p SuppressUserConversions, user-defined conversions are
3653/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003654/// When @p AllowExplicit, we also permit explicit user-defined
3655/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003656/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump11289f42009-09-09 15:08:12 +00003657bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003658Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003659 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003660 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003661 bool AllowExplicit, bool ForceRValue,
3662 ImplicitConversionSequence *ICS) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003663 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3664
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003665 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003666 QualType T2 = Init->getType();
3667
Douglas Gregorcd695e52008-11-10 20:40:00 +00003668 // If the initializer is the address of an overloaded function, try
3669 // to resolve the overloaded function. If all goes well, T2 is the
3670 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003671 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003672 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003673 ICS != 0);
3674 if (Fn) {
3675 // Since we're performing this reference-initialization for
3676 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003677 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003678 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003679 return true;
3680
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003681 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003682 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003683
3684 T2 = Fn->getType();
3685 }
3686 }
3687
Douglas Gregor786ab212008-10-29 02:00:59 +00003688 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003689 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003690 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003691 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3692 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003693 ReferenceCompareResult RefRelationship
Douglas Gregor786ab212008-10-29 02:00:59 +00003694 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3695
3696 // Most paths end in a failed conversion.
3697 if (ICS)
3698 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003699
3700 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003701 // A reference to type "cv1 T1" is initialized by an expression
3702 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003703
3704 // -- If the initializer expression
3705
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003706 // Rvalue references cannot bind to lvalues (N2812).
3707 // There is absolutely no situation where they can. In particular, note that
3708 // this is ill-formed, even if B has a user-defined conversion to A&&:
3709 // B b;
3710 // A&& r = b;
3711 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3712 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003713 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003714 << Init->getSourceRange();
3715 return true;
3716 }
3717
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003718 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003719 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3720 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003721 //
3722 // Note that the bit-field check is skipped if we are just computing
3723 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003724 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003725 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003726 BindsDirectly = true;
3727
Douglas Gregor786ab212008-10-29 02:00:59 +00003728 if (ICS) {
3729 // C++ [over.ics.ref]p1:
3730 // When a parameter of reference type binds directly (8.5.3)
3731 // to an argument expression, the implicit conversion sequence
3732 // is the identity conversion, unless the argument expression
3733 // has a type that is a derived class of the parameter type,
3734 // in which case the implicit conversion sequence is a
3735 // derived-to-base Conversion (13.3.3.1).
3736 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3737 ICS->Standard.First = ICK_Identity;
3738 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3739 ICS->Standard.Third = ICK_Identity;
3740 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3741 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003742 ICS->Standard.ReferenceBinding = true;
3743 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003744 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003745 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003746
3747 // Nothing more to do: the inaccessibility/ambiguity check for
3748 // derived-to-base conversions is suppressed when we're
3749 // computing the implicit conversion sequence (C++
3750 // [over.best.ics]p2).
3751 return false;
3752 } else {
3753 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003754 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3755 if (DerivedToBase)
3756 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003757 else if(CheckExceptionSpecCompatibility(Init, T1))
3758 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003759 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003760 }
3761 }
3762
3763 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003764 // implicitly converted to an lvalue of type "cv3 T3,"
3765 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003766 // 92) (this conversion is selected by enumerating the
3767 // applicable conversion functions (13.3.1.6) and choosing
3768 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003769 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003770 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003771 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003772 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003773
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003774 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003775 OverloadedFunctionDecl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003776 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003777 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003778 = Conversions->function_begin();
3779 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003780 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003781 = dyn_cast<FunctionTemplateDecl>(*Func);
3782 CXXConversionDecl *Conv;
3783 if (ConvTemplate)
3784 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3785 else
3786 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003787
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003788 // If the conversion function doesn't return a reference type,
3789 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003790 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003791 (AllowExplicit || !Conv->isExplicit())) {
3792 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003793 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003794 CandidateSet);
3795 else
3796 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3797 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003798 }
3799
3800 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003801 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003802 case OR_Success:
3803 // This is a direct binding.
3804 BindsDirectly = true;
3805
3806 if (ICS) {
3807 // C++ [over.ics.ref]p1:
3808 //
3809 // [...] If the parameter binds directly to the result of
3810 // applying a conversion function to the argument
3811 // expression, the implicit conversion sequence is a
3812 // user-defined conversion sequence (13.3.3.1.2), with the
3813 // second standard conversion sequence either an identity
3814 // conversion or, if the conversion function returns an
3815 // entity of a type that is a derived class of the parameter
3816 // type, a derived-to-base Conversion.
3817 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3818 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3819 ICS->UserDefined.After = Best->FinalConversion;
3820 ICS->UserDefined.ConversionFunction = Best->Function;
3821 assert(ICS->UserDefined.After.ReferenceBinding &&
3822 ICS->UserDefined.After.DirectBinding &&
3823 "Expected a direct reference binding!");
3824 return false;
3825 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003826 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003827 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003828 CastExpr::CK_UserDefinedConversion,
3829 cast<CXXMethodDecl>(Best->Function),
3830 Owned(Init));
3831 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003832
3833 if (CheckExceptionSpecCompatibility(Init, T1))
3834 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003835 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3836 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003837 }
3838 break;
3839
3840 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003841 if (ICS) {
3842 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3843 Cand != CandidateSet.end(); ++Cand)
3844 if (Cand->Viable)
3845 ICS->ConversionFunctionSet.push_back(Cand->Function);
3846 break;
3847 }
3848 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3849 << Init->getSourceRange();
3850 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003851 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003852
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003853 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003854 case OR_Deleted:
3855 // There was no suitable conversion, or we found a deleted
3856 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003857 break;
3858 }
3859 }
Mike Stump11289f42009-09-09 15:08:12 +00003860
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003861 if (BindsDirectly) {
3862 // C++ [dcl.init.ref]p4:
3863 // [...] In all cases where the reference-related or
3864 // reference-compatible relationship of two types is used to
3865 // establish the validity of a reference binding, and T1 is a
3866 // base class of T2, a program that necessitates such a binding
3867 // is ill-formed if T1 is an inaccessible (clause 11) or
3868 // ambiguous (10.2) base class of T2.
3869 //
3870 // Note that we only check this condition when we're allowed to
3871 // complain about errors, because we should not be checking for
3872 // ambiguity (or inaccessibility) unless the reference binding
3873 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003874 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003875 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor786ab212008-10-29 02:00:59 +00003876 Init->getSourceRange());
3877 else
3878 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003879 }
3880
3881 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003882 // type (i.e., cv1 shall be const), or the reference shall be an
3883 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003884 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003885 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003886 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003887 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3888 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003889 return true;
3890 }
3891
3892 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003893 // class type, and "cv1 T1" is reference-compatible with
3894 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003895 // following ways (the choice is implementation-defined):
3896 //
3897 // -- The reference is bound to the object represented by
3898 // the rvalue (see 3.10) or to a sub-object within that
3899 // object.
3900 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003901 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003902 // a constructor is called to copy the entire rvalue
3903 // object into the temporary. The reference is bound to
3904 // the temporary or to a sub-object within the
3905 // temporary.
3906 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003907 // The constructor that would be used to make the copy
3908 // shall be callable whether or not the copy is actually
3909 // done.
3910 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003911 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003912 // freedom, so we will always take the first option and never build
3913 // a temporary in this case. FIXME: We will, however, have to check
3914 // for the presence of a copy constructor in C++98/03 mode.
3915 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003916 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3917 if (ICS) {
3918 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3919 ICS->Standard.First = ICK_Identity;
3920 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3921 ICS->Standard.Third = ICK_Identity;
3922 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3923 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003924 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003925 ICS->Standard.DirectBinding = false;
3926 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003927 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003928 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003929 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3930 if (DerivedToBase)
3931 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003932 else if(CheckExceptionSpecCompatibility(Init, T1))
3933 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003934 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003935 }
3936 return false;
3937 }
3938
Eli Friedman44b83ee2009-08-05 19:21:58 +00003939 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003940 // initialized from the initializer expression using the
3941 // rules for a non-reference copy initialization (8.5). The
3942 // reference is then bound to the temporary. If T1 is
3943 // reference-related to T2, cv1 must be the same
3944 // cv-qualification as, or greater cv-qualification than,
3945 // cv2; otherwise, the program is ill-formed.
3946 if (RefRelationship == Ref_Related) {
3947 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3948 // we would be reference-compatible or reference-compatible with
3949 // added qualification. But that wasn't the case, so the reference
3950 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003951 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003952 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003953 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3954 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003955 return true;
3956 }
3957
Douglas Gregor576e98c2009-01-30 23:27:23 +00003958 // If at least one of the types is a class type, the types are not
3959 // related, and we aren't allowed any user conversions, the
3960 // reference binding fails. This case is important for breaking
3961 // recursion, since TryImplicitConversion below will attempt to
3962 // create a temporary through the use of a copy constructor.
3963 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3964 (T1->isRecordType() || T2->isRecordType())) {
3965 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003966 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00003967 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3968 return true;
3969 }
3970
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003971 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00003972 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003973 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003974 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003975 // When a parameter of reference type is not bound directly to
3976 // an argument expression, the conversion sequence is the one
3977 // required to convert the argument expression to the
3978 // underlying type of the reference according to
3979 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3980 // to copy-initializing a temporary of the underlying type with
3981 // the argument expression. Any difference in top-level
3982 // cv-qualification is subsumed by the initialization itself
3983 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00003984 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3985 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00003986 /*ForceRValue=*/false,
3987 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003988
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003989 // Of course, that's still a reference binding.
3990 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3991 ICS->Standard.ReferenceBinding = true;
3992 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00003993 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003994 ImplicitConversionSequence::UserDefinedConversion) {
3995 ICS->UserDefined.After.ReferenceBinding = true;
3996 ICS->UserDefined.After.RRefBinding = isRValRef;
3997 }
Douglas Gregor786ab212008-10-29 02:00:59 +00003998 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3999 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004000 ImplicitConversionSequence Conversions;
4001 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4002 false, false,
4003 Conversions);
4004 if (badConversion) {
4005 if ((Conversions.ConversionKind ==
4006 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004007 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004008 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004009 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4010 for (int j = Conversions.ConversionFunctionSet.size()-1;
4011 j >= 0; j--) {
4012 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4013 Diag(Func->getLocation(), diag::err_ovl_candidate);
4014 }
4015 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004016 else {
4017 if (isRValRef)
4018 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4019 << Init->getSourceRange();
4020 else
4021 Diag(DeclLoc, diag::err_invalid_initialization)
4022 << DeclType << Init->getType() << Init->getSourceRange();
4023 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004024 }
4025 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004026 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004027}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004028
4029/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4030/// of this overloaded operator is well-formed. If so, returns false;
4031/// otherwise, emits appropriate diagnostics and returns true.
4032bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004033 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004034 "Expected an overloaded operator declaration");
4035
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004036 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4037
Mike Stump11289f42009-09-09 15:08:12 +00004038 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004039 // The allocation and deallocation functions, operator new,
4040 // operator new[], operator delete and operator delete[], are
4041 // described completely in 3.7.3. The attributes and restrictions
4042 // found in the rest of this subclause do not apply to them unless
4043 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004044 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004045 if (Op == OO_New || Op == OO_Array_New ||
4046 Op == OO_Delete || Op == OO_Array_Delete)
4047 return false;
4048
4049 // C++ [over.oper]p6:
4050 // An operator function shall either be a non-static member
4051 // function or be a non-member function and have at least one
4052 // parameter whose type is a class, a reference to a class, an
4053 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004054 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4055 if (MethodDecl->isStatic())
4056 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004057 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004058 } else {
4059 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004060 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4061 ParamEnd = FnDecl->param_end();
4062 Param != ParamEnd; ++Param) {
4063 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004064 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4065 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004066 ClassOrEnumParam = true;
4067 break;
4068 }
4069 }
4070
Douglas Gregord69246b2008-11-17 16:14:12 +00004071 if (!ClassOrEnumParam)
4072 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004073 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004074 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004075 }
4076
4077 // C++ [over.oper]p8:
4078 // An operator function cannot have default arguments (8.3.6),
4079 // except where explicitly stated below.
4080 //
Mike Stump11289f42009-09-09 15:08:12 +00004081 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004082 // (C++ [over.call]p1).
4083 if (Op != OO_Call) {
4084 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4085 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004086 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004087 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004088 diag::err_operator_overload_default_arg)
4089 << FnDecl->getDeclName();
4090 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004091 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004092 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004093 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004094 }
4095 }
4096
Douglas Gregor6cf08062008-11-10 13:38:07 +00004097 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4098 { false, false, false }
4099#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4100 , { Unary, Binary, MemberOnly }
4101#include "clang/Basic/OperatorKinds.def"
4102 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004103
Douglas Gregor6cf08062008-11-10 13:38:07 +00004104 bool CanBeUnaryOperator = OperatorUses[Op][0];
4105 bool CanBeBinaryOperator = OperatorUses[Op][1];
4106 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004107
4108 // C++ [over.oper]p8:
4109 // [...] Operator functions cannot have more or fewer parameters
4110 // than the number required for the corresponding operator, as
4111 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004112 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004113 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004114 if (Op != OO_Call &&
4115 ((NumParams == 1 && !CanBeUnaryOperator) ||
4116 (NumParams == 2 && !CanBeBinaryOperator) ||
4117 (NumParams < 1) || (NumParams > 2))) {
4118 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004119 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004120 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004121 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004122 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004123 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004124 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004125 assert(CanBeBinaryOperator &&
4126 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004127 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004128 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004129
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004130 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004131 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004132 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004133
Douglas Gregord69246b2008-11-17 16:14:12 +00004134 // Overloaded operators other than operator() cannot be variadic.
4135 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004136 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004137 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004138 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004139 }
4140
4141 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004142 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4143 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004144 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004145 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004146 }
4147
4148 // C++ [over.inc]p1:
4149 // The user-defined function called operator++ implements the
4150 // prefix and postfix ++ operator. If this function is a member
4151 // function with no parameters, or a non-member function with one
4152 // parameter of class or enumeration type, it defines the prefix
4153 // increment operator ++ for objects of that type. If the function
4154 // is a member function with one parameter (which shall be of type
4155 // int) or a non-member function with two parameters (the second
4156 // of which shall be of type int), it defines the postfix
4157 // increment operator ++ for objects of that type.
4158 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4159 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4160 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004161 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004162 ParamIsInt = BT->getKind() == BuiltinType::Int;
4163
Chris Lattner2b786902008-11-21 07:50:02 +00004164 if (!ParamIsInt)
4165 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004166 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004167 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004168 }
4169
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004170 // Notify the class if it got an assignment operator.
4171 if (Op == OO_Equal) {
4172 // Would have returned earlier otherwise.
4173 assert(isa<CXXMethodDecl>(FnDecl) &&
4174 "Overloaded = not member, but not filtered.");
4175 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian4985b332009-08-13 21:09:41 +00004176 Method->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004177 Method->getParent()->addedAssignmentOperator(Context, Method);
4178 }
4179
Douglas Gregord69246b2008-11-17 16:14:12 +00004180 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004181}
Chris Lattner3b024a32008-12-17 07:09:26 +00004182
Douglas Gregor07665a62009-01-05 19:45:36 +00004183/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4184/// linkage specification, including the language and (if present)
4185/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4186/// the location of the language string literal, which is provided
4187/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4188/// the '{' brace. Otherwise, this linkage specification does not
4189/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004190Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4191 SourceLocation ExternLoc,
4192 SourceLocation LangLoc,
4193 const char *Lang,
4194 unsigned StrSize,
4195 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004196 LinkageSpecDecl::LanguageIDs Language;
4197 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4198 Language = LinkageSpecDecl::lang_c;
4199 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4200 Language = LinkageSpecDecl::lang_cxx;
4201 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004202 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004203 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004204 }
Mike Stump11289f42009-09-09 15:08:12 +00004205
Chris Lattner438e5012008-12-17 07:13:27 +00004206 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004207
Douglas Gregor07665a62009-01-05 19:45:36 +00004208 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004209 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004210 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004211 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004212 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004213 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004214}
4215
Douglas Gregor07665a62009-01-05 19:45:36 +00004216/// ActOnFinishLinkageSpecification - Completely the definition of
4217/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4218/// valid, it's the position of the closing '}' brace in a linkage
4219/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004220Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4221 DeclPtrTy LinkageSpec,
4222 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004223 if (LinkageSpec)
4224 PopDeclContext();
4225 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004226}
4227
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004228/// \brief Perform semantic analysis for the variable declaration that
4229/// occurs within a C++ catch clause, returning the newly-created
4230/// variable.
4231VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004232 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004233 IdentifierInfo *Name,
4234 SourceLocation Loc,
4235 SourceRange Range) {
4236 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004237
4238 // Arrays and functions decay.
4239 if (ExDeclType->isArrayType())
4240 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4241 else if (ExDeclType->isFunctionType())
4242 ExDeclType = Context.getPointerType(ExDeclType);
4243
4244 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4245 // The exception-declaration shall not denote a pointer or reference to an
4246 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004247 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004248 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004249 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004250 Invalid = true;
4251 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004252
Sebastian Redl54c04d42008-12-22 19:15:10 +00004253 QualType BaseType = ExDeclType;
4254 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004255 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004256 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004257 BaseType = Ptr->getPointeeType();
4258 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004259 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004260 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004261 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004262 BaseType = Ref->getPointeeType();
4263 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004264 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004265 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004266 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004267 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004268 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004269
Mike Stump11289f42009-09-09 15:08:12 +00004270 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004271 RequireNonAbstractType(Loc, ExDeclType,
4272 diag::err_abstract_type_in_decl,
4273 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004274 Invalid = true;
4275
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004276 // FIXME: Need to test for ability to copy-construct and destroy the
4277 // exception variable.
4278
Sebastian Redl9b244a82008-12-22 21:35:02 +00004279 // FIXME: Need to check for abstract classes.
4280
Mike Stump11289f42009-09-09 15:08:12 +00004281 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004282 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004283
4284 if (Invalid)
4285 ExDecl->setInvalidDecl();
4286
4287 return ExDecl;
4288}
4289
4290/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4291/// handler.
4292Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004293 DeclaratorInfo *DInfo = 0;
4294 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004295
4296 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004297 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004298 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004299 // The scope should be freshly made just for us. There is just no way
4300 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004301 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004302 if (PrevDecl->isTemplateParameter()) {
4303 // Maybe we will complain about the shadowed template parameter.
4304 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004305 }
4306 }
4307
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004308 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004309 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4310 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004311 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004312 }
4313
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004314 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004315 D.getIdentifier(),
4316 D.getIdentifierLoc(),
4317 D.getDeclSpec().getSourceRange());
4318
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004319 if (Invalid)
4320 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004321
Sebastian Redl54c04d42008-12-22 19:15:10 +00004322 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004323 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004324 PushOnScopeChains(ExDecl, S);
4325 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004326 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004327
Douglas Gregor758a8692009-06-17 21:51:59 +00004328 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004329 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004330}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004331
Mike Stump11289f42009-09-09 15:08:12 +00004332Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004333 ExprArg assertexpr,
4334 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004335 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004336 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004337 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4338
Anders Carlsson54b26982009-03-14 00:33:21 +00004339 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4340 llvm::APSInt Value(32);
4341 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4342 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4343 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004344 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004345 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004346
Anders Carlsson54b26982009-03-14 00:33:21 +00004347 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004348 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004349 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004350 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004351 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004352 }
4353 }
Mike Stump11289f42009-09-09 15:08:12 +00004354
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004355 assertexpr.release();
4356 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004357 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004358 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004359
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004360 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004361 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004362}
Sebastian Redlf769df52009-03-24 22:27:57 +00004363
John McCall11083da2009-09-16 22:47:08 +00004364/// Handle a friend type declaration. This works in tandem with
4365/// ActOnTag.
4366///
4367/// Notes on friend class templates:
4368///
4369/// We generally treat friend class declarations as if they were
4370/// declaring a class. So, for example, the elaborated type specifier
4371/// in a friend declaration is required to obey the restrictions of a
4372/// class-head (i.e. no typedefs in the scope chain), template
4373/// parameters are required to match up with simple template-ids, &c.
4374/// However, unlike when declaring a template specialization, it's
4375/// okay to refer to a template specialization without an empty
4376/// template parameter declaration, e.g.
4377/// friend class A<T>::B<unsigned>;
4378/// We permit this as a special case; if there are any template
4379/// parameters present at all, require proper matching, i.e.
4380/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004381Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004382 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004383 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004384
4385 assert(DS.isFriendSpecified());
4386 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4387
John McCall11083da2009-09-16 22:47:08 +00004388 // Try to convert the decl specifier to a type. This works for
4389 // friend templates because ActOnTag never produces a ClassTemplateDecl
4390 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004391 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004392 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4393 if (TheDeclarator.isInvalidType())
4394 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004395
John McCall11083da2009-09-16 22:47:08 +00004396 // This is definitely an error in C++98. It's probably meant to
4397 // be forbidden in C++0x, too, but the specification is just
4398 // poorly written.
4399 //
4400 // The problem is with declarations like the following:
4401 // template <T> friend A<T>::foo;
4402 // where deciding whether a class C is a friend or not now hinges
4403 // on whether there exists an instantiation of A that causes
4404 // 'foo' to equal C. There are restrictions on class-heads
4405 // (which we declare (by fiat) elaborated friend declarations to
4406 // be) that makes this tractable.
4407 //
4408 // FIXME: handle "template <> friend class A<T>;", which
4409 // is possibly well-formed? Who even knows?
4410 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4411 Diag(Loc, diag::err_tagless_friend_type_template)
4412 << DS.getSourceRange();
4413 return DeclPtrTy();
4414 }
4415
John McCallaa74a0c2009-08-28 07:59:38 +00004416 // C++ [class.friend]p2:
4417 // An elaborated-type-specifier shall be used in a friend declaration
4418 // for a class.*
4419 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004420 // This is one of the rare places in Clang where it's legitimate to
4421 // ask about the "spelling" of the type.
4422 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4423 // If we evaluated the type to a record type, suggest putting
4424 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004425 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004426 RecordDecl *RD = RT->getDecl();
4427
4428 std::string InsertionText = std::string(" ") + RD->getKindName();
4429
John McCallc3987482009-10-07 23:34:25 +00004430 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4431 << (unsigned) RD->getTagKind()
4432 << T
4433 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004434 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4435 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004436 return DeclPtrTy();
4437 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004438 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4439 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004440 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004441 }
4442 }
4443
John McCallc3987482009-10-07 23:34:25 +00004444 // Enum types cannot be friends.
4445 if (T->getAs<EnumType>()) {
4446 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4447 << SourceRange(DS.getFriendSpecLoc());
4448 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004449 }
John McCallaa74a0c2009-08-28 07:59:38 +00004450
John McCallaa74a0c2009-08-28 07:59:38 +00004451 // C++98 [class.friend]p1: A friend of a class is a function
4452 // or class that is not a member of the class . . .
4453 // But that's a silly restriction which nobody implements for
4454 // inner classes, and C++0x removes it anyway, so we only report
4455 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004456 if (!getLangOptions().CPlusPlus0x)
4457 if (const RecordType *RT = T->getAs<RecordType>())
4458 if (RT->getDecl()->getDeclContext() == CurContext)
4459 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004460
John McCall11083da2009-09-16 22:47:08 +00004461 Decl *D;
4462 if (TempParams.size())
4463 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4464 TempParams.size(),
4465 (TemplateParameterList**) TempParams.release(),
4466 T.getTypePtr(),
4467 DS.getFriendSpecLoc());
4468 else
4469 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4470 DS.getFriendSpecLoc());
4471 D->setAccess(AS_public);
4472 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004473
John McCall11083da2009-09-16 22:47:08 +00004474 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004475}
4476
John McCall2f212b32009-09-11 21:02:39 +00004477Sema::DeclPtrTy
4478Sema::ActOnFriendFunctionDecl(Scope *S,
4479 Declarator &D,
4480 bool IsDefinition,
4481 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004482 const DeclSpec &DS = D.getDeclSpec();
4483
4484 assert(DS.isFriendSpecified());
4485 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4486
4487 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004488 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004489 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004490
4491 // C++ [class.friend]p1
4492 // A friend of a class is a function or class....
4493 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004494 // It *doesn't* see through dependent types, which is correct
4495 // according to [temp.arg.type]p3:
4496 // If a declaration acquires a function type through a
4497 // type dependent on a template-parameter and this causes
4498 // a declaration that does not use the syntactic form of a
4499 // function declarator to have a function type, the program
4500 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004501 if (!T->isFunctionType()) {
4502 Diag(Loc, diag::err_unexpected_friend);
4503
4504 // It might be worthwhile to try to recover by creating an
4505 // appropriate declaration.
4506 return DeclPtrTy();
4507 }
4508
4509 // C++ [namespace.memdef]p3
4510 // - If a friend declaration in a non-local class first declares a
4511 // class or function, the friend class or function is a member
4512 // of the innermost enclosing namespace.
4513 // - The name of the friend is not found by simple name lookup
4514 // until a matching declaration is provided in that namespace
4515 // scope (either before or after the class declaration granting
4516 // friendship).
4517 // - If a friend function is called, its name may be found by the
4518 // name lookup that considers functions from namespaces and
4519 // classes associated with the types of the function arguments.
4520 // - When looking for a prior declaration of a class or a function
4521 // declared as a friend, scopes outside the innermost enclosing
4522 // namespace scope are not considered.
4523
John McCallaa74a0c2009-08-28 07:59:38 +00004524 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4525 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004526 assert(Name);
4527
John McCall07e91c02009-08-06 02:15:43 +00004528 // The context we found the declaration in, or in which we should
4529 // create the declaration.
4530 DeclContext *DC;
4531
4532 // FIXME: handle local classes
4533
4534 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004535 NamedDecl *PrevDecl = 0;
John McCall07e91c02009-08-06 02:15:43 +00004536 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004537 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004538 DC = computeDeclContext(ScopeQual);
4539
4540 // FIXME: handle dependent contexts
4541 if (!DC) return DeclPtrTy();
4542
John McCall9f3059a2009-10-09 21:13:30 +00004543 LookupResult R;
4544 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4545 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004546
4547 // If searching in that context implicitly found a declaration in
4548 // a different context, treat it like it wasn't found at all.
4549 // TODO: better diagnostics for this case. Suggesting the right
4550 // qualified scope would be nice...
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004551 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004552 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004553 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4554 return DeclPtrTy();
4555 }
4556
4557 // C++ [class.friend]p1: A friend of a class is a function or
4558 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004559 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004560 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4561
John McCall07e91c02009-08-06 02:15:43 +00004562 // Otherwise walk out to the nearest namespace scope looking for matches.
4563 } else {
4564 // TODO: handle local class contexts.
4565
4566 DC = CurContext;
4567 while (true) {
4568 // Skip class contexts. If someone can cite chapter and verse
4569 // for this behavior, that would be nice --- it's what GCC and
4570 // EDG do, and it seems like a reasonable intent, but the spec
4571 // really only says that checks for unqualified existing
4572 // declarations should stop at the nearest enclosing namespace,
4573 // not that they should only consider the nearest enclosing
4574 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004575 while (DC->isRecord())
4576 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004577
John McCall9f3059a2009-10-09 21:13:30 +00004578 LookupResult R;
4579 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4580 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004581
4582 // TODO: decide what we think about using declarations.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004583 if (PrevDecl)
John McCall07e91c02009-08-06 02:15:43 +00004584 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004585
John McCall07e91c02009-08-06 02:15:43 +00004586 if (DC->isFileContext()) break;
4587 DC = DC->getParent();
4588 }
4589
4590 // C++ [class.friend]p1: A friend of a class is a function or
4591 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004592 // C++0x changes this for both friend types and functions.
4593 // Most C++ 98 compilers do seem to give an error here, so
4594 // we do, too.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004595 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004596 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4597 }
4598
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004599 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004600 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004601 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4602 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4603 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004604 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004605 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4606 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004607 return DeclPtrTy();
4608 }
John McCall07e91c02009-08-06 02:15:43 +00004609 }
4610
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004611 bool Redeclaration = false;
4612 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004613 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004614 IsDefinition,
4615 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004616 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004617
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004618 assert(ND->getDeclContext() == DC);
4619 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004620
John McCall759e32b2009-08-31 22:39:49 +00004621 // Add the function declaration to the appropriate lookup tables,
4622 // adjusting the redeclarations list as necessary. We don't
4623 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004624 //
John McCall759e32b2009-08-31 22:39:49 +00004625 // Also update the scope-based lookup if the target context's
4626 // lookup context is in lexical scope.
4627 if (!CurContext->isDependentContext()) {
4628 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004629 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004630 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004631 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004632 }
John McCallaa74a0c2009-08-28 07:59:38 +00004633
4634 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004635 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004636 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004637 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004638 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004639
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004640 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004641}
4642
Chris Lattner83f095c2009-03-28 19:18:32 +00004643void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004644 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004645
Chris Lattner83f095c2009-03-28 19:18:32 +00004646 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004647 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4648 if (!Fn) {
4649 Diag(DelLoc, diag::err_deleted_non_function);
4650 return;
4651 }
4652 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4653 Diag(DelLoc, diag::err_deleted_decl_not_first);
4654 Diag(Prev->getLocation(), diag::note_previous_declaration);
4655 // If the declaration wasn't the first, we delete the function anyway for
4656 // recovery.
4657 }
4658 Fn->setDeleted();
4659}
Sebastian Redl4c018662009-04-27 21:33:24 +00004660
4661static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4662 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4663 ++CI) {
4664 Stmt *SubStmt = *CI;
4665 if (!SubStmt)
4666 continue;
4667 if (isa<ReturnStmt>(SubStmt))
4668 Self.Diag(SubStmt->getSourceRange().getBegin(),
4669 diag::err_return_in_constructor_handler);
4670 if (!isa<Expr>(SubStmt))
4671 SearchForReturnInStmt(Self, SubStmt);
4672 }
4673}
4674
4675void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4676 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4677 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4678 SearchForReturnInStmt(*this, Handler);
4679 }
4680}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004681
Mike Stump11289f42009-09-09 15:08:12 +00004682bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004683 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004684 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4685 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004686
4687 QualType CNewTy = Context.getCanonicalType(NewTy);
4688 QualType COldTy = Context.getCanonicalType(OldTy);
4689
Mike Stump11289f42009-09-09 15:08:12 +00004690 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004691 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4692 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004693
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004694 // Check if the return types are covariant
4695 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004696
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004697 /// Both types must be pointers or references to classes.
4698 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4699 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4700 NewClassTy = NewPT->getPointeeType();
4701 OldClassTy = OldPT->getPointeeType();
4702 }
4703 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4704 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4705 NewClassTy = NewRT->getPointeeType();
4706 OldClassTy = OldRT->getPointeeType();
4707 }
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004710 // The return types aren't either both pointers or references to a class type.
4711 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004712 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004713 diag::err_different_return_type_for_overriding_virtual_function)
4714 << New->getDeclName() << NewTy << OldTy;
4715 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004716
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004717 return true;
4718 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004719
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004720 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4721 // Check if the new class derives from the old class.
4722 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4723 Diag(New->getLocation(),
4724 diag::err_covariant_return_not_derived)
4725 << New->getDeclName() << NewTy << OldTy;
4726 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4727 return true;
4728 }
Mike Stump11289f42009-09-09 15:08:12 +00004729
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004730 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004731 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004732 diag::err_covariant_return_inaccessible_base,
4733 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4734 // FIXME: Should this point to the return type?
4735 New->getLocation(), SourceRange(), New->getDeclName())) {
4736 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4737 return true;
4738 }
4739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004741 // The qualifiers of the return types must be the same.
4742 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4743 Diag(New->getLocation(),
4744 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004745 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004746 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4747 return true;
4748 };
Mike Stump11289f42009-09-09 15:08:12 +00004749
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004750
4751 // The new class type must have the same or less qualifiers as the old type.
4752 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4753 Diag(New->getLocation(),
4754 diag::err_covariant_return_type_class_type_more_qualified)
4755 << New->getDeclName() << NewTy << OldTy;
4756 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4757 return true;
4758 };
Mike Stump11289f42009-09-09 15:08:12 +00004759
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004760 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004761}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004762
4763/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4764/// initializer for the declaration 'Dcl'.
4765/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4766/// static data member of class X, names should be looked up in the scope of
4767/// class X.
4768void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004769 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004770
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004771 Decl *D = Dcl.getAs<Decl>();
4772 // If there is no declaration, there was an error parsing it.
4773 if (D == 0)
4774 return;
4775
4776 // Check whether it is a declaration with a nested name specifier like
4777 // int foo::bar;
4778 if (!D->isOutOfLine())
4779 return;
Mike Stump11289f42009-09-09 15:08:12 +00004780
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004781 // C++ [basic.lookup.unqual]p13
4782 //
4783 // A name used in the definition of a static data member of class X
4784 // (after the qualified-id of the static member) is looked up as if the name
4785 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004786
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004787 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004788 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004789}
4790
4791/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4792/// initializer for the declaration 'Dcl'.
4793void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004794 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004795
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004796 Decl *D = Dcl.getAs<Decl>();
4797 // If there is no declaration, there was an error parsing it.
4798 if (D == 0)
4799 return;
4800
4801 // Check whether it is a declaration with a nested name specifier like
4802 // int foo::bar;
4803 if (!D->isOutOfLine())
4804 return;
4805
4806 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004807 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004808}