blob: 4be5c62ee04313dd87de9dce8526ff5d4fc3fe60 [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"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000024#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000026#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000028#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000029#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000030
31using namespace clang;
32
Chris Lattner58258242008-04-10 02:22:51 +000033//===----------------------------------------------------------------------===//
34// CheckDefaultArgumentVisitor
35//===----------------------------------------------------------------------===//
36
Chris Lattnerb0d38442008-04-12 23:52:44 +000037namespace {
38 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
39 /// the default argument of a parameter to determine whether it
40 /// contains any ill-formed subexpressions. For example, this will
41 /// diagnose the use of local variables or parameters within the
42 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000043 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000044 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000045 Expr *DefaultArg;
46 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000047
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 public:
Mike Stump11289f42009-09-09 15:08:12 +000049 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000050 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000051
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 bool VisitExpr(Expr *Node);
53 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000054 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 };
Chris Lattner58258242008-04-10 02:22:51 +000056
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 /// VisitExpr - Visit all of the children of this expression.
58 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
59 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000060 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000061 E = Node->child_end(); I != E; ++I)
62 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000064 }
65
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 /// VisitDeclRefExpr - Visit a reference to a declaration, to
67 /// determine whether this declaration can be used in the default
68 /// argument expression.
69 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000070 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
72 // C++ [dcl.fct.default]p9
73 // Default arguments are evaluated each time the function is
74 // called. The order of evaluation of function arguments is
75 // unspecified. Consequently, parameters of a function shall not
76 // be used in default argument expressions, even if they are not
77 // evaluated. Parameters of a function declared before a default
78 // argument expression are in scope and can hide namespace and
79 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000080 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000081 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000082 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000083 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000084 // C++ [dcl.fct.default]p7
85 // Local variables shall not be used in default argument
86 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000087 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000090 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000091 }
Chris Lattner58258242008-04-10 02:22:51 +000092
Douglas Gregor8e12c382008-11-04 13:41:56 +000093 return false;
94 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000095
Douglas Gregor97a9c812008-11-04 14:32:21 +000096 /// VisitCXXThisExpr - Visit a C++ "this" expression.
97 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
98 // C++ [dcl.fct.default]p8:
99 // The keyword this shall not be used in a default argument of a
100 // member function.
101 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000102 diag::err_param_default_argument_references_this)
103 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000104 }
Chris Lattner58258242008-04-10 02:22:51 +0000105}
106
Anders Carlssonc80a1272009-08-25 02:29:20 +0000107bool
108Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000109 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000110 QualType ParamType = Param->getType();
111
Anders Carlsson114056f2009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssonc80a1272009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000119
Anders Carlssonc80a1272009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000126 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000127 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000128 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000129
130 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000131
Anders Carlssonc80a1272009-08-25 02:29:20 +0000132 // Okay: add the default argument to the parameter
133 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000134
Anders Carlssonc80a1272009-08-25 02:29:20 +0000135 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000136
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000137 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138}
139
Chris Lattner58258242008-04-10 02:22:51 +0000140/// ActOnParamDefaultArgument - Check whether the default argument
141/// provided for a function parameter is well-formed. If so, attach it
142/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000143void
Mike Stump11289f42009-09-09 15:08:12 +0000144Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000145 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000146 if (!param || !defarg.get())
147 return;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Chris Lattner83f095c2009-03-28 19:18:32 +0000149 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000150 UnparsedDefaultArgLocs.erase(Param);
151
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000152 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000153 QualType ParamType = Param->getType();
154
155 // Default arguments are only permitted in C++
156 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000157 Diag(EqualLoc, diag::err_param_default_argument)
158 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000159 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000160 return;
161 }
162
Anders Carlssonf1c26952009-08-25 01:02:06 +0000163 // Check that the default argument is well-formed
164 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
165 if (DefaultArgChecker.Visit(DefaultArg.get())) {
166 Param->setInvalidDecl();
167 return;
168 }
Mike Stump11289f42009-09-09 15:08:12 +0000169
Anders Carlssonc80a1272009-08-25 02:29:20 +0000170 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000171}
172
Douglas Gregor58354032008-12-24 00:01:03 +0000173/// ActOnParamUnparsedDefaultArgument - We've seen a default
174/// argument for a function parameter, but we can't parse it yet
175/// because we're inside a class definition. Note that this default
176/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000177void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000178 SourceLocation EqualLoc,
179 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000180 if (!param)
181 return;
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner83f095c2009-03-28 19:18:32 +0000183 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000184 if (Param)
185 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000186
Anders Carlsson84613c42009-06-12 16:51:40 +0000187 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000188}
189
Douglas Gregor4d87df52008-12-16 21:30:33 +0000190/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
191/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000192void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000193 if (!param)
194 return;
Mike Stump11289f42009-09-09 15:08:12 +0000195
Anders Carlsson84613c42009-06-12 16:51:40 +0000196 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000197
Anders Carlsson84613c42009-06-12 16:51:40 +0000198 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000201}
202
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000203/// CheckExtraCXXDefaultArguments - Check for any extra default
204/// arguments in the declarator, which is not a function declaration
205/// or definition and therefore is not permitted to have default
206/// arguments. This routine should be invoked for every declarator
207/// that is not a function declaration or definition.
208void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
209 // C++ [dcl.fct.default]p3
210 // A default argument expression shall be specified only in the
211 // parameter-declaration-clause of a function declaration or in a
212 // template-parameter (14.1). It shall not be specified for a
213 // parameter pack. If it is specified in a
214 // parameter-declaration-clause, it shall not occur within a
215 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000216 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000217 DeclaratorChunk &chunk = D.getTypeObject(i);
218 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000219 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
220 ParmVarDecl *Param =
221 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000222 if (Param->hasUnparsedDefaultArg()) {
223 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
225 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
226 delete Toks;
227 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000228 } else if (Param->getDefaultArg()) {
229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << Param->getDefaultArg()->getSourceRange();
231 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000232 }
233 }
234 }
235 }
236}
237
Chris Lattner199abbc2008-04-08 05:04:30 +0000238// MergeCXXFunctionDecl - Merge two declarations of the same C++
239// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000240// type. Subroutine of MergeFunctionDecl. Returns true if there was an
241// error, false otherwise.
242bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
243 bool Invalid = false;
244
Chris Lattner199abbc2008-04-08 05:04:30 +0000245 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000257 //
258 // C++ [dcl.fct.default]p6:
259 // Except for member functions of class templates, the default arguments
260 // in a member function definition that appears outside of the class
261 // definition are added to the set of default arguments provided by the
262 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000263 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
264 ParmVarDecl *OldParam = Old->getParamDecl(p);
265 ParmVarDecl *NewParam = New->getParamDecl(p);
266
Douglas Gregorc732aba2009-09-11 18:44:32 +0000267 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000268 // FIXME: If the parameter doesn't have an identifier then the location
269 // points to the '=' which means that the fixit hint won't remove any
270 // extra spaces between the type and the '='.
271 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson1566eb52009-11-10 03:32:44 +0000272 if (NewParam->getIdentifier())
273 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000274
Mike Stump11289f42009-09-09 15:08:12 +0000275 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000276 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000277 << NewParam->getDefaultArgRange()
278 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
279 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280
281 // Look for the function declaration where the default argument was
282 // actually written, which may be a declaration prior to Old.
283 for (FunctionDecl *Older = Old->getPreviousDeclaration();
284 Older; Older = Older->getPreviousDeclaration()) {
285 if (!Older->getParamDecl(p)->hasDefaultArg())
286 break;
287
288 OldParam = Older->getParamDecl(p);
289 }
290
291 Diag(OldParam->getLocation(), diag::note_previous_definition)
292 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000293 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000294 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000295 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000296 if (OldParam->hasUninstantiatedDefaultArg())
297 NewParam->setUninstantiatedDefaultArg(
298 OldParam->getUninstantiatedDefaultArg());
299 else
300 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000301 } else if (NewParam->hasDefaultArg()) {
302 if (New->getDescribedFunctionTemplate()) {
303 // Paragraph 4, quoted above, only applies to non-template functions.
304 Diag(NewParam->getLocation(),
305 diag::err_param_default_argument_template_redecl)
306 << NewParam->getDefaultArgRange();
307 Diag(Old->getLocation(), diag::note_template_prev_declaration)
308 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000309 } else if (New->getTemplateSpecializationKind()
310 != TSK_ImplicitInstantiation &&
311 New->getTemplateSpecializationKind() != TSK_Undeclared) {
312 // C++ [temp.expr.spec]p21:
313 // Default function arguments shall not be specified in a declaration
314 // or a definition for one of the following explicit specializations:
315 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000316 // - the explicit specialization of a member function template;
317 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000318 // template where the class template specialization to which the
319 // member function specialization belongs is implicitly
320 // instantiated.
321 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
322 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
323 << New->getDeclName()
324 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000325 } else if (New->getDeclContext()->isDependentContext()) {
326 // C++ [dcl.fct.default]p6 (DR217):
327 // Default arguments for a member function of a class template shall
328 // be specified on the initial declaration of the member function
329 // within the class template.
330 //
331 // Reading the tea leaves a bit in DR217 and its reference to DR205
332 // leads me to the conclusion that one cannot add default function
333 // arguments for an out-of-line definition of a member function of a
334 // dependent type.
335 int WhichKind = 2;
336 if (CXXRecordDecl *Record
337 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
338 if (Record->getDescribedClassTemplate())
339 WhichKind = 0;
340 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
341 WhichKind = 1;
342 else
343 WhichKind = 2;
344 }
345
346 Diag(NewParam->getLocation(),
347 diag::err_param_default_argument_member_template_redecl)
348 << WhichKind
349 << NewParam->getDefaultArgRange();
350 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000351 }
352 }
353
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000354 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000355 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
356 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000357 Invalid = true;
358 }
359
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000393 else
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregor556877c2008-04-13 21:30:24 +0000416
Douglas Gregor61956c42008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedmanc96d4962009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
491
492 // C++ [dcl.init.aggr]p1:
493 // An aggregate is [...] a class with [...] no base classes [...].
494 Class->setAggregate(false);
495 Class->setPOD(false);
496
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000497 if (Virtual) {
498 // C++ [class.ctor]p5:
499 // A constructor is trivial if its class has no virtual base classes.
500 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000501
502 // C++ [class.copy]p6:
503 // A copy constructor is trivial if its class has no virtual base classes.
504 Class->setHasTrivialCopyConstructor(false);
505
506 // C++ [class.copy]p11:
507 // A copy assignment operator is trivial if its class has no virtual
508 // base classes.
509 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000510
511 // C++0x [meta.unary.prop] is_empty:
512 // T is a class type, but not a union type, with ... no virtual base
513 // classes
514 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000515 } else {
516 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000517 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000518 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000519 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
520 Class->setHasTrivialConstructor(false);
521
522 // C++ [class.copy]p6:
523 // A copy constructor is trivial if all the direct base classes of its
524 // class have trivial copy constructors.
525 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
526 Class->setHasTrivialCopyConstructor(false);
527
528 // C++ [class.copy]p11:
529 // A copy assignment operator is trivial if all the direct base classes
530 // of its class have trivial copy assignment operators.
531 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
532 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000533 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000534
535 // C++ [class.ctor]p3:
536 // A destructor is trivial if all the direct base classes of its class
537 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000538 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
539 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000540
Douglas Gregor463421d2009-03-03 04:44:36 +0000541 // Create the base specifier.
542 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000543 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
544 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000545 Access, BaseType);
546}
547
Douglas Gregor556877c2008-04-13 21:30:24 +0000548/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
549/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000550/// example:
551/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000552/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000553Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000554Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000555 bool Virtual, AccessSpecifier Access,
556 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000557 if (!classdecl)
558 return true;
559
Douglas Gregorc40290e2009-03-09 23:48:35 +0000560 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000561 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000562 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000563 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
564 Virtual, Access,
565 BaseType, BaseLoc))
566 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000567
Douglas Gregor463421d2009-03-03 04:44:36 +0000568 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000569}
Douglas Gregor556877c2008-04-13 21:30:24 +0000570
Douglas Gregor463421d2009-03-03 04:44:36 +0000571/// \brief Performs the actual work of attaching the given base class
572/// specifiers to a C++ class.
573bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
574 unsigned NumBases) {
575 if (NumBases == 0)
576 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000577
578 // Used to keep track of which base types we have already seen, so
579 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000580 // that the key is always the unqualified canonical type of the base
581 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
583
584 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000585 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000587 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000588 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000590 NewBaseType = NewBaseType.getUnqualifiedType();
591
Douglas Gregor29a92472008-10-22 17:49:05 +0000592 if (KnownBaseTypes[NewBaseType]) {
593 // C++ [class.mi]p3:
594 // A class shall not be specified as a direct base class of a
595 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000597 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000598 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000599 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000600
601 // Delete the duplicate base class specifier; we're going to
602 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000603 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000604
605 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 } else {
607 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000608 KnownBaseTypes[NewBaseType] = Bases[idx];
609 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000610 }
611 }
612
613 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000614 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615
616 // Delete the remaining (good) base class specifiers, since their
617 // data has been copied into the CXXRecordDecl.
618 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000619 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000620
621 return Invalid;
622}
623
624/// ActOnBaseSpecifiers - Attach the given base specifiers to the
625/// class, after checking whether there are any duplicate base
626/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000627void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000628 unsigned NumBases) {
629 if (!ClassDecl || !Bases || !NumBases)
630 return;
631
632 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000633 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000635}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000636
Douglas Gregor36d1b142009-10-06 17:59:45 +0000637/// \brief Determine whether the type \p Derived is a C++ class that is
638/// derived from the type \p Base.
639bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
640 if (!getLangOptions().CPlusPlus)
641 return false;
642
643 const RecordType *DerivedRT = Derived->getAs<RecordType>();
644 if (!DerivedRT)
645 return false;
646
647 const RecordType *BaseRT = Base->getAs<RecordType>();
648 if (!BaseRT)
649 return false;
650
651 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
652 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
653 return DerivedRD->isDerivedFrom(BaseRD);
654}
655
656/// \brief Determine whether the type \p Derived is a C++ class that is
657/// derived from the type \p Base.
658bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
659 if (!getLangOptions().CPlusPlus)
660 return false;
661
662 const RecordType *DerivedRT = Derived->getAs<RecordType>();
663 if (!DerivedRT)
664 return false;
665
666 const RecordType *BaseRT = Base->getAs<RecordType>();
667 if (!BaseRT)
668 return false;
669
670 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
671 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
672 return DerivedRD->isDerivedFrom(BaseRD, Paths);
673}
674
675/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
676/// conversion (where Derived and Base are class types) is
677/// well-formed, meaning that the conversion is unambiguous (and
678/// that all of the base classes are accessible). Returns true
679/// and emits a diagnostic if the code is ill-formed, returns false
680/// otherwise. Loc is the location where this routine should point to
681/// if there is an error, and Range is the source range to highlight
682/// if there is an error.
683bool
684Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
685 unsigned InaccessibleBaseID,
686 unsigned AmbigiousBaseConvID,
687 SourceLocation Loc, SourceRange Range,
688 DeclarationName Name) {
689 // First, determine whether the path from Derived to Base is
690 // ambiguous. This is slightly more expensive than checking whether
691 // the Derived to Base conversion exists, because here we need to
692 // explore multiple paths to determine if there is an ambiguity.
693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
694 /*DetectVirtual=*/false);
695 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
696 assert(DerivationOkay &&
697 "Can only be used with a derived-to-base conversion");
698 (void)DerivationOkay;
699
700 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
701 // Check that the base class can be accessed.
702 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
703 Name);
704 }
705
706 // We know that the derived-to-base conversion is ambiguous, and
707 // we're going to produce a diagnostic. Perform the derived-to-base
708 // search just one more time to compute all of the possible paths so
709 // that we can print them out. This is more expensive than any of
710 // the previous derived-to-base checks we've done, but at this point
711 // performance isn't as much of an issue.
712 Paths.clear();
713 Paths.setRecordingPaths(true);
714 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
715 assert(StillOkay && "Can only be used with a derived-to-base conversion");
716 (void)StillOkay;
717
718 // Build up a textual representation of the ambiguous paths, e.g.,
719 // D -> B -> A, that will be used to illustrate the ambiguous
720 // conversions in the diagnostic. We only print one of the paths
721 // to each base class subobject.
722 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
723
724 Diag(Loc, AmbigiousBaseConvID)
725 << Derived << Base << PathDisplayStr << Range << Name;
726 return true;
727}
728
729bool
730Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
731 SourceLocation Loc, SourceRange Range) {
732 return CheckDerivedToBaseConversion(Derived, Base,
733 diag::err_conv_to_inaccessible_base,
734 diag::err_ambiguous_derived_to_base_conv,
735 Loc, Range, DeclarationName());
736}
737
738
739/// @brief Builds a string representing ambiguous paths from a
740/// specific derived class to different subobjects of the same base
741/// class.
742///
743/// This function builds a string that can be used in error messages
744/// to show the different paths that one can take through the
745/// inheritance hierarchy to go from the derived class to different
746/// subobjects of a base class. The result looks something like this:
747/// @code
748/// struct D -> struct B -> struct A
749/// struct D -> struct C -> struct A
750/// @endcode
751std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
752 std::string PathDisplayStr;
753 std::set<unsigned> DisplayedPaths;
754 for (CXXBasePaths::paths_iterator Path = Paths.begin();
755 Path != Paths.end(); ++Path) {
756 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
757 // We haven't displayed a path to this particular base
758 // class subobject yet.
759 PathDisplayStr += "\n ";
760 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
761 for (CXXBasePath::const_iterator Element = Path->begin();
762 Element != Path->end(); ++Element)
763 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
764 }
765 }
766
767 return PathDisplayStr;
768}
769
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000770//===----------------------------------------------------------------------===//
771// C++ class member Handling
772//===----------------------------------------------------------------------===//
773
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000774/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
775/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
776/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000777/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000778Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000779Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000780 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000781 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000782 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000783 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000784 Expr *BitWidth = static_cast<Expr*>(BW);
785 Expr *Init = static_cast<Expr*>(InitExpr);
786 SourceLocation Loc = D.getIdentifierLoc();
787
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000788 bool isFunc = D.isFunctionDeclarator();
789
John McCall07e91c02009-08-06 02:15:43 +0000790 assert(!DS.isFriendSpecified());
791
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000792 // C++ 9.2p6: A member shall not be declared to have automatic storage
793 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000794 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
795 // data members and cannot be applied to names declared const or static,
796 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000797 switch (DS.getStorageClassSpec()) {
798 case DeclSpec::SCS_unspecified:
799 case DeclSpec::SCS_typedef:
800 case DeclSpec::SCS_static:
801 // FALL THROUGH.
802 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000803 case DeclSpec::SCS_mutable:
804 if (isFunc) {
805 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000806 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000807 else
Chris Lattner3b054132008-11-19 05:08:23 +0000808 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000809
Sebastian Redl8071edb2008-11-17 23:24:37 +0000810 // FIXME: It would be nicer if the keyword was ignored only for this
811 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000812 D.getMutableDeclSpec().ClearStorageClassSpecs();
813 } else {
814 QualType T = GetTypeForDeclarator(D, S);
815 diag::kind err = static_cast<diag::kind>(0);
816 if (T->isReferenceType())
817 err = diag::err_mutable_reference;
818 else if (T.isConstQualified())
819 err = diag::err_mutable_const;
820 if (err != 0) {
821 if (DS.getStorageClassSpecLoc().isValid())
822 Diag(DS.getStorageClassSpecLoc(), err);
823 else
824 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000825 // FIXME: It would be nicer if the keyword was ignored only for this
826 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829 }
830 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000831 default:
832 if (DS.getStorageClassSpecLoc().isValid())
833 Diag(DS.getStorageClassSpecLoc(),
834 diag::err_storageclass_invalid_for_member);
835 else
836 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
837 D.getMutableDeclSpec().ClearStorageClassSpecs();
838 }
839
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000840 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000841 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000842 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000843 // Check also for this case:
844 //
845 // typedef int f();
846 // f a;
847 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000848 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000849 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000850 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000851
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000852 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
853 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000854 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000855
856 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000857 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000858 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000859 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
860 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000861 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000862 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000863 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
864 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000865 if (!Member) {
866 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000867 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000868 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000869
870 // Non-instance-fields can't have a bitfield.
871 if (BitWidth) {
872 if (Member->isInvalidDecl()) {
873 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000874 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000875 // C++ 9.6p3: A bit-field shall not be a static member.
876 // "static member 'A' cannot be a bit-field"
877 Diag(Loc, diag::err_static_not_bitfield)
878 << Name << BitWidth->getSourceRange();
879 } else if (isa<TypedefDecl>(Member)) {
880 // "typedef member 'x' cannot be a bit-field"
881 Diag(Loc, diag::err_typedef_not_bitfield)
882 << Name << BitWidth->getSourceRange();
883 } else {
884 // A function typedef ("typedef int f(); f a;").
885 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
886 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000887 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000888 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000889 }
Mike Stump11289f42009-09-09 15:08:12 +0000890
Chris Lattnerd26760a2009-03-05 23:01:03 +0000891 DeleteExpr(BitWidth);
892 BitWidth = 0;
893 Member->setInvalidDecl();
894 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000895
896 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregor3447e762009-08-20 22:52:58 +0000898 // If we have declared a member function template, set the access of the
899 // templated declaration as well.
900 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
901 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000902 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000903
Douglas Gregor92751d42008-11-17 22:58:34 +0000904 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000905
Douglas Gregor0c880302009-03-11 23:00:04 +0000906 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000907 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000908 if (Deleted) // FIXME: Source location is not very good.
909 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000910
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000911 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000912 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000913 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000915 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000916}
917
Douglas Gregore8381c02008-11-05 04:29:56 +0000918/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000919Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000920Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000921 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000922 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000923 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000924 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000925 SourceLocation IdLoc,
926 SourceLocation LParenLoc,
927 ExprTy **Args, unsigned NumArgs,
928 SourceLocation *CommaLocs,
929 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000930 if (!ConstructorD)
931 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000932
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000933 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000934
935 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000936 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000937 if (!Constructor) {
938 // The user wrote a constructor initializer on a function that is
939 // not a C++ constructor. Ignore the error for now, because we may
940 // have more member initializers coming; we'll diagnose it just
941 // once in ActOnMemInitializers.
942 return true;
943 }
944
945 CXXRecordDecl *ClassDecl = Constructor->getParent();
946
947 // C++ [class.base.init]p2:
948 // Names in a mem-initializer-id are looked up in the scope of the
949 // constructor’s class and, if not found in that scope, are looked
950 // up in the scope containing the constructor’s
951 // definition. [Note: if the constructor’s class contains a member
952 // with the same name as a direct or virtual base class of the
953 // class, a mem-initializer-id naming the member or base class and
954 // composed of a single identifier refers to the class member. A
955 // mem-initializer-id for the hidden base class may be specified
956 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000957 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000958 // Look for a member, first.
959 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000960 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000961 = ClassDecl->lookup(MemberOrBase);
962 if (Result.first != Result.second)
963 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000964
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000965 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000966
Eli Friedman8e1433b2009-07-29 19:44:27 +0000967 if (Member)
968 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
969 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000970 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000971 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000972 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000973 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000974 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000975 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
976 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000977
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000978 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000979
Eli Friedman8e1433b2009-07-29 19:44:27 +0000980 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
981 RParenLoc, ClassDecl);
982}
983
John McCalle22a04a2009-11-04 23:02:40 +0000984/// Checks an initializer expression for use of uninitialized fields, such as
985/// containing the field that is being initialized. Returns true if there is an
986/// uninitialized field was used an updates the SourceLocation parameter; false
987/// otherwise.
988static bool InitExprContainsUninitializedFields(const Stmt* S,
989 const FieldDecl* LhsField,
990 SourceLocation* L) {
991 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
992 if (ME) {
993 const NamedDecl* RhsField = ME->getMemberDecl();
994 if (RhsField == LhsField) {
995 // Initializing a field with itself. Throw a warning.
996 // But wait; there are exceptions!
997 // Exception #1: The field may not belong to this record.
998 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
999 const Expr* base = ME->getBase();
1000 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1001 // Even though the field matches, it does not belong to this record.
1002 return false;
1003 }
1004 // None of the exceptions triggered; return true to indicate an
1005 // uninitialized field was used.
1006 *L = ME->getMemberLoc();
1007 return true;
1008 }
1009 }
1010 bool found = false;
1011 for (Stmt::const_child_iterator it = S->child_begin();
1012 it != S->child_end() && found == false;
1013 ++it) {
1014 if (isa<CallExpr>(S)) {
1015 // Do not descend into function calls or constructors, as the use
1016 // of an uninitialized field may be valid. One would have to inspect
1017 // the contents of the function/ctor to determine if it is safe or not.
1018 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1019 // may be safe, depending on what the function/ctor does.
1020 continue;
1021 }
1022 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1023 }
1024 return found;
1025}
1026
Eli Friedman8e1433b2009-07-29 19:44:27 +00001027Sema::MemInitResult
1028Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1029 unsigned NumArgs, SourceLocation IdLoc,
1030 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001031 // Diagnose value-uses of fields to initialize themselves, e.g.
1032 // foo(foo)
1033 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001034 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001035 for (unsigned i = 0; i < NumArgs; ++i) {
1036 SourceLocation L;
1037 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1038 // FIXME: Return true in the case when other fields are used before being
1039 // uninitialized. For example, let this field be the i'th field. When
1040 // initializing the i'th field, throw a warning if any of the >= i'th
1041 // fields are used, as they are not yet initialized.
1042 // Right now we are only handling the case where the i'th field uses
1043 // itself in its initializer.
1044 Diag(L, diag::warn_field_is_uninit);
1045 }
1046 }
1047
Eli Friedman8e1433b2009-07-29 19:44:27 +00001048 bool HasDependentArg = false;
1049 for (unsigned i = 0; i < NumArgs; i++)
1050 HasDependentArg |= Args[i]->isTypeDependent();
1051
1052 CXXConstructorDecl *C = 0;
1053 QualType FieldType = Member->getType();
1054 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1055 FieldType = Array->getElementType();
1056 if (FieldType->isDependentType()) {
1057 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001058 } else if (FieldType->isRecordType()) {
1059 // Member is a record (struct/union/class), so pass the initializer
1060 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001061 if (!HasDependentArg) {
1062 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1063
1064 C = PerformInitializationByConstructor(FieldType,
1065 MultiExprArg(*this,
1066 (void**)Args,
1067 NumArgs),
1068 IdLoc,
1069 SourceRange(IdLoc, RParenLoc),
1070 Member->getDeclName(), IK_Direct,
1071 ConstructorArgs);
1072
1073 if (C) {
1074 // Take over the constructor arguments as our own.
1075 NumArgs = ConstructorArgs.size();
1076 Args = (Expr **)ConstructorArgs.take();
1077 }
1078 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001079 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001080 // The member type is not a record type (or an array of record
1081 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001082 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001083 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1084 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001085 Expr *NewExp;
1086 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001087 if (FieldType->isReferenceType()) {
1088 Diag(IdLoc, diag::err_null_intialized_reference_member)
1089 << Member->getDeclName();
1090 return Diag(Member->getLocation(), diag::note_declared_at);
1091 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001092 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1093 NumArgs = 1;
1094 }
1095 else
1096 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001097 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1098 return true;
1099 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001100 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001101 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001102 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001103 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001104}
1105
1106Sema::MemInitResult
1107Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1108 unsigned NumArgs, SourceLocation IdLoc,
1109 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1110 bool HasDependentArg = false;
1111 for (unsigned i = 0; i < NumArgs; i++)
1112 HasDependentArg |= Args[i]->isTypeDependent();
1113
1114 if (!BaseType->isDependentType()) {
1115 if (!BaseType->isRecordType())
1116 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1117 << BaseType << SourceRange(IdLoc, RParenLoc);
1118
1119 // C++ [class.base.init]p2:
1120 // [...] Unless the mem-initializer-id names a nonstatic data
1121 // member of the constructor’s class or a direct or virtual base
1122 // of that class, the mem-initializer is ill-formed. A
1123 // mem-initializer-list can initialize a base class using any
1124 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001125
Eli Friedman8e1433b2009-07-29 19:44:27 +00001126 // First, check for a direct base class.
1127 const CXXBaseSpecifier *DirectBaseSpec = 0;
1128 for (CXXRecordDecl::base_class_const_iterator Base =
1129 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +00001130 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +00001131 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1132 // We found a direct base of this type. That's what we're
1133 // initializing.
1134 DirectBaseSpec = &*Base;
1135 break;
1136 }
1137 }
Mike Stump11289f42009-09-09 15:08:12 +00001138
Eli Friedman8e1433b2009-07-29 19:44:27 +00001139 // Check for a virtual base class.
1140 // FIXME: We might be able to short-circuit this if we know in advance that
1141 // there are no virtual bases.
1142 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1143 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1144 // We haven't found a base yet; search the class hierarchy for a
1145 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001146 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1147 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001148 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001149 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001150 Path != Paths.end(); ++Path) {
1151 if (Path->back().Base->isVirtual()) {
1152 VirtualBaseSpec = Path->back().Base;
1153 break;
1154 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001155 }
1156 }
1157 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001158
1159 // C++ [base.class.init]p2:
1160 // If a mem-initializer-id is ambiguous because it designates both
1161 // a direct non-virtual base class and an inherited virtual base
1162 // class, the mem-initializer is ill-formed.
1163 if (DirectBaseSpec && VirtualBaseSpec)
1164 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1165 << BaseType << SourceRange(IdLoc, RParenLoc);
1166 // C++ [base.class.init]p2:
1167 // Unless the mem-initializer-id names a nonstatic data membeer of the
1168 // constructor's class ot a direst or virtual base of that class, the
1169 // mem-initializer is ill-formed.
1170 if (!DirectBaseSpec && !VirtualBaseSpec)
1171 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1172 << BaseType << ClassDecl->getNameAsCString()
1173 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001174 }
1175
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001176 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001177 if (!BaseType->isDependentType() && !HasDependentArg) {
1178 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001179 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001180 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1181
1182 C = PerformInitializationByConstructor(BaseType,
1183 MultiExprArg(*this,
1184 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001185 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001186 Name, IK_Direct,
1187 ConstructorArgs);
1188 if (C) {
1189 // Take over the constructor arguments as our own.
1190 NumArgs = ConstructorArgs.size();
1191 Args = (Expr **)ConstructorArgs.take();
1192 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001193 }
1194
Mike Stump11289f42009-09-09 15:08:12 +00001195 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001196 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001197}
1198
Eli Friedman9cf6b592009-11-09 19:20:36 +00001199bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001200Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001201 CXXBaseOrMemberInitializer **Initializers,
1202 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001203 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001204 // We need to build the initializer AST according to order of construction
1205 // and not what user specified in the Initializers list.
1206 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1207 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1208 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1209 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001210 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001211
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001212 for (unsigned i = 0; i < NumInitializers; i++) {
1213 CXXBaseOrMemberInitializer *Member = Initializers[i];
1214 if (Member->isBaseInitializer()) {
1215 if (Member->getBaseClass()->isDependentType())
1216 HasDependentBaseInit = true;
1217 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1218 } else {
1219 AllBaseFields[Member->getMember()] = Member;
1220 }
1221 }
Mike Stump11289f42009-09-09 15:08:12 +00001222
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001223 if (HasDependentBaseInit) {
1224 // FIXME. This does not preserve the ordering of the initializers.
1225 // Try (with -Wreorder)
1226 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001227 // template<class X> struct B : A<X> {
1228 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001229 // int x1;
1230 // };
1231 // B<int> x;
1232 // On seeing one dependent type, we should essentially exit this routine
1233 // while preserving user-declared initializer list. When this routine is
1234 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001235 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001236
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001237 // If we have a dependent base initialization, we can't determine the
1238 // association between initializers and bases; just dump the known
1239 // initializers into the list, and don't try to deal with other bases.
1240 for (unsigned i = 0; i < NumInitializers; i++) {
1241 CXXBaseOrMemberInitializer *Member = Initializers[i];
1242 if (Member->isBaseInitializer())
1243 AllToInit.push_back(Member);
1244 }
1245 } else {
1246 // Push virtual bases before others.
1247 for (CXXRecordDecl::base_class_iterator VBase =
1248 ClassDecl->vbases_begin(),
1249 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1250 if (VBase->getType()->isDependentType())
1251 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001252 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001253 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001254 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001255 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001256 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001257 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1258 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001259 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001260 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001261 else {
Mike Stump11289f42009-09-09 15:08:12 +00001262 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001263 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001264 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001265 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001266 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001267 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1268 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1269 << 0 << VBase->getType();
1270 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1271 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001272 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001273 continue;
1274 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001275
Anders Carlsson561f7932009-10-29 15:46:07 +00001276 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1277 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1278 Constructor->getLocation(), CtorArgs))
1279 continue;
1280
1281 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1282
Mike Stump11289f42009-09-09 15:08:12 +00001283 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001284 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1285 CtorArgs.takeAs<Expr>(),
1286 CtorArgs.size(), Ctor,
1287 SourceLocation(),
1288 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001289 AllToInit.push_back(Member);
1290 }
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001293 for (CXXRecordDecl::base_class_iterator Base =
1294 ClassDecl->bases_begin(),
1295 E = ClassDecl->bases_end(); Base != E; ++Base) {
1296 // Virtuals are in the virtual base list and already constructed.
1297 if (Base->isVirtual())
1298 continue;
1299 // Skip dependent types.
1300 if (Base->getType()->isDependentType())
1301 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001302 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001303 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001304 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001305 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001306 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001307 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1308 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001309 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001310 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001311 else {
Mike Stump11289f42009-09-09 15:08:12 +00001312 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001313 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001314 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001315 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001316 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001317 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1318 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1319 << 0 << Base->getType();
1320 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1321 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001322 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001323 continue;
1324 }
1325
1326 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1327 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1328 Constructor->getLocation(), CtorArgs))
1329 continue;
1330
1331 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001332
Mike Stump11289f42009-09-09 15:08:12 +00001333 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001334 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1335 CtorArgs.takeAs<Expr>(),
1336 CtorArgs.size(), Ctor,
1337 SourceLocation(),
1338 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001339 AllToInit.push_back(Member);
1340 }
1341 }
1342 }
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001344 // non-static data members.
1345 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1346 E = ClassDecl->field_end(); Field != E; ++Field) {
1347 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001348 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001349 Field->getType()->getAs<RecordType>()) {
1350 CXXRecordDecl *FieldClassDecl
1351 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001352 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001353 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1354 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1355 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1356 // set to the anonymous union data member used in the initializer
1357 // list.
1358 Value->setMember(*Field);
1359 Value->setAnonUnionMember(*FA);
1360 AllToInit.push_back(Value);
1361 break;
1362 }
1363 }
1364 }
1365 continue;
1366 }
1367 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001368 QualType FT = (*Field)->getType();
1369 if (const RecordType* RT = FT->getAs<RecordType>()) {
1370 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001371 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump11289f42009-09-09 15:08:12 +00001372 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001373 FieldRecDecl->getDefaultConstructor(Context))
1374 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1375 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001376 AllToInit.push_back(Value);
1377 continue;
1378 }
Mike Stump11289f42009-09-09 15:08:12 +00001379
Eli Friedmand7686ef2009-11-09 01:05:47 +00001380 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001381 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001382
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001383 QualType FT = Context.getBaseElementType((*Field)->getType());
1384 if (const RecordType* RT = FT->getAs<RecordType>()) {
1385 CXXConstructorDecl *Ctor =
1386 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001387 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001388 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1389 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1390 << 1 << (*Field)->getDeclName();
1391 Diag(Field->getLocation(), diag::note_field_decl);
1392 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1393 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001394 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001395 continue;
1396 }
1397
1398 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1399 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1400 Constructor->getLocation(), CtorArgs))
1401 continue;
1402
Mike Stump11289f42009-09-09 15:08:12 +00001403 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001404 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1405 CtorArgs.size(), Ctor,
1406 SourceLocation(),
1407 SourceLocation());
1408
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001409 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001410 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1411 if (FT.isConstQualified() && Ctor->isTrivial()) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001412 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001413 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1414 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001415 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001416 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001417 }
1418 }
1419 else if (FT->isReferenceType()) {
1420 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001421 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1422 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001423 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001424 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001425 }
1426 else if (FT.isConstQualified()) {
1427 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001428 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1429 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001430 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001431 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001432 }
1433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001435 NumInitializers = AllToInit.size();
1436 if (NumInitializers > 0) {
1437 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1438 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1439 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001440
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001441 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1442 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1443 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1444 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001445
1446 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001447}
1448
Eli Friedman952c15d2009-07-21 19:28:10 +00001449static void *GetKeyForTopLevelField(FieldDecl *Field) {
1450 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001451 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001452 if (RT->getDecl()->isAnonymousStructOrUnion())
1453 return static_cast<void *>(RT->getDecl());
1454 }
1455 return static_cast<void *>(Field);
1456}
1457
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001458static void *GetKeyForBase(QualType BaseType) {
1459 if (const RecordType *RT = BaseType->getAs<RecordType>())
1460 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001461
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001462 assert(0 && "Unexpected base type!");
1463 return 0;
1464}
1465
Mike Stump11289f42009-09-09 15:08:12 +00001466static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001467 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001468 // For fields injected into the class via declaration of an anonymous union,
1469 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001470 if (Member->isMemberInitializer()) {
1471 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001472
Eli Friedmand7686ef2009-11-09 01:05:47 +00001473 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001474 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001475 // in AnonUnionMember field.
1476 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1477 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001478 if (Field->getDeclContext()->isRecord()) {
1479 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1480 if (RD->isAnonymousStructOrUnion())
1481 return static_cast<void *>(RD);
1482 }
1483 return static_cast<void *>(Field);
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001486 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001487}
1488
John McCallc90f6d72009-11-04 23:13:52 +00001489/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001490void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001491 SourceLocation ColonLoc,
1492 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001493 if (!ConstructorDecl)
1494 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001495
1496 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001497
1498 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001499 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001500
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001501 if (!Constructor) {
1502 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1503 return;
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001506 if (!Constructor->isDependentContext()) {
1507 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1508 bool err = false;
1509 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001510 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001511 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1512 void *KeyToMember = GetKeyForMember(Member);
1513 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1514 if (!PrevMember) {
1515 PrevMember = Member;
1516 continue;
1517 }
1518 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001519 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001520 diag::error_multiple_mem_initialization)
1521 << Field->getNameAsString();
1522 else {
1523 Type *BaseClass = Member->getBaseClass();
1524 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001525 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001526 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001527 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001528 }
1529 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1530 << 0;
1531 err = true;
1532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001534 if (err)
1535 return;
1536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Eli Friedmand7686ef2009-11-09 01:05:47 +00001538 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001539 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001540 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001541
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001542 if (Constructor->isDependentContext())
1543 return;
Mike Stump11289f42009-09-09 15:08:12 +00001544
1545 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001546 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001547 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001548 Diagnostic::Ignored)
1549 return;
Mike Stump11289f42009-09-09 15:08:12 +00001550
Anders Carlssone0eebb32009-08-27 05:45:01 +00001551 // Also issue warning if order of ctor-initializer list does not match order
1552 // of 1) base class declarations and 2) order of non-static data members.
1553 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001554
Anders Carlssone0eebb32009-08-27 05:45:01 +00001555 CXXRecordDecl *ClassDecl
1556 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1557 // Push virtual bases before others.
1558 for (CXXRecordDecl::base_class_iterator VBase =
1559 ClassDecl->vbases_begin(),
1560 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001561 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001562
Anders Carlssone0eebb32009-08-27 05:45:01 +00001563 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1564 E = ClassDecl->bases_end(); Base != E; ++Base) {
1565 // Virtuals are alread in the virtual base list and are constructed
1566 // first.
1567 if (Base->isVirtual())
1568 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001569 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001570 }
Mike Stump11289f42009-09-09 15:08:12 +00001571
Anders Carlssone0eebb32009-08-27 05:45:01 +00001572 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1573 E = ClassDecl->field_end(); Field != E; ++Field)
1574 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001575
Anders Carlssone0eebb32009-08-27 05:45:01 +00001576 int Last = AllBaseOrMembers.size();
1577 int curIndex = 0;
1578 CXXBaseOrMemberInitializer *PrevMember = 0;
1579 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001580 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001581 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1582 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001583
Anders Carlssone0eebb32009-08-27 05:45:01 +00001584 for (; curIndex < Last; curIndex++)
1585 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1586 break;
1587 if (curIndex == Last) {
1588 assert(PrevMember && "Member not in member list?!");
1589 // Initializer as specified in ctor-initializer list is out of order.
1590 // Issue a warning diagnostic.
1591 if (PrevMember->isBaseInitializer()) {
1592 // Diagnostics is for an initialized base class.
1593 Type *BaseClass = PrevMember->getBaseClass();
1594 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001595 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001596 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001597 } else {
1598 FieldDecl *Field = PrevMember->getMember();
1599 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001600 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001601 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001602 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001603 // Also the note!
1604 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001605 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001606 diag::note_fieldorbase_initialized_here) << 0
1607 << Field->getNameAsString();
1608 else {
1609 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001610 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001611 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001612 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001613 }
1614 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001615 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001616 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001617 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001618 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001619 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001620}
1621
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001622void
1623Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1624 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1625 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001626
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001627 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1628 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1629 if (VBase->getType()->isDependentType())
1630 continue;
1631 // Skip over virtual bases which have trivial destructors.
1632 CXXRecordDecl *BaseClassDecl
1633 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1634 if (BaseClassDecl->hasTrivialDestructor())
1635 continue;
1636 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001637 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001638 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001639
1640 uintptr_t Member =
1641 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001642 | CXXDestructorDecl::VBASE;
1643 AllToDestruct.push_back(Member);
1644 }
1645 for (CXXRecordDecl::base_class_iterator Base =
1646 ClassDecl->bases_begin(),
1647 E = ClassDecl->bases_end(); Base != E; ++Base) {
1648 if (Base->isVirtual())
1649 continue;
1650 if (Base->getType()->isDependentType())
1651 continue;
1652 // Skip over virtual bases which have trivial destructors.
1653 CXXRecordDecl *BaseClassDecl
1654 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1655 if (BaseClassDecl->hasTrivialDestructor())
1656 continue;
1657 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001658 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001659 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001660 uintptr_t Member =
1661 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001662 | CXXDestructorDecl::DRCTNONVBASE;
1663 AllToDestruct.push_back(Member);
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001666 // non-static data members.
1667 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1668 E = ClassDecl->field_end(); Field != E; ++Field) {
1669 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001670
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001671 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1672 // Skip over virtual bases which have trivial destructors.
1673 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1674 if (FieldClassDecl->hasTrivialDestructor())
1675 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001676 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001677 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001678 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001679 const_cast<CXXDestructorDecl*>(Dtor));
1680 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1681 AllToDestruct.push_back(Member);
1682 }
1683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001685 unsigned NumDestructions = AllToDestruct.size();
1686 if (NumDestructions > 0) {
1687 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001688 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001689 new (Context) uintptr_t [NumDestructions];
1690 // Insert in reverse order.
1691 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1692 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1693 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1694 }
1695}
1696
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001697void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001698 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001699 return;
Mike Stump11289f42009-09-09 15:08:12 +00001700
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001701 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001702
1703 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001704 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001705 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001706}
1707
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001708namespace {
1709 /// PureVirtualMethodCollector - traverses a class and its superclasses
1710 /// and determines if it has any pure virtual methods.
1711 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1712 ASTContext &Context;
1713
Sebastian Redlb7d64912009-03-22 21:28:55 +00001714 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001715 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001716
1717 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001718 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001719
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001720 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001722 public:
Mike Stump11289f42009-09-09 15:08:12 +00001723 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001724 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001725
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001726 MethodList List;
1727 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001728
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001729 // Copy the temporary list to methods, and make sure to ignore any
1730 // null entries.
1731 for (size_t i = 0, e = List.size(); i != e; ++i) {
1732 if (List[i])
1733 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001734 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001737 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001738
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001739 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1740 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001741 };
Mike Stump11289f42009-09-09 15:08:12 +00001742
1743 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001744 MethodList& Methods) {
1745 // First, collect the pure virtual methods for the base classes.
1746 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1747 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001748 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001749 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001750 if (BaseDecl && BaseDecl->isAbstract())
1751 Collect(BaseDecl, Methods);
1752 }
1753 }
Mike Stump11289f42009-09-09 15:08:12 +00001754
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001755 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001756 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001757
Anders Carlsson3c012712009-05-17 00:00:05 +00001758 MethodSetTy OverriddenMethods;
1759 size_t MethodsSize = Methods.size();
1760
Mike Stump11289f42009-09-09 15:08:12 +00001761 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001762 i != e; ++i) {
1763 // Traverse the record, looking for methods.
1764 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001765 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001766 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001767 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001768
Anders Carlsson700179432009-10-18 19:34:08 +00001769 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001770 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1771 E = MD->end_overridden_methods(); I != E; ++I) {
1772 // Keep track of the overridden methods.
1773 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001774 }
1775 }
1776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
1778 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001779 // overridden.
1780 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1781 if (OverriddenMethods.count(Methods[i]))
1782 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001785 }
1786}
Douglas Gregore8381c02008-11-05 04:29:56 +00001787
Anders Carlssoneabf7702009-08-27 00:13:57 +00001788
Mike Stump11289f42009-09-09 15:08:12 +00001789bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001790 unsigned DiagID, AbstractDiagSelID SelID,
1791 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001792 if (SelID == -1)
1793 return RequireNonAbstractType(Loc, T,
1794 PDiag(DiagID), CurrentRD);
1795 else
1796 return RequireNonAbstractType(Loc, T,
1797 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001798}
1799
Anders Carlssoneabf7702009-08-27 00:13:57 +00001800bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1801 const PartialDiagnostic &PD,
1802 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001803 if (!getLangOptions().CPlusPlus)
1804 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001805
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001806 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001807 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001808 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001809
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001810 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001811 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001812 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001813 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001814
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001815 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001816 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001819 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001820 if (!RT)
1821 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001822
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001823 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1824 if (!RD)
1825 return false;
1826
Anders Carlssonb57738b2009-03-24 17:23:42 +00001827 if (CurrentRD && CurrentRD != RD)
1828 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001829
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001830 if (!RD->isAbstract())
1831 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001832
Anders Carlssoneabf7702009-08-27 00:13:57 +00001833 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001834
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001835 // Check if we've already emitted the list of pure virtual functions for this
1836 // class.
1837 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1838 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001839
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001840 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001841
1842 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001843 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1844 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001845
1846 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001847 MD->getDeclName();
1848 }
1849
1850 if (!PureVirtualClassDiagSet)
1851 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1852 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001854 return true;
1855}
1856
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001857namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001858 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001859 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1860 Sema &SemaRef;
1861 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001862
Anders Carlssonb57738b2009-03-24 17:23:42 +00001863 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001864 bool Invalid = false;
1865
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001866 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1867 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001868 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001869
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001870 return Invalid;
1871 }
Mike Stump11289f42009-09-09 15:08:12 +00001872
Anders Carlssonb57738b2009-03-24 17:23:42 +00001873 public:
1874 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1875 : SemaRef(SemaRef), AbstractClass(ac) {
1876 Visit(SemaRef.Context.getTranslationUnitDecl());
1877 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001878
Anders Carlssonb57738b2009-03-24 17:23:42 +00001879 bool VisitFunctionDecl(const FunctionDecl *FD) {
1880 if (FD->isThisDeclarationADefinition()) {
1881 // No need to do the check if we're in a definition, because it requires
1882 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001883 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001884 return VisitDeclContext(FD);
1885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886
Anders Carlssonb57738b2009-03-24 17:23:42 +00001887 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001888 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001889 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001890 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1891 diag::err_abstract_type_in_decl,
1892 Sema::AbstractReturnType,
1893 AbstractClass);
1894
Mike Stump11289f42009-09-09 15:08:12 +00001895 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001896 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001897 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001898 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001899 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001900 VD->getOriginalType(),
1901 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001902 Sema::AbstractParamType,
1903 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001904 }
1905
1906 return Invalid;
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
Anders Carlssonb57738b2009-03-24 17:23:42 +00001909 bool VisitDecl(const Decl* D) {
1910 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1911 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001912
Anders Carlssonb57738b2009-03-24 17:23:42 +00001913 return false;
1914 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001915 };
1916}
1917
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001918void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001919 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001920 SourceLocation LBrac,
1921 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001922 if (!TagDecl)
1923 return;
Mike Stump11289f42009-09-09 15:08:12 +00001924
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001925 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001926 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001927 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001928 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001929
Chris Lattner83f095c2009-03-28 19:18:32 +00001930 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001931 if (!RD->isAbstract()) {
1932 // Collect all the pure virtual methods and see if this is an abstract
1933 // class after all.
1934 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001935 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001936 RD->setAbstract(true);
1937 }
Mike Stump11289f42009-09-09 15:08:12 +00001938
1939 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001940 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001941
Douglas Gregor3c74d412009-10-14 20:14:33 +00001942 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001943 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944}
1945
Douglas Gregor05379422008-11-03 17:51:48 +00001946/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1947/// special functions, such as the default constructor, copy
1948/// constructor, or destructor, to the given C++ class (C++
1949/// [special]p1). This routine can only be executed just before the
1950/// definition of the class is complete.
1951void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001952 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001953 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001954
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001955 // FIXME: Implicit declarations have exception specifications, which are
1956 // the union of the specifications of the implicitly called functions.
1957
Douglas Gregor05379422008-11-03 17:51:48 +00001958 if (!ClassDecl->hasUserDeclaredConstructor()) {
1959 // C++ [class.ctor]p5:
1960 // A default constructor for a class X is a constructor of class X
1961 // that can be called without an argument. If there is no
1962 // user-declared constructor for class X, a default constructor is
1963 // implicitly declared. An implicitly-declared default constructor
1964 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001965 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001966 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001967 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001968 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001969 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001970 Context.getFunctionType(Context.VoidTy,
1971 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001972 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001973 /*isExplicit=*/false,
1974 /*isInline=*/true,
1975 /*isImplicitlyDeclared=*/true);
1976 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001977 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001978 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001979 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001980 }
1981
1982 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1983 // C++ [class.copy]p4:
1984 // If the class definition does not explicitly declare a copy
1985 // constructor, one is declared implicitly.
1986
1987 // C++ [class.copy]p5:
1988 // The implicitly-declared copy constructor for a class X will
1989 // have the form
1990 //
1991 // X::X(const X&)
1992 //
1993 // if
1994 bool HasConstCopyConstructor = true;
1995
1996 // -- each direct or virtual base class B of X has a copy
1997 // constructor whose first parameter is of type const B& or
1998 // const volatile B&, and
1999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2000 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2001 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002002 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002003 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002004 = BaseClassDecl->hasConstCopyConstructor(Context);
2005 }
2006
2007 // -- for all the nonstatic data members of X that are of a
2008 // class type M (or array thereof), each such class type
2009 // has a copy constructor whose first parameter is of type
2010 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002011 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2012 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002013 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002014 QualType FieldType = (*Field)->getType();
2015 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2016 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002017 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002018 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002019 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002020 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002021 = FieldClassDecl->hasConstCopyConstructor(Context);
2022 }
2023 }
2024
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002025 // Otherwise, the implicitly declared copy constructor will have
2026 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002027 //
2028 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002029 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002030 if (HasConstCopyConstructor)
2031 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002032 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002033
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002034 // An implicitly-declared copy constructor is an inline public
2035 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002036 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002037 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002038 CXXConstructorDecl *CopyConstructor
2039 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002040 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002041 Context.getFunctionType(Context.VoidTy,
2042 &ArgType, 1,
2043 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002044 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002045 /*isExplicit=*/false,
2046 /*isInline=*/true,
2047 /*isImplicitlyDeclared=*/true);
2048 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002049 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002050 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002051
2052 // Add the parameter to the constructor.
2053 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2054 ClassDecl->getLocation(),
2055 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002056 ArgType, /*DInfo=*/0,
2057 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002058 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002059 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002060 }
2061
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002062 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2063 // Note: The following rules are largely analoguous to the copy
2064 // constructor rules. Note that virtual bases are not taken into account
2065 // for determining the argument type of the operator. Note also that
2066 // operators taking an object instead of a reference are allowed.
2067 //
2068 // C++ [class.copy]p10:
2069 // If the class definition does not explicitly declare a copy
2070 // assignment operator, one is declared implicitly.
2071 // The implicitly-defined copy assignment operator for a class X
2072 // will have the form
2073 //
2074 // X& X::operator=(const X&)
2075 //
2076 // if
2077 bool HasConstCopyAssignment = true;
2078
2079 // -- each direct base class B of X has a copy assignment operator
2080 // whose parameter is of type const B&, const volatile B& or B,
2081 // and
2082 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2083 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002084 assert(!Base->getType()->isDependentType() &&
2085 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002086 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002087 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002088 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002089 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002090 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002091 }
2092
2093 // -- for all the nonstatic data members of X that are of a class
2094 // type M (or array thereof), each such class type has a copy
2095 // assignment operator whose parameter is of type const M&,
2096 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002097 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2098 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002099 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002100 QualType FieldType = (*Field)->getType();
2101 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2102 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002103 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002104 const CXXRecordDecl *FieldClassDecl
2105 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002106 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002107 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002108 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002109 }
2110 }
2111
2112 // Otherwise, the implicitly declared copy assignment operator will
2113 // have the form
2114 //
2115 // X& X::operator=(X&)
2116 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002117 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002118 if (HasConstCopyAssignment)
2119 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002120 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002121
2122 // An implicitly-declared copy assignment operator is an inline public
2123 // member of its class.
2124 DeclarationName Name =
2125 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2126 CXXMethodDecl *CopyAssignment =
2127 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2128 Context.getFunctionType(RetType, &ArgType, 1,
2129 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002130 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002131 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002132 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002133 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002134 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002135
2136 // Add the parameter to the operator.
2137 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2138 ClassDecl->getLocation(),
2139 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002140 ArgType, /*DInfo=*/0,
2141 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002142 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002143
2144 // Don't call addedAssignmentOperator. There is no way to distinguish an
2145 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002146 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002147 }
2148
Douglas Gregor1349b452008-12-15 21:24:18 +00002149 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002150 // C++ [class.dtor]p2:
2151 // If a class has no user-declared destructor, a destructor is
2152 // declared implicitly. An implicitly-declared destructor is an
2153 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002154 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002155 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002156 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002157 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002158 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002159 Context.getFunctionType(Context.VoidTy,
2160 0, 0, false, 0),
2161 /*isInline=*/true,
2162 /*isImplicitlyDeclared=*/true);
2163 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002164 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002165 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002166 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002167 }
Douglas Gregor05379422008-11-03 17:51:48 +00002168}
2169
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002170void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002171 Decl *D = TemplateD.getAs<Decl>();
2172 if (!D)
2173 return;
2174
2175 TemplateParameterList *Params = 0;
2176 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2177 Params = Template->getTemplateParameters();
2178 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2179 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2180 Params = PartialSpec->getTemplateParameters();
2181 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002182 return;
2183
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002184 for (TemplateParameterList::iterator Param = Params->begin(),
2185 ParamEnd = Params->end();
2186 Param != ParamEnd; ++Param) {
2187 NamedDecl *Named = cast<NamedDecl>(*Param);
2188 if (Named->getDeclName()) {
2189 S->AddDecl(DeclPtrTy::make(Named));
2190 IdResolver.AddDecl(Named);
2191 }
2192 }
2193}
2194
Douglas Gregor4d87df52008-12-16 21:30:33 +00002195/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2196/// parsing a top-level (non-nested) C++ class, and we are now
2197/// parsing those parts of the given Method declaration that could
2198/// not be parsed earlier (C++ [class.mem]p2), such as default
2199/// arguments. This action should enter the scope of the given
2200/// Method declaration as if we had just parsed the qualified method
2201/// name. However, it should not bring the parameters into scope;
2202/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002203void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002204 if (!MethodD)
2205 return;
Mike Stump11289f42009-09-09 15:08:12 +00002206
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002207 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002208
Douglas Gregor4d87df52008-12-16 21:30:33 +00002209 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002210 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002211 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002212 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2213 SS.setScopeRep(
2214 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002215 ActOnCXXEnterDeclaratorScope(S, SS);
2216}
2217
2218/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2219/// C++ method declaration. We're (re-)introducing the given
2220/// function parameter into scope for use in parsing later parts of
2221/// the method declaration. For example, we could see an
2222/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002223void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002224 if (!ParamD)
2225 return;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Chris Lattner83f095c2009-03-28 19:18:32 +00002227 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002228
2229 // If this parameter has an unparsed default argument, clear it out
2230 // to make way for the parsed default argument.
2231 if (Param->hasUnparsedDefaultArg())
2232 Param->setDefaultArg(0);
2233
Chris Lattner83f095c2009-03-28 19:18:32 +00002234 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002235 if (Param->getDeclName())
2236 IdResolver.AddDecl(Param);
2237}
2238
2239/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2240/// processing the delayed method declaration for Method. The method
2241/// declaration is now considered finished. There may be a separate
2242/// ActOnStartOfFunctionDef action later (not necessarily
2243/// immediately!) for this method, if it was also defined inside the
2244/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002245void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002246 if (!MethodD)
2247 return;
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002249 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002250
Chris Lattner83f095c2009-03-28 19:18:32 +00002251 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002252 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002253 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002254 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2255 SS.setScopeRep(
2256 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002257 ActOnCXXExitDeclaratorScope(S, SS);
2258
2259 // Now that we have our default arguments, check the constructor
2260 // again. It could produce additional diagnostics or affect whether
2261 // the class has implicitly-declared destructors, among other
2262 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002263 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2264 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002265
2266 // Check the default arguments, which we may have added.
2267 if (!Method->isInvalidDecl())
2268 CheckCXXDefaultArguments(Method);
2269}
2270
Douglas Gregor831c93f2008-11-05 20:51:48 +00002271/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002272/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002273/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002274/// emit diagnostics and set the invalid bit to true. In any case, the type
2275/// will be updated to reflect a well-formed type for the constructor and
2276/// returned.
2277QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2278 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002279 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002280
2281 // C++ [class.ctor]p3:
2282 // A constructor shall not be virtual (10.3) or static (9.4). A
2283 // constructor can be invoked for a const, volatile or const
2284 // volatile object. A constructor shall not be declared const,
2285 // volatile, or const volatile (9.3.2).
2286 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002287 if (!D.isInvalidType())
2288 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2289 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2290 << SourceRange(D.getIdentifierLoc());
2291 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002292 }
2293 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002294 if (!D.isInvalidType())
2295 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2296 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2297 << SourceRange(D.getIdentifierLoc());
2298 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002299 SC = FunctionDecl::None;
2300 }
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattner38378bf2009-04-25 08:28:21 +00002302 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2303 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002304 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002305 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2306 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002307 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002308 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2309 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002310 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002311 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2312 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002313 }
Mike Stump11289f42009-09-09 15:08:12 +00002314
Douglas Gregor831c93f2008-11-05 20:51:48 +00002315 // Rebuild the function type "R" without any type qualifiers (in
2316 // case any of the errors above fired) and with "void" as the
2317 // return type, since constructors don't have return types. We
2318 // *always* have to do this, because GetTypeForDeclarator will
2319 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002320 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002321 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2322 Proto->getNumArgs(),
2323 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002324}
2325
Douglas Gregor4d87df52008-12-16 21:30:33 +00002326/// CheckConstructor - Checks a fully-formed constructor for
2327/// well-formedness, issuing any diagnostics required. Returns true if
2328/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002329void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002330 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002331 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2332 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002333 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002334
2335 // C++ [class.copy]p3:
2336 // A declaration of a constructor for a class X is ill-formed if
2337 // its first parameter is of type (optionally cv-qualified) X and
2338 // either there are no other parameters or else all other
2339 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002340 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002341 ((Constructor->getNumParams() == 1) ||
2342 (Constructor->getNumParams() > 1 &&
Anders Carlsson85446472009-06-06 04:14:07 +00002343 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002344 QualType ParamType = Constructor->getParamDecl(0)->getType();
2345 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2346 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002347 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2348 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002349 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002350 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002351 }
2352 }
Mike Stump11289f42009-09-09 15:08:12 +00002353
Douglas Gregor4d87df52008-12-16 21:30:33 +00002354 // Notify the class that we've added a constructor.
2355 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002356}
2357
Mike Stump11289f42009-09-09 15:08:12 +00002358static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002359FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2360 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2361 FTI.ArgInfo[0].Param &&
2362 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2363}
2364
Douglas Gregor831c93f2008-11-05 20:51:48 +00002365/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2366/// the well-formednes of the destructor declarator @p D with type @p
2367/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002368/// emit diagnostics and set the declarator to invalid. Even if this happens,
2369/// will be updated to reflect a well-formed type for the destructor and
2370/// returned.
2371QualType Sema::CheckDestructorDeclarator(Declarator &D,
2372 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002373 // C++ [class.dtor]p1:
2374 // [...] A typedef-name that names a class is a class-name
2375 // (7.1.3); however, a typedef-name that names a class shall not
2376 // be used as the identifier in the declarator for a destructor
2377 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002378 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002379 if (isa<TypedefType>(DeclaratorType)) {
2380 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002381 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002382 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002383 }
2384
2385 // C++ [class.dtor]p2:
2386 // A destructor is used to destroy objects of its class type. A
2387 // destructor takes no parameters, and no return type can be
2388 // specified for it (not even void). The address of a destructor
2389 // shall not be taken. A destructor shall not be static. A
2390 // destructor can be invoked for a const, volatile or const
2391 // volatile object. A destructor shall not be declared const,
2392 // volatile or const volatile (9.3.2).
2393 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002394 if (!D.isInvalidType())
2395 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2396 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2397 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002398 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002399 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002400 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002401 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002402 // Destructors don't have return types, but the parser will
2403 // happily parse something like:
2404 //
2405 // class X {
2406 // float ~X();
2407 // };
2408 //
2409 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002410 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2411 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2412 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
Chris Lattner38378bf2009-04-25 08:28:21 +00002415 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2416 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002417 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002418 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2419 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002420 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002421 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2422 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002423 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002424 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2425 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002426 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002427 }
2428
2429 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002430 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002431 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2432
2433 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002434 FTI.freeArgs();
2435 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002436 }
2437
Mike Stump11289f42009-09-09 15:08:12 +00002438 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002439 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002440 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002441 D.setInvalidType();
2442 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002443
2444 // Rebuild the function type "R" without any type qualifiers or
2445 // parameters (in case any of the errors above fired) and with
2446 // "void" as the return type, since destructors don't have return
2447 // types. We *always* have to do this, because GetTypeForDeclarator
2448 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002449 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002450}
2451
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002452/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2453/// well-formednes of the conversion function declarator @p D with
2454/// type @p R. If there are any errors in the declarator, this routine
2455/// will emit diagnostics and return true. Otherwise, it will return
2456/// false. Either way, the type @p R will be updated to reflect a
2457/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002458void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002459 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002460 // C++ [class.conv.fct]p1:
2461 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002462 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002463 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002464 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002465 if (!D.isInvalidType())
2466 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2467 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2468 << SourceRange(D.getIdentifierLoc());
2469 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002470 SC = FunctionDecl::None;
2471 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002472 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002473 // Conversion functions don't have return types, but the parser will
2474 // happily parse something like:
2475 //
2476 // class X {
2477 // float operator bool();
2478 // };
2479 //
2480 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002481 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2482 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2483 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002484 }
2485
2486 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002487 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002488 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2489
2490 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002491 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002492 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002493 }
2494
Mike Stump11289f42009-09-09 15:08:12 +00002495 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002496 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002497 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002498 D.setInvalidType();
2499 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002500
2501 // C++ [class.conv.fct]p4:
2502 // The conversion-type-id shall not represent a function type nor
2503 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002504 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002505 if (ConvType->isArrayType()) {
2506 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2507 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002508 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002509 } else if (ConvType->isFunctionType()) {
2510 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2511 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002512 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002513 }
2514
2515 // Rebuild the function type "R" without any parameters (in case any
2516 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002517 // return type.
2518 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002519 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002520
Douglas Gregor5fb53972009-01-14 15:45:31 +00002521 // C++0x explicit conversion operators.
2522 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002523 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002524 diag::warn_explicit_conversion_functions)
2525 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002526}
2527
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002528/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2529/// the declaration of the given C++ conversion function. This routine
2530/// is responsible for recording the conversion function in the C++
2531/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002532Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002533 assert(Conversion && "Expected to receive a conversion function declaration");
2534
Douglas Gregor4287b372008-12-12 08:25:50 +00002535 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002536
2537 // Make sure we aren't redeclaring the conversion function.
2538 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539
2540 // C++ [class.conv.fct]p1:
2541 // [...] A conversion function is never used to convert a
2542 // (possibly cv-qualified) object to the (possibly cv-qualified)
2543 // same object type (or a reference to it), to a (possibly
2544 // cv-qualified) base class of that type (or a reference to it),
2545 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002546 // FIXME: Suppress this warning if the conversion function ends up being a
2547 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002548 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002549 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002550 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002551 ConvType = ConvTypeRef->getPointeeType();
2552 if (ConvType->isRecordType()) {
2553 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2554 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002555 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002556 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002557 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002558 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002559 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002560 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002561 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002562 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002563 }
2564
Douglas Gregor1dc98262008-12-26 15:00:45 +00002565 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002566 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002567 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002568 = Conversion->getDescribedFunctionTemplate())
2569 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002570 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002571 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002572 Conv = Conversions->function_begin(),
2573 ConvEnd = Conversions->function_end();
2574 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002575 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002576 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002577 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002578 }
2579 }
2580 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002581 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002582 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002583 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002584 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002585 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002586
Chris Lattner83f095c2009-03-28 19:18:32 +00002587 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002588}
2589
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002590//===----------------------------------------------------------------------===//
2591// Namespace Handling
2592//===----------------------------------------------------------------------===//
2593
2594/// ActOnStartNamespaceDef - This is called at the start of a namespace
2595/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002596Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2597 SourceLocation IdentLoc,
2598 IdentifierInfo *II,
2599 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002600 NamespaceDecl *Namespc =
2601 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2602 Namespc->setLBracLoc(LBrace);
2603
2604 Scope *DeclRegionScope = NamespcScope->getParent();
2605
2606 if (II) {
2607 // C++ [namespace.def]p2:
2608 // The identifier in an original-namespace-definition shall not have been
2609 // previously defined in the declarative region in which the
2610 // original-namespace-definition appears. The identifier in an
2611 // original-namespace-definition is the name of the namespace. Subsequently
2612 // in that declarative region, it is treated as an original-namespace-name.
2613
John McCall9f3059a2009-10-09 21:13:30 +00002614 NamedDecl *PrevDecl
2615 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump11289f42009-09-09 15:08:12 +00002616
Douglas Gregor91f84212008-12-11 16:49:14 +00002617 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2618 // This is an extended namespace definition.
2619 // Attach this namespace decl to the chain of extended namespace
2620 // definitions.
2621 OrigNS->setNextNamespace(Namespc);
2622 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002623
Mike Stump11289f42009-09-09 15:08:12 +00002624 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002625 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002626 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002627 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002628 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002629 } else if (PrevDecl) {
2630 // This is an invalid name redefinition.
2631 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2632 << Namespc->getDeclName();
2633 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2634 Namespc->setInvalidDecl();
2635 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002636 } else if (II->isStr("std") &&
2637 CurContext->getLookupContext()->isTranslationUnit()) {
2638 // This is the first "real" definition of the namespace "std", so update
2639 // our cache of the "std" namespace to point at this definition.
2640 if (StdNamespace) {
2641 // We had already defined a dummy namespace "std". Link this new
2642 // namespace definition to the dummy namespace "std".
2643 StdNamespace->setNextNamespace(Namespc);
2644 StdNamespace->setLocation(IdentLoc);
2645 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2646 }
2647
2648 // Make our StdNamespace cache point at the first real definition of the
2649 // "std" namespace.
2650 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002651 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002652
2653 PushOnScopeChains(Namespc, DeclRegionScope);
2654 } else {
John McCall4fa53422009-10-01 00:25:31 +00002655 // Anonymous namespaces.
2656
2657 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2658 // behaves as if it were replaced by
2659 // namespace unique { /* empty body */ }
2660 // using namespace unique;
2661 // namespace unique { namespace-body }
2662 // where all occurrences of 'unique' in a translation unit are
2663 // replaced by the same identifier and this identifier differs
2664 // from all other identifiers in the entire program.
2665
2666 // We just create the namespace with an empty name and then add an
2667 // implicit using declaration, just like the standard suggests.
2668 //
2669 // CodeGen enforces the "universally unique" aspect by giving all
2670 // declarations semantically contained within an anonymous
2671 // namespace internal linkage.
2672
2673 assert(Namespc->isAnonymousNamespace());
2674 CurContext->addDecl(Namespc);
2675
2676 UsingDirectiveDecl* UD
2677 = UsingDirectiveDecl::Create(Context, CurContext,
2678 /* 'using' */ LBrace,
2679 /* 'namespace' */ SourceLocation(),
2680 /* qualifier */ SourceRange(),
2681 /* NNS */ NULL,
2682 /* identifier */ SourceLocation(),
2683 Namespc,
2684 /* Ancestor */ CurContext);
2685 UD->setImplicit();
2686 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002687 }
2688
2689 // Although we could have an invalid decl (i.e. the namespace name is a
2690 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002691 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2692 // for the namespace has the declarations that showed up in that particular
2693 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002694 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002695 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002696}
2697
2698/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2699/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002700void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2701 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002702 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2703 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2704 Namespc->setRBracLoc(RBrace);
2705 PopDeclContext();
2706}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002707
Chris Lattner83f095c2009-03-28 19:18:32 +00002708Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2709 SourceLocation UsingLoc,
2710 SourceLocation NamespcLoc,
2711 const CXXScopeSpec &SS,
2712 SourceLocation IdentLoc,
2713 IdentifierInfo *NamespcName,
2714 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002715 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2716 assert(NamespcName && "Invalid NamespcName.");
2717 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002718 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002719
Douglas Gregor889ceb72009-02-03 19:21:40 +00002720 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002721
Douglas Gregor34074322009-01-14 22:20:51 +00002722 // Lookup namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002723 LookupResult R;
2724 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002725 if (R.isAmbiguous()) {
2726 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002727 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002728 }
John McCall9f3059a2009-10-09 21:13:30 +00002729 if (!R.empty()) {
2730 NamedDecl *NS = R.getFoundDecl();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002731 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002732 // C++ [namespace.udir]p1:
2733 // A using-directive specifies that the names in the nominated
2734 // namespace can be used in the scope in which the
2735 // using-directive appears after the using-directive. During
2736 // unqualified name lookup (3.4.1), the names appear as if they
2737 // were declared in the nearest enclosing namespace which
2738 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002739 // namespace. [Note: in this context, "contains" means "contains
2740 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002741
2742 // Find enclosing context containing both using-directive and
2743 // nominated namespace.
2744 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2745 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2746 CommonAncestor = CommonAncestor->getParent();
2747
Mike Stump11289f42009-09-09 15:08:12 +00002748 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002749 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002750 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002751 SS.getRange(),
2752 (NestedNameSpecifier *)SS.getScopeRep(),
2753 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002754 cast<NamespaceDecl>(NS),
2755 CommonAncestor);
2756 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002757 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002758 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002759 }
2760
Douglas Gregor889ceb72009-02-03 19:21:40 +00002761 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002762 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002763 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002764}
2765
2766void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2767 // If scope has associated entity, then using directive is at namespace
2768 // or translation unit scope. We add UsingDirectiveDecls, into
2769 // it's lookup structure.
2770 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002771 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002772 else
2773 // Otherwise it is block-sope. using-directives will affect lookup
2774 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002775 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002776}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002777
Douglas Gregorfec52632009-06-20 00:51:54 +00002778
2779Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002780 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002781 SourceLocation UsingLoc,
2782 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002783 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002784 AttributeList *AttrList,
2785 bool IsTypeName) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002786 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002787
Douglas Gregor220f4272009-11-04 16:30:06 +00002788 switch (Name.getKind()) {
2789 case UnqualifiedId::IK_Identifier:
2790 case UnqualifiedId::IK_OperatorFunctionId:
2791 case UnqualifiedId::IK_ConversionFunctionId:
2792 break;
2793
2794 case UnqualifiedId::IK_ConstructorName:
2795 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2796 << SS.getRange();
2797 return DeclPtrTy();
2798
2799 case UnqualifiedId::IK_DestructorName:
2800 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2801 << SS.getRange();
2802 return DeclPtrTy();
2803
2804 case UnqualifiedId::IK_TemplateId:
2805 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2806 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2807 return DeclPtrTy();
2808 }
2809
2810 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2811 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2812 Name.getSourceRange().getBegin(),
2813 TargetName, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002814 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002815 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002816 UD->setAccess(AS);
2817 }
Mike Stump11289f42009-09-09 15:08:12 +00002818
Anders Carlsson696a3f12009-08-28 05:40:36 +00002819 return DeclPtrTy::make(UD);
2820}
2821
2822NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2823 const CXXScopeSpec &SS,
2824 SourceLocation IdentLoc,
2825 DeclarationName Name,
2826 AttributeList *AttrList,
2827 bool IsTypeName) {
2828 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2829 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002830
Anders Carlssonf038fc22009-08-28 05:49:21 +00002831 // FIXME: We ignore attributes for now.
2832 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002833
Anders Carlsson59140b32009-08-28 03:16:11 +00002834 if (SS.isEmpty()) {
2835 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002836 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002837 }
Mike Stump11289f42009-09-09 15:08:12 +00002838
2839 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002840 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2841
Anders Carlssonf038fc22009-08-28 05:49:21 +00002842 if (isUnknownSpecialization(SS)) {
2843 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2844 SS.getRange(), NNS,
2845 IdentLoc, Name, IsTypeName);
2846 }
Mike Stump11289f42009-09-09 15:08:12 +00002847
Anders Carlsson59140b32009-08-28 03:16:11 +00002848 DeclContext *LookupContext = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002849
Anders Carlsson59140b32009-08-28 03:16:11 +00002850 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2851 // C++0x N2914 [namespace.udecl]p3:
2852 // A using-declaration used as a member-declaration shall refer to a member
2853 // of a base class of the class being defined, shall refer to a member of an
2854 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002855 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002856 // a member of a base class of the class being defined.
2857 const Type *Ty = NNS->getAsType();
2858 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2859 Diag(SS.getRange().getBegin(),
2860 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2861 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002862 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002863 }
Anders Carlsson4bd78752009-08-28 15:18:15 +00002864
2865 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2866 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlsson59140b32009-08-28 03:16:11 +00002867 } else {
2868 // C++0x N2914 [namespace.udecl]p8:
2869 // A using-declaration for a class member shall be a member-declaration.
2870 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002871 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002872 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002873 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002874 }
Mike Stump11289f42009-09-09 15:08:12 +00002875
Anders Carlsson59140b32009-08-28 03:16:11 +00002876 // C++0x N2914 [namespace.udecl]p9:
2877 // In a using-declaration, a prefix :: refers to the global namespace.
2878 if (NNS->getKind() == NestedNameSpecifier::Global)
2879 LookupContext = Context.getTranslationUnitDecl();
2880 else
2881 LookupContext = NNS->getAsNamespace();
2882 }
2883
2884
Douglas Gregorfec52632009-06-20 00:51:54 +00002885 // Lookup target name.
John McCall9f3059a2009-10-09 21:13:30 +00002886 LookupResult R;
2887 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002888
John McCall9f3059a2009-10-09 21:13:30 +00002889 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002890 Diag(IdentLoc, diag::err_no_member)
2891 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002892 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002893 }
2894
John McCall9f3059a2009-10-09 21:13:30 +00002895 // FIXME: handle ambiguity?
2896 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002897
Anders Carlsson59140b32009-08-28 03:16:11 +00002898 if (IsTypeName && !isa<TypeDecl>(ND)) {
2899 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002900 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002901 }
2902
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002903 // C++0x N2914 [namespace.udecl]p6:
2904 // A using-declaration shall not name a namespace.
2905 if (isa<NamespaceDecl>(ND)) {
2906 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2907 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002908 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
Anders Carlsson696a3f12009-08-28 05:40:36 +00002911 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2912 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002913}
2914
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002915/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2916/// is a namespace alias, returns the namespace it points to.
2917static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2918 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2919 return AD->getNamespace();
2920 return dyn_cast_or_null<NamespaceDecl>(D);
2921}
2922
Mike Stump11289f42009-09-09 15:08:12 +00002923Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002924 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002925 SourceLocation AliasLoc,
2926 IdentifierInfo *Alias,
2927 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002928 SourceLocation IdentLoc,
2929 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002930
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002931 // Lookup the namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002932 LookupResult R;
2933 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002934
Anders Carlssondca83c42009-03-28 06:23:46 +00002935 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002936 if (NamedDecl *PrevDecl
2937 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002938 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002939 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002940 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00002941 if (!R.isAmbiguous() && !R.empty() &&
2942 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002943 return DeclPtrTy();
2944 }
Mike Stump11289f42009-09-09 15:08:12 +00002945
Anders Carlssondca83c42009-03-28 06:23:46 +00002946 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2947 diag::err_redefinition_different_kind;
2948 Diag(AliasLoc, DiagID) << Alias;
2949 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002950 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002951 }
2952
Anders Carlssonac2c9652009-03-28 06:42:02 +00002953 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002954 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002955 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002956 }
Mike Stump11289f42009-09-09 15:08:12 +00002957
John McCall9f3059a2009-10-09 21:13:30 +00002958 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00002959 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002960 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002961 }
Mike Stump11289f42009-09-09 15:08:12 +00002962
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002963 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002964 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2965 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002966 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00002967 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002968
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002969 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002970 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002971}
2972
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002973void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2974 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002975 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2976 !Constructor->isUsed()) &&
2977 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002978
Eli Friedman9cf6b592009-11-09 19:20:36 +00002979 CXXRecordDecl *ClassDecl
2980 = cast<CXXRecordDecl>(Constructor->getDeclContext());
2981 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00002982
Eli Friedman9cf6b592009-11-09 19:20:36 +00002983 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
2984 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
2985 << Context.getTagDeclType(ClassDecl);
2986 Constructor->setInvalidDecl();
2987 } else {
2988 Constructor->setUsed();
2989 }
Eli Friedmand7686ef2009-11-09 01:05:47 +00002990 return;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002991}
2992
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002993void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00002994 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002995 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2996 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00002997
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002998 CXXRecordDecl *ClassDecl
2999 = cast<CXXRecordDecl>(Destructor->getDeclContext());
3000 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3001 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003002 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003003 // implicitly defined, all the implicitly-declared default destructors
3004 // for its base class and its non-static data members shall have been
3005 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003006 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3007 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003008 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003009 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003010 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003011 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003012 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3013 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3014 else
Mike Stump11289f42009-09-09 15:08:12 +00003015 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003016 "DefineImplicitDestructor - missing dtor in a base class");
3017 }
3018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003020 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3021 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003022 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3023 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3024 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003025 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003026 CXXRecordDecl *FieldClassDecl
3027 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3028 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003029 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003030 const_cast<CXXDestructorDecl*>(
3031 FieldClassDecl->getDestructor(Context)))
3032 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3033 else
Mike Stump11289f42009-09-09 15:08:12 +00003034 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003035 "DefineImplicitDestructor - missing dtor in class of a data member");
3036 }
3037 }
3038 }
3039 Destructor->setUsed();
3040}
3041
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003042void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3043 CXXMethodDecl *MethodDecl) {
3044 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3045 MethodDecl->getOverloadedOperator() == OO_Equal &&
3046 !MethodDecl->isUsed()) &&
3047 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003048
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003049 CXXRecordDecl *ClassDecl
3050 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003051
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003052 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003053 // Before the implicitly-declared copy assignment operator for a class is
3054 // implicitly defined, all implicitly-declared copy assignment operators
3055 // for its direct base classes and its nonstatic data members shall have
3056 // been implicitly defined.
3057 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3059 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003060 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003061 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003062 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003063 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3064 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3065 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003066 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3067 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003068 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3069 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3070 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003071 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003072 CXXRecordDecl *FieldClassDecl
3073 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003074 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003075 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3076 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003077 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003078 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003079 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3080 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003081 Diag(CurrentLocation, diag::note_first_required_here);
3082 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003083 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003084 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003085 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3086 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003087 Diag(CurrentLocation, diag::note_first_required_here);
3088 err = true;
3089 }
3090 }
3091 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003092 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003093}
3094
3095CXXMethodDecl *
3096Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3097 CXXRecordDecl *ClassDecl) {
3098 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3099 QualType RHSType(LHSType);
3100 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003101 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003102 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003103 RHSType = Context.getCVRQualifiedType(RHSType,
3104 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003105 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3106 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003107 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003108 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3109 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003110 SourceLocation()));
3111 Expr *Args[2] = { &*LHS, &*RHS };
3112 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003113 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003114 CandidateSet);
3115 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003116 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003117 ClassDecl->getLocation(), Best) == OR_Success)
3118 return cast<CXXMethodDecl>(Best->Function);
3119 assert(false &&
3120 "getAssignOperatorMethod - copy assignment operator method not found");
3121 return 0;
3122}
3123
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003124void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3125 CXXConstructorDecl *CopyConstructor,
3126 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003127 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003128 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3129 !CopyConstructor->isUsed()) &&
3130 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003131
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003132 CXXRecordDecl *ClassDecl
3133 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3134 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003135 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003136 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003137 // implicitly defined, all the implicitly-declared copy constructors
3138 // for its base class and its non-static data members shall have been
3139 // implicitly defined.
3140 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3141 Base != ClassDecl->bases_end(); ++Base) {
3142 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003143 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003144 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003145 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003146 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003147 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003148 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3149 FieldEnd = ClassDecl->field_end();
3150 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003151 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3152 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3153 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003154 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003155 CXXRecordDecl *FieldClassDecl
3156 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003157 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003158 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003159 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003160 }
3161 }
3162 CopyConstructor->setUsed();
3163}
3164
Anders Carlsson6eb55572009-08-25 05:12:04 +00003165Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003166Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003167 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003168 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003169 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003171 // C++ [class.copy]p15:
3172 // Whenever a temporary class object is copied using a copy constructor, and
3173 // this object and the copy have the same cv-unqualified type, an
3174 // implementation is permitted to treat the original and the copy as two
3175 // different ways of referring to the same object and not perform a copy at
3176 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003177
Anders Carlsson250aada2009-08-16 05:13:48 +00003178 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003179 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003180 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003181 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3182 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003183 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3184 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3185 E = ICE->getSubExpr();
3186
Anders Carlsson250aada2009-08-16 05:13:48 +00003187 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3188 Elidable = true;
3189 }
Mike Stump11289f42009-09-09 15:08:12 +00003190
3191 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003192 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003193}
3194
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003195/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3196/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003197Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003198Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3199 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003200 MultiExprArg ExprArgs) {
3201 unsigned NumExprs = ExprArgs.size();
3202 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003203
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003204 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3205 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003206}
3207
Anders Carlsson574315a2009-08-27 05:08:22 +00003208Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003209Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3210 QualType Ty,
3211 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003212 MultiExprArg Args,
3213 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003214 unsigned NumExprs = Args.size();
3215 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003216
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003217 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3218 TyBeginLoc, Exprs,
3219 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003220}
3221
3222
Mike Stump11289f42009-09-09 15:08:12 +00003223bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003224 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003225 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003226 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003227 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003228 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003229 if (TempResult.isInvalid())
3230 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003231
Anders Carlsson6eb55572009-08-25 05:12:04 +00003232 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003233 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003234 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003235 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003236
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003237 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003238}
3239
Mike Stump11289f42009-09-09 15:08:12 +00003240void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003241 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003242 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003243 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003244 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003245 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003246 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003247}
3248
Mike Stump11289f42009-09-09 15:08:12 +00003249/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003250/// ActOnDeclarator, when a C++ direct initializer is present.
3251/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003252void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3253 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003254 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003255 SourceLocation *CommaLocs,
3256 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003257 unsigned NumExprs = Exprs.size();
3258 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003259 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003260
3261 // If there is no declaration, there was an error parsing it. Just ignore
3262 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003263 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003264 return;
Mike Stump11289f42009-09-09 15:08:12 +00003265
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003266 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3267 if (!VDecl) {
3268 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3269 RealDecl->setInvalidDecl();
3270 return;
3271 }
3272
Douglas Gregor402250f2009-08-26 21:14:46 +00003273 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003274 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003275 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3276 //
3277 // Clients that want to distinguish between the two forms, can check for
3278 // direct initializer using VarDecl::hasCXXDirectInitializer().
3279 // A major benefit is that clients that don't particularly care about which
3280 // exactly form was it (like the CodeGen) can handle both cases without
3281 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003282
Douglas Gregor402250f2009-08-26 21:14:46 +00003283 // If either the declaration has a dependent type or if any of the expressions
3284 // is type-dependent, we represent the initialization via a ParenListExpr for
3285 // later use during template instantiation.
3286 if (VDecl->getType()->isDependentType() ||
3287 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3288 // Let clients know that initialization was done with a direct initializer.
3289 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregor402250f2009-08-26 21:14:46 +00003291 // Store the initialization expressions as a ParenListExpr.
3292 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003293 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003294 new (Context) ParenListExpr(Context, LParenLoc,
3295 (Expr **)Exprs.release(),
3296 NumExprs, RParenLoc));
3297 return;
3298 }
Mike Stump11289f42009-09-09 15:08:12 +00003299
Douglas Gregor402250f2009-08-26 21:14:46 +00003300
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003301 // C++ 8.5p11:
3302 // The form of initialization (using parentheses or '=') is generally
3303 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003304 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003305 QualType DeclInitType = VDecl->getType();
3306 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003307 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003308
Douglas Gregor4044d992009-03-24 16:43:20 +00003309 // FIXME: This isn't the right place to complete the type.
3310 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3311 diag::err_typecheck_decl_incomplete_type)) {
3312 VDecl->setInvalidDecl();
3313 return;
3314 }
3315
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003316 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003317 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3318
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003319 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003320 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003321 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003322 VDecl->getLocation(),
3323 SourceRange(VDecl->getLocation(),
3324 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003325 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003326 IK_Direct,
3327 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003328 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003329 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003330 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003331 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003332 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003333 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003334 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003335 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003336 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003337 return;
3338 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003339
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003340 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003341 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3342 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003343 RealDecl->setInvalidDecl();
3344 return;
3345 }
3346
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003347 // Let clients know that initialization was done with a direct initializer.
3348 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003349
3350 assert(NumExprs == 1 && "Expected 1 expression");
3351 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003352 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3353 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003354}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003355
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003356/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3357/// may occur as part of direct-initialization or copy-initialization.
3358///
3359/// \param ClassType the type of the object being initialized, which must have
3360/// class type.
3361///
3362/// \param ArgsPtr the arguments provided to initialize the object
3363///
3364/// \param Loc the source location where the initialization occurs
3365///
3366/// \param Range the source range that covers the entire initialization
3367///
3368/// \param InitEntity the name of the entity being initialized, if known
3369///
3370/// \param Kind the type of initialization being performed
3371///
3372/// \param ConvertedArgs a vector that will be filled in with the
3373/// appropriately-converted arguments to the constructor (if initialization
3374/// succeeded).
3375///
3376/// \returns the constructor used to initialize the object, if successful.
3377/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003378CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003379Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003380 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003381 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003382 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003383 InitializationKind Kind,
3384 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003385 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003386 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003387 Expr **Args = (Expr **)ArgsPtr.get();
3388 unsigned NumArgs = ArgsPtr.size();
3389
Mike Stump11289f42009-09-09 15:08:12 +00003390 // C++ [dcl.init]p14:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003391 // If the initialization is direct-initialization, or if it is
3392 // copy-initialization where the cv-unqualified version of the
3393 // source type is the same class as, or a derived class of, the
3394 // class of the destination, constructors are considered. The
3395 // applicable constructors are enumerated (13.3.1.3), and the
3396 // best one is chosen through overload resolution (13.3). The
3397 // constructor so selected is called to initialize the object,
3398 // with the initializer expression(s) as its argument(s). If no
3399 // constructor applies, or the overload resolution is ambiguous,
3400 // the initialization is ill-formed.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003401 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3402 OverloadCandidateSet CandidateSet;
Douglas Gregor6f543152008-11-05 15:29:30 +00003403
3404 // Add constructors to the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00003405 DeclarationName ConstructorName
Douglas Gregor1349b452008-12-15 21:24:18 +00003406 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00003407 Context.getCanonicalType(ClassType).getUnqualifiedType());
Douglas Gregor55297ac2008-12-23 00:26:44 +00003408 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003409 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00003410 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003411 // Find the constructor (which may be a template).
3412 CXXConstructorDecl *Constructor = 0;
3413 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3414 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003415 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003416 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3417 else
3418 Constructor = cast<CXXConstructorDecl>(*Con);
3419
Douglas Gregor6f543152008-11-05 15:29:30 +00003420 if ((Kind == IK_Direct) ||
Mike Stump11289f42009-09-09 15:08:12 +00003421 (Kind == IK_Copy &&
Anders Carlssond20e7952009-08-28 16:57:08 +00003422 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003423 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3424 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003425 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003426 Args, NumArgs, CandidateSet);
3427 else
3428 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3429 }
Douglas Gregor6f543152008-11-05 15:29:30 +00003430 }
3431
Douglas Gregor1349b452008-12-15 21:24:18 +00003432 // FIXME: When we decide not to synthesize the implicitly-declared
3433 // constructors, we'll need to make them appear here.
3434
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003435 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003436 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003437 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003438 // We found a constructor. Break out so that we can convert the arguments
3439 // appropriately.
3440 break;
Mike Stump11289f42009-09-09 15:08:12 +00003441
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003442 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003443 if (InitEntity)
3444 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003445 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003446 else
3447 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003448 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003449 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003450 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003451
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003452 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003453 if (InitEntity)
3454 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3455 else
3456 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003457 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3458 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003459
3460 case OR_Deleted:
3461 if (InitEntity)
3462 Diag(Loc, diag::err_ovl_deleted_init)
3463 << Best->Function->isDeleted()
3464 << InitEntity << Range;
3465 else
3466 Diag(Loc, diag::err_ovl_deleted_init)
3467 << Best->Function->isDeleted()
3468 << InitEntity << Range;
3469 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3470 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003473 // Convert the arguments, fill in default arguments, etc.
3474 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3475 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3476 return 0;
3477
3478 return Constructor;
3479}
3480
3481/// \brief Given a constructor and the set of arguments provided for the
3482/// constructor, convert the arguments and add any required default arguments
3483/// to form a proper call to this constructor.
3484///
3485/// \returns true if an error occurred, false otherwise.
3486bool
3487Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3488 MultiExprArg ArgsPtr,
3489 SourceLocation Loc,
3490 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3491 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3492 unsigned NumArgs = ArgsPtr.size();
3493 Expr **Args = (Expr **)ArgsPtr.get();
3494
3495 const FunctionProtoType *Proto
3496 = Constructor->getType()->getAs<FunctionProtoType>();
3497 assert(Proto && "Constructor without a prototype?");
3498 unsigned NumArgsInProto = Proto->getNumArgs();
3499 unsigned NumArgsToCheck = NumArgs;
3500
3501 // If too few arguments are available, we'll fill in the rest with defaults.
3502 if (NumArgs < NumArgsInProto) {
3503 NumArgsToCheck = NumArgsInProto;
3504 ConvertedArgs.reserve(NumArgsInProto);
3505 } else {
3506 ConvertedArgs.reserve(NumArgs);
3507 if (NumArgs > NumArgsInProto)
3508 NumArgsToCheck = NumArgsInProto;
3509 }
3510
3511 // Convert arguments
3512 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3513 QualType ProtoArgType = Proto->getArgType(i);
3514
3515 Expr *Arg;
3516 if (i < NumArgs) {
3517 Arg = Args[i];
Anders Carlssonc8bfc462009-09-15 21:14:33 +00003518
3519 // Pass the argument.
3520 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3521 return true;
3522
3523 Args[i] = 0;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003524 } else {
3525 ParmVarDecl *Param = Constructor->getParamDecl(i);
3526
3527 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3528 if (DefArg.isInvalid())
3529 return true;
3530
3531 Arg = DefArg.takeAs<Expr>();
3532 }
3533
3534 ConvertedArgs.push_back(Arg);
3535 }
3536
3537 // If this is a variadic call, handle args passed through "...".
3538 if (Proto->isVariadic()) {
3539 // Promote the arguments (C99 6.5.2.2p7).
3540 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3541 Expr *Arg = Args[i];
3542 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3543 return true;
3544
3545 ConvertedArgs.push_back(Arg);
3546 Args[i] = 0;
3547 }
3548 }
3549
3550 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003551}
3552
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003553/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3554/// determine whether they are reference-related,
3555/// reference-compatible, reference-compatible with added
3556/// qualification, or incompatible, for use in C++ initialization by
3557/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3558/// type, and the first type (T1) is the pointee type of the reference
3559/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003560Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003561Sema::CompareReferenceRelationship(SourceLocation Loc,
3562 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003563 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003564 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003565 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003566 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003567
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003568 QualType T1 = Context.getCanonicalType(OrigT1);
3569 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003570 QualType UnqualT1 = T1.getUnqualifiedType();
3571 QualType UnqualT2 = T2.getUnqualifiedType();
3572
3573 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003574 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003575 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003576 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003577 if (UnqualT1 == UnqualT2)
3578 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003579 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3580 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3581 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003582 DerivedToBase = true;
3583 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003584 return Ref_Incompatible;
3585
3586 // At this point, we know that T1 and T2 are reference-related (at
3587 // least).
3588
3589 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003590 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003591 // reference-related to T2 and cv1 is the same cv-qualification
3592 // as, or greater cv-qualification than, cv2. For purposes of
3593 // overload resolution, cases for which cv1 is greater
3594 // cv-qualification than cv2 are identified as
3595 // reference-compatible with added qualification (see 13.3.3.2).
3596 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3597 return Ref_Compatible;
3598 else if (T1.isMoreQualifiedThan(T2))
3599 return Ref_Compatible_With_Added_Qualification;
3600 else
3601 return Ref_Related;
3602}
3603
3604/// CheckReferenceInit - Check the initialization of a reference
3605/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3606/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003607/// list), and DeclType is the type of the declaration. When ICS is
3608/// non-null, this routine will compute the implicit conversion
3609/// sequence according to C++ [over.ics.ref] and will not produce any
3610/// diagnostics; when ICS is null, it will emit diagnostics when any
3611/// errors are found. Either way, a return value of true indicates
3612/// that there was a failure, a return value of false indicates that
3613/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003614///
3615/// When @p SuppressUserConversions, user-defined conversions are
3616/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003617/// When @p AllowExplicit, we also permit explicit user-defined
3618/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003619/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump11289f42009-09-09 15:08:12 +00003620bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003621Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003622 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003623 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003624 bool AllowExplicit, bool ForceRValue,
3625 ImplicitConversionSequence *ICS) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003626 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3627
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003628 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003629 QualType T2 = Init->getType();
3630
Douglas Gregorcd695e52008-11-10 20:40:00 +00003631 // If the initializer is the address of an overloaded function, try
3632 // to resolve the overloaded function. If all goes well, T2 is the
3633 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003634 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003635 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003636 ICS != 0);
3637 if (Fn) {
3638 // Since we're performing this reference-initialization for
3639 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003640 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003641 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003642 return true;
3643
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003644 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003645 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003646
3647 T2 = Fn->getType();
3648 }
3649 }
3650
Douglas Gregor786ab212008-10-29 02:00:59 +00003651 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003652 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003653 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003654 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3655 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003656 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003657 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003658
3659 // Most paths end in a failed conversion.
3660 if (ICS)
3661 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003662
3663 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003664 // A reference to type "cv1 T1" is initialized by an expression
3665 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003666
3667 // -- If the initializer expression
3668
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003669 // Rvalue references cannot bind to lvalues (N2812).
3670 // There is absolutely no situation where they can. In particular, note that
3671 // this is ill-formed, even if B has a user-defined conversion to A&&:
3672 // B b;
3673 // A&& r = b;
3674 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3675 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003676 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003677 << Init->getSourceRange();
3678 return true;
3679 }
3680
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003681 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003682 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3683 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003684 //
3685 // Note that the bit-field check is skipped if we are just computing
3686 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003687 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003688 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003689 BindsDirectly = true;
3690
Douglas Gregor786ab212008-10-29 02:00:59 +00003691 if (ICS) {
3692 // C++ [over.ics.ref]p1:
3693 // When a parameter of reference type binds directly (8.5.3)
3694 // to an argument expression, the implicit conversion sequence
3695 // is the identity conversion, unless the argument expression
3696 // has a type that is a derived class of the parameter type,
3697 // in which case the implicit conversion sequence is a
3698 // derived-to-base Conversion (13.3.3.1).
3699 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3700 ICS->Standard.First = ICK_Identity;
3701 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3702 ICS->Standard.Third = ICK_Identity;
3703 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3704 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003705 ICS->Standard.ReferenceBinding = true;
3706 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003707 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003708 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003709
3710 // Nothing more to do: the inaccessibility/ambiguity check for
3711 // derived-to-base conversions is suppressed when we're
3712 // computing the implicit conversion sequence (C++
3713 // [over.best.ics]p2).
3714 return false;
3715 } else {
3716 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003717 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3718 if (DerivedToBase)
3719 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003720 else if(CheckExceptionSpecCompatibility(Init, T1))
3721 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003722 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003723 }
3724 }
3725
3726 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003727 // implicitly converted to an lvalue of type "cv3 T3,"
3728 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003729 // 92) (this conversion is selected by enumerating the
3730 // applicable conversion functions (13.3.1.6) and choosing
3731 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003732 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003733 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003734 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003735 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003736
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003737 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003738 OverloadedFunctionDecl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003739 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003740 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003741 = Conversions->function_begin();
3742 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003743 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003744 = dyn_cast<FunctionTemplateDecl>(*Func);
3745 CXXConversionDecl *Conv;
3746 if (ConvTemplate)
3747 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3748 else
3749 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003750
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003751 // If the conversion function doesn't return a reference type,
3752 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003753 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003754 (AllowExplicit || !Conv->isExplicit())) {
3755 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003756 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003757 CandidateSet);
3758 else
3759 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3760 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003761 }
3762
3763 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003764 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003765 case OR_Success:
3766 // This is a direct binding.
3767 BindsDirectly = true;
3768
3769 if (ICS) {
3770 // C++ [over.ics.ref]p1:
3771 //
3772 // [...] If the parameter binds directly to the result of
3773 // applying a conversion function to the argument
3774 // expression, the implicit conversion sequence is a
3775 // user-defined conversion sequence (13.3.3.1.2), with the
3776 // second standard conversion sequence either an identity
3777 // conversion or, if the conversion function returns an
3778 // entity of a type that is a derived class of the parameter
3779 // type, a derived-to-base Conversion.
3780 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3781 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3782 ICS->UserDefined.After = Best->FinalConversion;
3783 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003784 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003785 assert(ICS->UserDefined.After.ReferenceBinding &&
3786 ICS->UserDefined.After.DirectBinding &&
3787 "Expected a direct reference binding!");
3788 return false;
3789 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003790 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003791 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003792 CastExpr::CK_UserDefinedConversion,
3793 cast<CXXMethodDecl>(Best->Function),
3794 Owned(Init));
3795 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003796
3797 if (CheckExceptionSpecCompatibility(Init, T1))
3798 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003799 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3800 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003801 }
3802 break;
3803
3804 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003805 if (ICS) {
3806 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3807 Cand != CandidateSet.end(); ++Cand)
3808 if (Cand->Viable)
3809 ICS->ConversionFunctionSet.push_back(Cand->Function);
3810 break;
3811 }
3812 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3813 << Init->getSourceRange();
3814 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003815 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003816
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003817 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003818 case OR_Deleted:
3819 // There was no suitable conversion, or we found a deleted
3820 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003821 break;
3822 }
3823 }
Mike Stump11289f42009-09-09 15:08:12 +00003824
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003825 if (BindsDirectly) {
3826 // C++ [dcl.init.ref]p4:
3827 // [...] In all cases where the reference-related or
3828 // reference-compatible relationship of two types is used to
3829 // establish the validity of a reference binding, and T1 is a
3830 // base class of T2, a program that necessitates such a binding
3831 // is ill-formed if T1 is an inaccessible (clause 11) or
3832 // ambiguous (10.2) base class of T2.
3833 //
3834 // Note that we only check this condition when we're allowed to
3835 // complain about errors, because we should not be checking for
3836 // ambiguity (or inaccessibility) unless the reference binding
3837 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003838 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003839 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor786ab212008-10-29 02:00:59 +00003840 Init->getSourceRange());
3841 else
3842 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003843 }
3844
3845 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003846 // type (i.e., cv1 shall be const), or the reference shall be an
3847 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003848 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003849 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003850 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003851 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3852 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003853 return true;
3854 }
3855
3856 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003857 // class type, and "cv1 T1" is reference-compatible with
3858 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003859 // following ways (the choice is implementation-defined):
3860 //
3861 // -- The reference is bound to the object represented by
3862 // the rvalue (see 3.10) or to a sub-object within that
3863 // object.
3864 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003865 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003866 // a constructor is called to copy the entire rvalue
3867 // object into the temporary. The reference is bound to
3868 // the temporary or to a sub-object within the
3869 // temporary.
3870 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003871 // The constructor that would be used to make the copy
3872 // shall be callable whether or not the copy is actually
3873 // done.
3874 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003875 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003876 // freedom, so we will always take the first option and never build
3877 // a temporary in this case. FIXME: We will, however, have to check
3878 // for the presence of a copy constructor in C++98/03 mode.
3879 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003880 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3881 if (ICS) {
3882 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3883 ICS->Standard.First = ICK_Identity;
3884 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3885 ICS->Standard.Third = ICK_Identity;
3886 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3887 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003888 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003889 ICS->Standard.DirectBinding = false;
3890 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003891 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003892 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003893 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3894 if (DerivedToBase)
3895 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003896 else if(CheckExceptionSpecCompatibility(Init, T1))
3897 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003898 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003899 }
3900 return false;
3901 }
3902
Eli Friedman44b83ee2009-08-05 19:21:58 +00003903 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003904 // initialized from the initializer expression using the
3905 // rules for a non-reference copy initialization (8.5). The
3906 // reference is then bound to the temporary. If T1 is
3907 // reference-related to T2, cv1 must be the same
3908 // cv-qualification as, or greater cv-qualification than,
3909 // cv2; otherwise, the program is ill-formed.
3910 if (RefRelationship == Ref_Related) {
3911 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3912 // we would be reference-compatible or reference-compatible with
3913 // added qualification. But that wasn't the case, so the reference
3914 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003915 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003916 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003917 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3918 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003919 return true;
3920 }
3921
Douglas Gregor576e98c2009-01-30 23:27:23 +00003922 // If at least one of the types is a class type, the types are not
3923 // related, and we aren't allowed any user conversions, the
3924 // reference binding fails. This case is important for breaking
3925 // recursion, since TryImplicitConversion below will attempt to
3926 // create a temporary through the use of a copy constructor.
3927 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3928 (T1->isRecordType() || T2->isRecordType())) {
3929 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003930 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00003931 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3932 return true;
3933 }
3934
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003935 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00003936 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003937 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003938 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003939 // When a parameter of reference type is not bound directly to
3940 // an argument expression, the conversion sequence is the one
3941 // required to convert the argument expression to the
3942 // underlying type of the reference according to
3943 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3944 // to copy-initializing a temporary of the underlying type with
3945 // the argument expression. Any difference in top-level
3946 // cv-qualification is subsumed by the initialization itself
3947 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00003948 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3949 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00003950 /*ForceRValue=*/false,
3951 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003952
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003953 // Of course, that's still a reference binding.
3954 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3955 ICS->Standard.ReferenceBinding = true;
3956 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00003957 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003958 ImplicitConversionSequence::UserDefinedConversion) {
3959 ICS->UserDefined.After.ReferenceBinding = true;
3960 ICS->UserDefined.After.RRefBinding = isRValRef;
3961 }
Douglas Gregor786ab212008-10-29 02:00:59 +00003962 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3963 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003964 ImplicitConversionSequence Conversions;
3965 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3966 false, false,
3967 Conversions);
3968 if (badConversion) {
3969 if ((Conversions.ConversionKind ==
3970 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00003971 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00003972 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003973 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3974 for (int j = Conversions.ConversionFunctionSet.size()-1;
3975 j >= 0; j--) {
3976 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3977 Diag(Func->getLocation(), diag::err_ovl_candidate);
3978 }
3979 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00003980 else {
3981 if (isRValRef)
3982 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3983 << Init->getSourceRange();
3984 else
3985 Diag(DeclLoc, diag::err_invalid_initialization)
3986 << DeclType << Init->getType() << Init->getSourceRange();
3987 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003988 }
3989 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00003990 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003991}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003992
3993/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3994/// of this overloaded operator is well-formed. If so, returns false;
3995/// otherwise, emits appropriate diagnostics and returns true.
3996bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00003997 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003998 "Expected an overloaded operator declaration");
3999
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004000 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4001
Mike Stump11289f42009-09-09 15:08:12 +00004002 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004003 // The allocation and deallocation functions, operator new,
4004 // operator new[], operator delete and operator delete[], are
4005 // described completely in 3.7.3. The attributes and restrictions
4006 // found in the rest of this subclause do not apply to them unless
4007 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004008 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004009 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004010 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004011
4012 if (Op == OO_New || Op == OO_Array_New) {
4013 bool ret = false;
4014 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4015 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4016 QualType T = Context.getCanonicalType((*Param)->getType());
4017 if (!T->isDependentType() && SizeTy != T) {
4018 Diag(FnDecl->getLocation(),
4019 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4020 << SizeTy;
4021 ret = true;
4022 }
4023 }
4024 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4025 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4026 return Diag(FnDecl->getLocation(),
4027 diag::err_operator_new_result_type) << FnDecl->getDeclName()
4028 << Context.VoidPtrTy;
4029 return ret;
4030 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004031
4032 // C++ [over.oper]p6:
4033 // An operator function shall either be a non-static member
4034 // function or be a non-member function and have at least one
4035 // parameter whose type is a class, a reference to a class, an
4036 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004037 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4038 if (MethodDecl->isStatic())
4039 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004040 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004041 } else {
4042 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004043 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4044 ParamEnd = FnDecl->param_end();
4045 Param != ParamEnd; ++Param) {
4046 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004047 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4048 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004049 ClassOrEnumParam = true;
4050 break;
4051 }
4052 }
4053
Douglas Gregord69246b2008-11-17 16:14:12 +00004054 if (!ClassOrEnumParam)
4055 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004056 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004057 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004058 }
4059
4060 // C++ [over.oper]p8:
4061 // An operator function cannot have default arguments (8.3.6),
4062 // except where explicitly stated below.
4063 //
Mike Stump11289f42009-09-09 15:08:12 +00004064 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004065 // (C++ [over.call]p1).
4066 if (Op != OO_Call) {
4067 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4068 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004069 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004070 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004071 diag::err_operator_overload_default_arg)
4072 << FnDecl->getDeclName();
4073 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004074 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004075 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004076 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004077 }
4078 }
4079
Douglas Gregor6cf08062008-11-10 13:38:07 +00004080 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4081 { false, false, false }
4082#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4083 , { Unary, Binary, MemberOnly }
4084#include "clang/Basic/OperatorKinds.def"
4085 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004086
Douglas Gregor6cf08062008-11-10 13:38:07 +00004087 bool CanBeUnaryOperator = OperatorUses[Op][0];
4088 bool CanBeBinaryOperator = OperatorUses[Op][1];
4089 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004090
4091 // C++ [over.oper]p8:
4092 // [...] Operator functions cannot have more or fewer parameters
4093 // than the number required for the corresponding operator, as
4094 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004095 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004096 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004097 if (Op != OO_Call &&
4098 ((NumParams == 1 && !CanBeUnaryOperator) ||
4099 (NumParams == 2 && !CanBeBinaryOperator) ||
4100 (NumParams < 1) || (NumParams > 2))) {
4101 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004102 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004103 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004104 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004105 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004106 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004107 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004108 assert(CanBeBinaryOperator &&
4109 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004110 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004111 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004112
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004113 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004114 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004115 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004116
Douglas Gregord69246b2008-11-17 16:14:12 +00004117 // Overloaded operators other than operator() cannot be variadic.
4118 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004119 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004120 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004121 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004122 }
4123
4124 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004125 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4126 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004127 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004128 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004129 }
4130
4131 // C++ [over.inc]p1:
4132 // The user-defined function called operator++ implements the
4133 // prefix and postfix ++ operator. If this function is a member
4134 // function with no parameters, or a non-member function with one
4135 // parameter of class or enumeration type, it defines the prefix
4136 // increment operator ++ for objects of that type. If the function
4137 // is a member function with one parameter (which shall be of type
4138 // int) or a non-member function with two parameters (the second
4139 // of which shall be of type int), it defines the postfix
4140 // increment operator ++ for objects of that type.
4141 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4142 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4143 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004144 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004145 ParamIsInt = BT->getKind() == BuiltinType::Int;
4146
Chris Lattner2b786902008-11-21 07:50:02 +00004147 if (!ParamIsInt)
4148 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004149 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004150 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004151 }
4152
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004153 // Notify the class if it got an assignment operator.
4154 if (Op == OO_Equal) {
4155 // Would have returned earlier otherwise.
4156 assert(isa<CXXMethodDecl>(FnDecl) &&
4157 "Overloaded = not member, but not filtered.");
4158 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4159 Method->getParent()->addedAssignmentOperator(Context, Method);
4160 }
4161
Douglas Gregord69246b2008-11-17 16:14:12 +00004162 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004163}
Chris Lattner3b024a32008-12-17 07:09:26 +00004164
Douglas Gregor07665a62009-01-05 19:45:36 +00004165/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4166/// linkage specification, including the language and (if present)
4167/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4168/// the location of the language string literal, which is provided
4169/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4170/// the '{' brace. Otherwise, this linkage specification does not
4171/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004172Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4173 SourceLocation ExternLoc,
4174 SourceLocation LangLoc,
4175 const char *Lang,
4176 unsigned StrSize,
4177 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004178 LinkageSpecDecl::LanguageIDs Language;
4179 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4180 Language = LinkageSpecDecl::lang_c;
4181 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4182 Language = LinkageSpecDecl::lang_cxx;
4183 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004184 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004185 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004186 }
Mike Stump11289f42009-09-09 15:08:12 +00004187
Chris Lattner438e5012008-12-17 07:13:27 +00004188 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004189
Douglas Gregor07665a62009-01-05 19:45:36 +00004190 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004191 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004192 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004193 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004194 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004195 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004196}
4197
Douglas Gregor07665a62009-01-05 19:45:36 +00004198/// ActOnFinishLinkageSpecification - Completely the definition of
4199/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4200/// valid, it's the position of the closing '}' brace in a linkage
4201/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004202Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4203 DeclPtrTy LinkageSpec,
4204 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004205 if (LinkageSpec)
4206 PopDeclContext();
4207 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004208}
4209
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004210/// \brief Perform semantic analysis for the variable declaration that
4211/// occurs within a C++ catch clause, returning the newly-created
4212/// variable.
4213VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004214 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004215 IdentifierInfo *Name,
4216 SourceLocation Loc,
4217 SourceRange Range) {
4218 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004219
4220 // Arrays and functions decay.
4221 if (ExDeclType->isArrayType())
4222 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4223 else if (ExDeclType->isFunctionType())
4224 ExDeclType = Context.getPointerType(ExDeclType);
4225
4226 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4227 // The exception-declaration shall not denote a pointer or reference to an
4228 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004229 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004230 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004231 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004232 Invalid = true;
4233 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004234
Sebastian Redl54c04d42008-12-22 19:15:10 +00004235 QualType BaseType = ExDeclType;
4236 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004237 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004238 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004239 BaseType = Ptr->getPointeeType();
4240 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004241 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004242 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004243 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004244 BaseType = Ref->getPointeeType();
4245 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004246 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004247 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004248 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004249 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004250 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004251
Mike Stump11289f42009-09-09 15:08:12 +00004252 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004253 RequireNonAbstractType(Loc, ExDeclType,
4254 diag::err_abstract_type_in_decl,
4255 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004256 Invalid = true;
4257
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004258 // FIXME: Need to test for ability to copy-construct and destroy the
4259 // exception variable.
4260
Sebastian Redl9b244a82008-12-22 21:35:02 +00004261 // FIXME: Need to check for abstract classes.
4262
Mike Stump11289f42009-09-09 15:08:12 +00004263 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004264 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004265
4266 if (Invalid)
4267 ExDecl->setInvalidDecl();
4268
4269 return ExDecl;
4270}
4271
4272/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4273/// handler.
4274Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004275 DeclaratorInfo *DInfo = 0;
4276 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004277
4278 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004279 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004280 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004281 // The scope should be freshly made just for us. There is just no way
4282 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004283 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004284 if (PrevDecl->isTemplateParameter()) {
4285 // Maybe we will complain about the shadowed template parameter.
4286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004287 }
4288 }
4289
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004290 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004291 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4292 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004293 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004294 }
4295
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004296 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004297 D.getIdentifier(),
4298 D.getIdentifierLoc(),
4299 D.getDeclSpec().getSourceRange());
4300
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004301 if (Invalid)
4302 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004303
Sebastian Redl54c04d42008-12-22 19:15:10 +00004304 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004305 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004306 PushOnScopeChains(ExDecl, S);
4307 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004308 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004309
Douglas Gregor758a8692009-06-17 21:51:59 +00004310 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004311 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004312}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004313
Mike Stump11289f42009-09-09 15:08:12 +00004314Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004315 ExprArg assertexpr,
4316 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004317 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004318 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004319 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4320
Anders Carlsson54b26982009-03-14 00:33:21 +00004321 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4322 llvm::APSInt Value(32);
4323 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4324 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4325 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004326 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004327 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004328
Anders Carlsson54b26982009-03-14 00:33:21 +00004329 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004330 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004331 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004332 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004333 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004334 }
4335 }
Mike Stump11289f42009-09-09 15:08:12 +00004336
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004337 assertexpr.release();
4338 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004339 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004340 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004341
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004342 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004343 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004344}
Sebastian Redlf769df52009-03-24 22:27:57 +00004345
John McCall11083da2009-09-16 22:47:08 +00004346/// Handle a friend type declaration. This works in tandem with
4347/// ActOnTag.
4348///
4349/// Notes on friend class templates:
4350///
4351/// We generally treat friend class declarations as if they were
4352/// declaring a class. So, for example, the elaborated type specifier
4353/// in a friend declaration is required to obey the restrictions of a
4354/// class-head (i.e. no typedefs in the scope chain), template
4355/// parameters are required to match up with simple template-ids, &c.
4356/// However, unlike when declaring a template specialization, it's
4357/// okay to refer to a template specialization without an empty
4358/// template parameter declaration, e.g.
4359/// friend class A<T>::B<unsigned>;
4360/// We permit this as a special case; if there are any template
4361/// parameters present at all, require proper matching, i.e.
4362/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004363Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004364 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004365 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004366
4367 assert(DS.isFriendSpecified());
4368 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4369
John McCall11083da2009-09-16 22:47:08 +00004370 // Try to convert the decl specifier to a type. This works for
4371 // friend templates because ActOnTag never produces a ClassTemplateDecl
4372 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004373 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004374 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4375 if (TheDeclarator.isInvalidType())
4376 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004377
John McCall11083da2009-09-16 22:47:08 +00004378 // This is definitely an error in C++98. It's probably meant to
4379 // be forbidden in C++0x, too, but the specification is just
4380 // poorly written.
4381 //
4382 // The problem is with declarations like the following:
4383 // template <T> friend A<T>::foo;
4384 // where deciding whether a class C is a friend or not now hinges
4385 // on whether there exists an instantiation of A that causes
4386 // 'foo' to equal C. There are restrictions on class-heads
4387 // (which we declare (by fiat) elaborated friend declarations to
4388 // be) that makes this tractable.
4389 //
4390 // FIXME: handle "template <> friend class A<T>;", which
4391 // is possibly well-formed? Who even knows?
4392 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4393 Diag(Loc, diag::err_tagless_friend_type_template)
4394 << DS.getSourceRange();
4395 return DeclPtrTy();
4396 }
4397
John McCallaa74a0c2009-08-28 07:59:38 +00004398 // C++ [class.friend]p2:
4399 // An elaborated-type-specifier shall be used in a friend declaration
4400 // for a class.*
4401 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004402 // This is one of the rare places in Clang where it's legitimate to
4403 // ask about the "spelling" of the type.
4404 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4405 // If we evaluated the type to a record type, suggest putting
4406 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004407 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004408 RecordDecl *RD = RT->getDecl();
4409
4410 std::string InsertionText = std::string(" ") + RD->getKindName();
4411
John McCallc3987482009-10-07 23:34:25 +00004412 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4413 << (unsigned) RD->getTagKind()
4414 << T
4415 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004416 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4417 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004418 return DeclPtrTy();
4419 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004420 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4421 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004422 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004423 }
4424 }
4425
John McCallc3987482009-10-07 23:34:25 +00004426 // Enum types cannot be friends.
4427 if (T->getAs<EnumType>()) {
4428 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4429 << SourceRange(DS.getFriendSpecLoc());
4430 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004431 }
John McCallaa74a0c2009-08-28 07:59:38 +00004432
John McCallaa74a0c2009-08-28 07:59:38 +00004433 // C++98 [class.friend]p1: A friend of a class is a function
4434 // or class that is not a member of the class . . .
4435 // But that's a silly restriction which nobody implements for
4436 // inner classes, and C++0x removes it anyway, so we only report
4437 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004438 if (!getLangOptions().CPlusPlus0x)
4439 if (const RecordType *RT = T->getAs<RecordType>())
4440 if (RT->getDecl()->getDeclContext() == CurContext)
4441 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004442
John McCall11083da2009-09-16 22:47:08 +00004443 Decl *D;
4444 if (TempParams.size())
4445 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4446 TempParams.size(),
4447 (TemplateParameterList**) TempParams.release(),
4448 T.getTypePtr(),
4449 DS.getFriendSpecLoc());
4450 else
4451 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4452 DS.getFriendSpecLoc());
4453 D->setAccess(AS_public);
4454 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004455
John McCall11083da2009-09-16 22:47:08 +00004456 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004457}
4458
John McCall2f212b32009-09-11 21:02:39 +00004459Sema::DeclPtrTy
4460Sema::ActOnFriendFunctionDecl(Scope *S,
4461 Declarator &D,
4462 bool IsDefinition,
4463 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004464 const DeclSpec &DS = D.getDeclSpec();
4465
4466 assert(DS.isFriendSpecified());
4467 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4468
4469 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004470 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004471 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004472
4473 // C++ [class.friend]p1
4474 // A friend of a class is a function or class....
4475 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004476 // It *doesn't* see through dependent types, which is correct
4477 // according to [temp.arg.type]p3:
4478 // If a declaration acquires a function type through a
4479 // type dependent on a template-parameter and this causes
4480 // a declaration that does not use the syntactic form of a
4481 // function declarator to have a function type, the program
4482 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004483 if (!T->isFunctionType()) {
4484 Diag(Loc, diag::err_unexpected_friend);
4485
4486 // It might be worthwhile to try to recover by creating an
4487 // appropriate declaration.
4488 return DeclPtrTy();
4489 }
4490
4491 // C++ [namespace.memdef]p3
4492 // - If a friend declaration in a non-local class first declares a
4493 // class or function, the friend class or function is a member
4494 // of the innermost enclosing namespace.
4495 // - The name of the friend is not found by simple name lookup
4496 // until a matching declaration is provided in that namespace
4497 // scope (either before or after the class declaration granting
4498 // friendship).
4499 // - If a friend function is called, its name may be found by the
4500 // name lookup that considers functions from namespaces and
4501 // classes associated with the types of the function arguments.
4502 // - When looking for a prior declaration of a class or a function
4503 // declared as a friend, scopes outside the innermost enclosing
4504 // namespace scope are not considered.
4505
John McCallaa74a0c2009-08-28 07:59:38 +00004506 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4507 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004508 assert(Name);
4509
John McCall07e91c02009-08-06 02:15:43 +00004510 // The context we found the declaration in, or in which we should
4511 // create the declaration.
4512 DeclContext *DC;
4513
4514 // FIXME: handle local classes
4515
4516 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004517 NamedDecl *PrevDecl = 0;
John McCall07e91c02009-08-06 02:15:43 +00004518 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004519 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004520 DC = computeDeclContext(ScopeQual);
4521
4522 // FIXME: handle dependent contexts
4523 if (!DC) return DeclPtrTy();
4524
John McCall9f3059a2009-10-09 21:13:30 +00004525 LookupResult R;
4526 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4527 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004528
4529 // If searching in that context implicitly found a declaration in
4530 // a different context, treat it like it wasn't found at all.
4531 // TODO: better diagnostics for this case. Suggesting the right
4532 // qualified scope would be nice...
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004533 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004534 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004535 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4536 return DeclPtrTy();
4537 }
4538
4539 // C++ [class.friend]p1: A friend of a class is a function or
4540 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004541 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4543
John McCall07e91c02009-08-06 02:15:43 +00004544 // Otherwise walk out to the nearest namespace scope looking for matches.
4545 } else {
4546 // TODO: handle local class contexts.
4547
4548 DC = CurContext;
4549 while (true) {
4550 // Skip class contexts. If someone can cite chapter and verse
4551 // for this behavior, that would be nice --- it's what GCC and
4552 // EDG do, and it seems like a reasonable intent, but the spec
4553 // really only says that checks for unqualified existing
4554 // declarations should stop at the nearest enclosing namespace,
4555 // not that they should only consider the nearest enclosing
4556 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004557 while (DC->isRecord())
4558 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004559
John McCall9f3059a2009-10-09 21:13:30 +00004560 LookupResult R;
4561 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4562 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004563
4564 // TODO: decide what we think about using declarations.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004565 if (PrevDecl)
John McCall07e91c02009-08-06 02:15:43 +00004566 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004567
John McCall07e91c02009-08-06 02:15:43 +00004568 if (DC->isFileContext()) break;
4569 DC = DC->getParent();
4570 }
4571
4572 // C++ [class.friend]p1: A friend of a class is a function or
4573 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004574 // C++0x changes this for both friend types and functions.
4575 // Most C++ 98 compilers do seem to give an error here, so
4576 // we do, too.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004577 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004578 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4579 }
4580
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004581 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004582 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004583 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4584 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4585 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004586 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004587 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4588 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004589 return DeclPtrTy();
4590 }
John McCall07e91c02009-08-06 02:15:43 +00004591 }
4592
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004593 bool Redeclaration = false;
4594 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004595 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004596 IsDefinition,
4597 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004598 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004599
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004600 assert(ND->getDeclContext() == DC);
4601 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004602
John McCall759e32b2009-08-31 22:39:49 +00004603 // Add the function declaration to the appropriate lookup tables,
4604 // adjusting the redeclarations list as necessary. We don't
4605 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004606 //
John McCall759e32b2009-08-31 22:39:49 +00004607 // Also update the scope-based lookup if the target context's
4608 // lookup context is in lexical scope.
4609 if (!CurContext->isDependentContext()) {
4610 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004611 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004612 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004613 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004614 }
John McCallaa74a0c2009-08-28 07:59:38 +00004615
4616 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004617 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004618 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004619 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004620 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004621
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004622 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004623}
4624
Chris Lattner83f095c2009-03-28 19:18:32 +00004625void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004626 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004627
Chris Lattner83f095c2009-03-28 19:18:32 +00004628 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004629 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4630 if (!Fn) {
4631 Diag(DelLoc, diag::err_deleted_non_function);
4632 return;
4633 }
4634 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4635 Diag(DelLoc, diag::err_deleted_decl_not_first);
4636 Diag(Prev->getLocation(), diag::note_previous_declaration);
4637 // If the declaration wasn't the first, we delete the function anyway for
4638 // recovery.
4639 }
4640 Fn->setDeleted();
4641}
Sebastian Redl4c018662009-04-27 21:33:24 +00004642
4643static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4644 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4645 ++CI) {
4646 Stmt *SubStmt = *CI;
4647 if (!SubStmt)
4648 continue;
4649 if (isa<ReturnStmt>(SubStmt))
4650 Self.Diag(SubStmt->getSourceRange().getBegin(),
4651 diag::err_return_in_constructor_handler);
4652 if (!isa<Expr>(SubStmt))
4653 SearchForReturnInStmt(Self, SubStmt);
4654 }
4655}
4656
4657void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4658 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4659 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4660 SearchForReturnInStmt(*this, Handler);
4661 }
4662}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004663
Mike Stump11289f42009-09-09 15:08:12 +00004664bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004665 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004666 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4667 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004668
4669 QualType CNewTy = Context.getCanonicalType(NewTy);
4670 QualType COldTy = Context.getCanonicalType(OldTy);
4671
Mike Stump11289f42009-09-09 15:08:12 +00004672 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004673 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4674 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004675
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004676 // Check if the return types are covariant
4677 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004678
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004679 /// Both types must be pointers or references to classes.
4680 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4681 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4682 NewClassTy = NewPT->getPointeeType();
4683 OldClassTy = OldPT->getPointeeType();
4684 }
4685 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4686 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4687 NewClassTy = NewRT->getPointeeType();
4688 OldClassTy = OldRT->getPointeeType();
4689 }
4690 }
Mike Stump11289f42009-09-09 15:08:12 +00004691
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004692 // The return types aren't either both pointers or references to a class type.
4693 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004694 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004695 diag::err_different_return_type_for_overriding_virtual_function)
4696 << New->getDeclName() << NewTy << OldTy;
4697 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004698
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004699 return true;
4700 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004701
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004702 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4703 // Check if the new class derives from the old class.
4704 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4705 Diag(New->getLocation(),
4706 diag::err_covariant_return_not_derived)
4707 << New->getDeclName() << NewTy << OldTy;
4708 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4709 return true;
4710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004712 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004713 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004714 diag::err_covariant_return_inaccessible_base,
4715 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4716 // FIXME: Should this point to the return type?
4717 New->getLocation(), SourceRange(), New->getDeclName())) {
4718 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4719 return true;
4720 }
4721 }
Mike Stump11289f42009-09-09 15:08:12 +00004722
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004723 // The qualifiers of the return types must be the same.
4724 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4725 Diag(New->getLocation(),
4726 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004727 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004728 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4729 return true;
4730 };
Mike Stump11289f42009-09-09 15:08:12 +00004731
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004732
4733 // The new class type must have the same or less qualifiers as the old type.
4734 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4735 Diag(New->getLocation(),
4736 diag::err_covariant_return_type_class_type_more_qualified)
4737 << New->getDeclName() << NewTy << OldTy;
4738 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4739 return true;
4740 };
Mike Stump11289f42009-09-09 15:08:12 +00004741
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004742 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004743}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004744
4745/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4746/// initializer for the declaration 'Dcl'.
4747/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4748/// static data member of class X, names should be looked up in the scope of
4749/// class X.
4750void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004751 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004752
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004753 Decl *D = Dcl.getAs<Decl>();
4754 // If there is no declaration, there was an error parsing it.
4755 if (D == 0)
4756 return;
4757
4758 // Check whether it is a declaration with a nested name specifier like
4759 // int foo::bar;
4760 if (!D->isOutOfLine())
4761 return;
Mike Stump11289f42009-09-09 15:08:12 +00004762
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004763 // C++ [basic.lookup.unqual]p13
4764 //
4765 // A name used in the definition of a static data member of class X
4766 // (after the qualified-id of the static member) is looked up as if the name
4767 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004768
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004769 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004770 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004771}
4772
4773/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4774/// initializer for the declaration 'Dcl'.
4775void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004776 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004777
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004778 Decl *D = Dcl.getAs<Decl>();
4779 // If there is no declaration, there was an error parsing it.
4780 if (D == 0)
4781 return;
4782
4783 // Check whether it is a declaration with a nested name specifier like
4784 // int foo::bar;
4785 if (!D->isOutOfLine())
4786 return;
4787
4788 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004789 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004790}