blob: 4db769bd91a8d207c44fcca05cc6ca741a3ff768 [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"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonf98849e2009-12-02 17:15:43 +000018#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000021#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000023#include "clang/Parse/DeclSpec.h"
24#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000025#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000026#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000027#include "llvm/ADT/STLExtras.h"
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.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000043 class 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(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000356 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000357 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000358
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000359 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000360}
361
362/// CheckCXXDefaultArguments - Verify that the default arguments for a
363/// function declaration are well-formed according to C++
364/// [dcl.fct.default].
365void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
366 unsigned NumParams = FD->getNumParams();
367 unsigned p;
368
369 // Find first parameter with a default argument
370 for (p = 0; p < NumParams; ++p) {
371 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000372 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000373 break;
374 }
375
376 // C++ [dcl.fct.default]p4:
377 // In a given function declaration, all parameters
378 // subsequent to a parameter with a default argument shall
379 // have default arguments supplied in this or previous
380 // declarations. A default argument shall not be redefined
381 // by a later declaration (not even to the same value).
382 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000383 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000384 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000385 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 if (Param->isInvalidDecl())
387 /* We already complained about this parameter. */;
388 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000389 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000390 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000391 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000392 else
Mike Stump11289f42009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000394 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000395
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 LastMissingDefaultArg = p;
397 }
398 }
399
400 if (LastMissingDefaultArg > 0) {
401 // Some default arguments were missing. Clear out all of the
402 // default arguments up to (and including) the last missing
403 // default argument, so that we leave the function parameters
404 // in a semantically valid state.
405 for (p = 0; p <= LastMissingDefaultArg; ++p) {
406 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000407 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000408 if (!Param->hasUnparsedDefaultArg())
409 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000410 Param->setDefaultArg(0);
411 }
412 }
413 }
414}
Douglas Gregor556877c2008-04-13 21:30:24 +0000415
Douglas Gregor61956c42008-10-31 09:07:45 +0000416/// isCurrentClassName - Determine whether the identifier II is the
417/// name of the class type currently being defined. In the case of
418/// nested classes, this will only return true if II is the name of
419/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000420bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
421 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000422 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000423 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000424 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000425 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
426 } else
427 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
428
429 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000430 return &II == CurDecl->getIdentifier();
431 else
432 return false;
433}
434
Mike Stump11289f42009-09-09 15:08:12 +0000435/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000436///
437/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
438/// and returns NULL otherwise.
439CXXBaseSpecifier *
440Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
441 SourceRange SpecifierRange,
442 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000443 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000444 SourceLocation BaseLoc) {
445 // C++ [class.union]p1:
446 // A union shall not have base classes.
447 if (Class->isUnion()) {
448 Diag(Class->getLocation(), diag::err_base_clause_on_union)
449 << SpecifierRange;
450 return 0;
451 }
452
453 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000454 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000455 Class->getTagKind() == RecordDecl::TK_class,
456 Access, BaseType);
457
458 // Base specifiers must be record types.
459 if (!BaseType->isRecordType()) {
460 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
461 return 0;
462 }
463
464 // C++ [class.union]p1:
465 // A union shall not be used as a base class.
466 if (BaseType->isUnionType()) {
467 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.derived]p2:
472 // The class-name in a base-specifier shall not be an incompletely
473 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000474 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000475 PDiag(diag::err_incomplete_base_class)
476 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000477 return 0;
478
Eli Friedmanc96d4962009-08-15 21:55:26 +0000479 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000480 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000481 assert(BaseDecl && "Record type has no declaration");
482 BaseDecl = BaseDecl->getDefinition(Context);
483 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000484 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
485 assert(CXXBaseDecl && "Base type is not a C++ type");
486 if (!CXXBaseDecl->isEmpty())
487 Class->setEmpty(false);
488 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000489 Class->setPolymorphic(true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000490 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
491 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
492 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000493 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
494 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000495 return 0;
496 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000497
498 // C++ [dcl.init.aggr]p1:
499 // An aggregate is [...] a class with [...] no base classes [...].
500 Class->setAggregate(false);
501 Class->setPOD(false);
502
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000503 if (Virtual) {
504 // C++ [class.ctor]p5:
505 // A constructor is trivial if its class has no virtual base classes.
506 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000507
508 // C++ [class.copy]p6:
509 // A copy constructor is trivial if its class has no virtual base classes.
510 Class->setHasTrivialCopyConstructor(false);
511
512 // C++ [class.copy]p11:
513 // A copy assignment operator is trivial if its class has no virtual
514 // base classes.
515 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000516
517 // C++0x [meta.unary.prop] is_empty:
518 // T is a class type, but not a union type, with ... no virtual base
519 // classes
520 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000521 } else {
522 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000523 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000524 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000525 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
526 Class->setHasTrivialConstructor(false);
527
528 // C++ [class.copy]p6:
529 // A copy constructor is trivial if all the direct base classes of its
530 // class have trivial copy constructors.
531 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
532 Class->setHasTrivialCopyConstructor(false);
533
534 // C++ [class.copy]p11:
535 // A copy assignment operator is trivial if all the direct base classes
536 // of its class have trivial copy assignment operators.
537 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
538 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000539 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000540
541 // C++ [class.ctor]p3:
542 // A destructor is trivial if all the direct base classes of its class
543 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000544 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
545 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregor463421d2009-03-03 04:44:36 +0000547 // Create the base specifier.
548 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000549 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
550 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000551 Access, BaseType);
552}
553
Douglas Gregor556877c2008-04-13 21:30:24 +0000554/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
555/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000556/// example:
557/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000558/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000559Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000560Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000561 bool Virtual, AccessSpecifier Access,
562 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000563 if (!classdecl)
564 return true;
565
Douglas Gregorc40290e2009-03-09 23:48:35 +0000566 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000567 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000568 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000569 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
570 Virtual, Access,
571 BaseType, BaseLoc))
572 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000573
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000575}
Douglas Gregor556877c2008-04-13 21:30:24 +0000576
Douglas Gregor463421d2009-03-03 04:44:36 +0000577/// \brief Performs the actual work of attaching the given base class
578/// specifiers to a C++ class.
579bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
580 unsigned NumBases) {
581 if (NumBases == 0)
582 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000583
584 // Used to keep track of which base types we have already seen, so
585 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000586 // that the key is always the unqualified canonical type of the base
587 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000588 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
589
590 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000591 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000592 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000593 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000594 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000595 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000596 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000597
Douglas Gregor29a92472008-10-22 17:49:05 +0000598 if (KnownBaseTypes[NewBaseType]) {
599 // C++ [class.mi]p3:
600 // A class shall not be specified as a direct base class of a
601 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000602 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000603 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000604 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000605 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000606
607 // Delete the duplicate base class specifier; we're going to
608 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000609 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000610
611 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000612 } else {
613 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000614 KnownBaseTypes[NewBaseType] = Bases[idx];
615 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 }
617 }
618
619 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000620 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000621
622 // Delete the remaining (good) base class specifiers, since their
623 // data has been copied into the CXXRecordDecl.
624 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000625 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000626
627 return Invalid;
628}
629
630/// ActOnBaseSpecifiers - Attach the given base specifiers to the
631/// class, after checking whether there are any duplicate base
632/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000633void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 unsigned NumBases) {
635 if (!ClassDecl || !Bases || !NumBases)
636 return;
637
638 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000639 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000640 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000641}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000642
Douglas Gregor36d1b142009-10-06 17:59:45 +0000643/// \brief Determine whether the type \p Derived is a C++ class that is
644/// derived from the type \p Base.
645bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
646 if (!getLangOptions().CPlusPlus)
647 return false;
648
649 const RecordType *DerivedRT = Derived->getAs<RecordType>();
650 if (!DerivedRT)
651 return false;
652
653 const RecordType *BaseRT = Base->getAs<RecordType>();
654 if (!BaseRT)
655 return false;
656
657 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
658 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
659 return DerivedRD->isDerivedFrom(BaseRD);
660}
661
662/// \brief Determine whether the type \p Derived is a C++ class that is
663/// derived from the type \p Base.
664bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
665 if (!getLangOptions().CPlusPlus)
666 return false;
667
668 const RecordType *DerivedRT = Derived->getAs<RecordType>();
669 if (!DerivedRT)
670 return false;
671
672 const RecordType *BaseRT = Base->getAs<RecordType>();
673 if (!BaseRT)
674 return false;
675
676 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
677 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
678 return DerivedRD->isDerivedFrom(BaseRD, Paths);
679}
680
681/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
682/// conversion (where Derived and Base are class types) is
683/// well-formed, meaning that the conversion is unambiguous (and
684/// that all of the base classes are accessible). Returns true
685/// and emits a diagnostic if the code is ill-formed, returns false
686/// otherwise. Loc is the location where this routine should point to
687/// if there is an error, and Range is the source range to highlight
688/// if there is an error.
689bool
690Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
691 unsigned InaccessibleBaseID,
692 unsigned AmbigiousBaseConvID,
693 SourceLocation Loc, SourceRange Range,
694 DeclarationName Name) {
695 // First, determine whether the path from Derived to Base is
696 // ambiguous. This is slightly more expensive than checking whether
697 // the Derived to Base conversion exists, because here we need to
698 // explore multiple paths to determine if there is an ambiguity.
699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
700 /*DetectVirtual=*/false);
701 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
702 assert(DerivationOkay &&
703 "Can only be used with a derived-to-base conversion");
704 (void)DerivationOkay;
705
706 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000707 if (InaccessibleBaseID == 0)
708 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000709 // Check that the base class can be accessed.
710 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
711 Name);
712 }
713
714 // We know that the derived-to-base conversion is ambiguous, and
715 // we're going to produce a diagnostic. Perform the derived-to-base
716 // search just one more time to compute all of the possible paths so
717 // that we can print them out. This is more expensive than any of
718 // the previous derived-to-base checks we've done, but at this point
719 // performance isn't as much of an issue.
720 Paths.clear();
721 Paths.setRecordingPaths(true);
722 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
723 assert(StillOkay && "Can only be used with a derived-to-base conversion");
724 (void)StillOkay;
725
726 // Build up a textual representation of the ambiguous paths, e.g.,
727 // D -> B -> A, that will be used to illustrate the ambiguous
728 // conversions in the diagnostic. We only print one of the paths
729 // to each base class subobject.
730 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
731
732 Diag(Loc, AmbigiousBaseConvID)
733 << Derived << Base << PathDisplayStr << Range << Name;
734 return true;
735}
736
737bool
738Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000739 SourceLocation Loc, SourceRange Range,
740 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000741 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000742 IgnoreAccess ? 0 :
743 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000744 diag::err_ambiguous_derived_to_base_conv,
745 Loc, Range, DeclarationName());
746}
747
748
749/// @brief Builds a string representing ambiguous paths from a
750/// specific derived class to different subobjects of the same base
751/// class.
752///
753/// This function builds a string that can be used in error messages
754/// to show the different paths that one can take through the
755/// inheritance hierarchy to go from the derived class to different
756/// subobjects of a base class. The result looks something like this:
757/// @code
758/// struct D -> struct B -> struct A
759/// struct D -> struct C -> struct A
760/// @endcode
761std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
762 std::string PathDisplayStr;
763 std::set<unsigned> DisplayedPaths;
764 for (CXXBasePaths::paths_iterator Path = Paths.begin();
765 Path != Paths.end(); ++Path) {
766 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
767 // We haven't displayed a path to this particular base
768 // class subobject yet.
769 PathDisplayStr += "\n ";
770 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
771 for (CXXBasePath::const_iterator Element = Path->begin();
772 Element != Path->end(); ++Element)
773 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
774 }
775 }
776
777 return PathDisplayStr;
778}
779
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000780//===----------------------------------------------------------------------===//
781// C++ class member Handling
782//===----------------------------------------------------------------------===//
783
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000784/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
785/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
786/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000787/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000788Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000789Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000790 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000791 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
792 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000793 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000794 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000795 Expr *BitWidth = static_cast<Expr*>(BW);
796 Expr *Init = static_cast<Expr*>(InitExpr);
797 SourceLocation Loc = D.getIdentifierLoc();
798
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000799 bool isFunc = D.isFunctionDeclarator();
800
John McCall07e91c02009-08-06 02:15:43 +0000801 assert(!DS.isFriendSpecified());
802
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000803 // C++ 9.2p6: A member shall not be declared to have automatic storage
804 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000805 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
806 // data members and cannot be applied to names declared const or static,
807 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000808 switch (DS.getStorageClassSpec()) {
809 case DeclSpec::SCS_unspecified:
810 case DeclSpec::SCS_typedef:
811 case DeclSpec::SCS_static:
812 // FALL THROUGH.
813 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000814 case DeclSpec::SCS_mutable:
815 if (isFunc) {
816 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000817 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000818 else
Chris Lattner3b054132008-11-19 05:08:23 +0000819 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000820
Sebastian Redl8071edb2008-11-17 23:24:37 +0000821 // FIXME: It would be nicer if the keyword was ignored only for this
822 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000823 D.getMutableDeclSpec().ClearStorageClassSpecs();
824 } else {
825 QualType T = GetTypeForDeclarator(D, S);
826 diag::kind err = static_cast<diag::kind>(0);
827 if (T->isReferenceType())
828 err = diag::err_mutable_reference;
829 else if (T.isConstQualified())
830 err = diag::err_mutable_const;
831 if (err != 0) {
832 if (DS.getStorageClassSpecLoc().isValid())
833 Diag(DS.getStorageClassSpecLoc(), err);
834 else
835 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000836 // FIXME: It would be nicer if the keyword was ignored only for this
837 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000838 D.getMutableDeclSpec().ClearStorageClassSpecs();
839 }
840 }
841 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000842 default:
843 if (DS.getStorageClassSpecLoc().isValid())
844 Diag(DS.getStorageClassSpecLoc(),
845 diag::err_storageclass_invalid_for_member);
846 else
847 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
848 D.getMutableDeclSpec().ClearStorageClassSpecs();
849 }
850
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000851 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000852 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000853 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000854 // Check also for this case:
855 //
856 // typedef int f();
857 // f a;
858 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000859 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000860 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000861 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000862
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000863 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
864 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000865 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866
867 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000868 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000869 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000870 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
871 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000872 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000873 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000874 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000875 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000876 if (!Member) {
877 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000878 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000879 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000880
881 // Non-instance-fields can't have a bitfield.
882 if (BitWidth) {
883 if (Member->isInvalidDecl()) {
884 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000885 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000886 // C++ 9.6p3: A bit-field shall not be a static member.
887 // "static member 'A' cannot be a bit-field"
888 Diag(Loc, diag::err_static_not_bitfield)
889 << Name << BitWidth->getSourceRange();
890 } else if (isa<TypedefDecl>(Member)) {
891 // "typedef member 'x' cannot be a bit-field"
892 Diag(Loc, diag::err_typedef_not_bitfield)
893 << Name << BitWidth->getSourceRange();
894 } else {
895 // A function typedef ("typedef int f(); f a;").
896 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
897 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000898 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000899 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000900 }
Mike Stump11289f42009-09-09 15:08:12 +0000901
Chris Lattnerd26760a2009-03-05 23:01:03 +0000902 DeleteExpr(BitWidth);
903 BitWidth = 0;
904 Member->setInvalidDecl();
905 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000906
907 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregor3447e762009-08-20 22:52:58 +0000909 // If we have declared a member function template, set the access of the
910 // templated declaration as well.
911 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
912 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000913 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914
Douglas Gregor92751d42008-11-17 22:58:34 +0000915 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000916
Douglas Gregor0c880302009-03-11 23:00:04 +0000917 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000918 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000919 if (Deleted) // FIXME: Source location is not very good.
920 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000921
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000922 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000923 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000924 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000925 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000926 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000927}
928
Douglas Gregore8381c02008-11-05 04:29:56 +0000929/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000930Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000931Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000932 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000933 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000934 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000935 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000936 SourceLocation IdLoc,
937 SourceLocation LParenLoc,
938 ExprTy **Args, unsigned NumArgs,
939 SourceLocation *CommaLocs,
940 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000941 if (!ConstructorD)
942 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000944 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000945
946 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000947 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000948 if (!Constructor) {
949 // The user wrote a constructor initializer on a function that is
950 // not a C++ constructor. Ignore the error for now, because we may
951 // have more member initializers coming; we'll diagnose it just
952 // once in ActOnMemInitializers.
953 return true;
954 }
955
956 CXXRecordDecl *ClassDecl = Constructor->getParent();
957
958 // C++ [class.base.init]p2:
959 // Names in a mem-initializer-id are looked up in the scope of the
960 // constructor’s class and, if not found in that scope, are looked
961 // up in the scope containing the constructor’s
962 // definition. [Note: if the constructor’s class contains a member
963 // with the same name as a direct or virtual base class of the
964 // class, a mem-initializer-id naming the member or base class and
965 // composed of a single identifier refers to the class member. A
966 // mem-initializer-id for the hidden base class may be specified
967 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000968 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000969 // Look for a member, first.
970 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000971 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000972 = ClassDecl->lookup(MemberOrBase);
973 if (Result.first != Result.second)
974 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000975
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000976 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000977
Eli Friedman8e1433b2009-07-29 19:44:27 +0000978 if (Member)
979 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
980 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000981 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000982 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000983 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000984 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000985 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000986 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
987 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000988
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000989 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000990
Eli Friedman8e1433b2009-07-29 19:44:27 +0000991 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
992 RParenLoc, ClassDecl);
993}
994
John McCalle22a04a2009-11-04 23:02:40 +0000995/// Checks an initializer expression for use of uninitialized fields, such as
996/// containing the field that is being initialized. Returns true if there is an
997/// uninitialized field was used an updates the SourceLocation parameter; false
998/// otherwise.
999static bool InitExprContainsUninitializedFields(const Stmt* S,
1000 const FieldDecl* LhsField,
1001 SourceLocation* L) {
1002 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1003 if (ME) {
1004 const NamedDecl* RhsField = ME->getMemberDecl();
1005 if (RhsField == LhsField) {
1006 // Initializing a field with itself. Throw a warning.
1007 // But wait; there are exceptions!
1008 // Exception #1: The field may not belong to this record.
1009 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1010 const Expr* base = ME->getBase();
1011 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1012 // Even though the field matches, it does not belong to this record.
1013 return false;
1014 }
1015 // None of the exceptions triggered; return true to indicate an
1016 // uninitialized field was used.
1017 *L = ME->getMemberLoc();
1018 return true;
1019 }
1020 }
1021 bool found = false;
1022 for (Stmt::const_child_iterator it = S->child_begin();
1023 it != S->child_end() && found == false;
1024 ++it) {
1025 if (isa<CallExpr>(S)) {
1026 // Do not descend into function calls or constructors, as the use
1027 // of an uninitialized field may be valid. One would have to inspect
1028 // the contents of the function/ctor to determine if it is safe or not.
1029 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1030 // may be safe, depending on what the function/ctor does.
1031 continue;
1032 }
1033 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1034 }
1035 return found;
1036}
1037
Eli Friedman8e1433b2009-07-29 19:44:27 +00001038Sema::MemInitResult
1039Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1040 unsigned NumArgs, SourceLocation IdLoc,
1041 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001042 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1043 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1044 ExprTemporaries.clear();
1045
John McCalle22a04a2009-11-04 23:02:40 +00001046 // Diagnose value-uses of fields to initialize themselves, e.g.
1047 // foo(foo)
1048 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001049 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001050 for (unsigned i = 0; i < NumArgs; ++i) {
1051 SourceLocation L;
1052 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1053 // FIXME: Return true in the case when other fields are used before being
1054 // uninitialized. For example, let this field be the i'th field. When
1055 // initializing the i'th field, throw a warning if any of the >= i'th
1056 // fields are used, as they are not yet initialized.
1057 // Right now we are only handling the case where the i'th field uses
1058 // itself in its initializer.
1059 Diag(L, diag::warn_field_is_uninit);
1060 }
1061 }
1062
Eli Friedman8e1433b2009-07-29 19:44:27 +00001063 bool HasDependentArg = false;
1064 for (unsigned i = 0; i < NumArgs; i++)
1065 HasDependentArg |= Args[i]->isTypeDependent();
1066
1067 CXXConstructorDecl *C = 0;
1068 QualType FieldType = Member->getType();
1069 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1070 FieldType = Array->getElementType();
1071 if (FieldType->isDependentType()) {
1072 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001073 } else if (FieldType->isRecordType()) {
1074 // Member is a record (struct/union/class), so pass the initializer
1075 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001076 if (!HasDependentArg) {
1077 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1078
1079 C = PerformInitializationByConstructor(FieldType,
1080 MultiExprArg(*this,
1081 (void**)Args,
1082 NumArgs),
1083 IdLoc,
1084 SourceRange(IdLoc, RParenLoc),
1085 Member->getDeclName(), IK_Direct,
1086 ConstructorArgs);
1087
1088 if (C) {
1089 // Take over the constructor arguments as our own.
1090 NumArgs = ConstructorArgs.size();
1091 Args = (Expr **)ConstructorArgs.take();
1092 }
1093 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001094 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001095 // The member type is not a record type (or an array of record
1096 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001097 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001098 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1099 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001100 Expr *NewExp;
1101 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001102 if (FieldType->isReferenceType()) {
1103 Diag(IdLoc, diag::err_null_intialized_reference_member)
1104 << Member->getDeclName();
1105 return Diag(Member->getLocation(), diag::note_declared_at);
1106 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001107 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1108 NumArgs = 1;
1109 }
1110 else
1111 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001112 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1113 return true;
1114 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001115 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001116
1117 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1118 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1119 ExprTemporaries.clear();
1120
Eli Friedman8e1433b2009-07-29 19:44:27 +00001121 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001122 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001123 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001124}
1125
1126Sema::MemInitResult
1127Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1128 unsigned NumArgs, SourceLocation IdLoc,
1129 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1130 bool HasDependentArg = false;
1131 for (unsigned i = 0; i < NumArgs; i++)
1132 HasDependentArg |= Args[i]->isTypeDependent();
1133
1134 if (!BaseType->isDependentType()) {
1135 if (!BaseType->isRecordType())
1136 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1137 << BaseType << SourceRange(IdLoc, RParenLoc);
1138
1139 // C++ [class.base.init]p2:
1140 // [...] Unless the mem-initializer-id names a nonstatic data
1141 // member of the constructor’s class or a direct or virtual base
1142 // of that class, the mem-initializer is ill-formed. A
1143 // mem-initializer-list can initialize a base class using any
1144 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001145
Eli Friedman8e1433b2009-07-29 19:44:27 +00001146 // First, check for a direct base class.
1147 const CXXBaseSpecifier *DirectBaseSpec = 0;
1148 for (CXXRecordDecl::base_class_const_iterator Base =
1149 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001150 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001151 // We found a direct base of this type. That's what we're
1152 // initializing.
1153 DirectBaseSpec = &*Base;
1154 break;
1155 }
1156 }
Mike Stump11289f42009-09-09 15:08:12 +00001157
Eli Friedman8e1433b2009-07-29 19:44:27 +00001158 // Check for a virtual base class.
1159 // FIXME: We might be able to short-circuit this if we know in advance that
1160 // there are no virtual bases.
1161 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1162 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1163 // We haven't found a base yet; search the class hierarchy for a
1164 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001165 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1166 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001167 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001168 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001169 Path != Paths.end(); ++Path) {
1170 if (Path->back().Base->isVirtual()) {
1171 VirtualBaseSpec = Path->back().Base;
1172 break;
1173 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001174 }
1175 }
1176 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001177
1178 // C++ [base.class.init]p2:
1179 // If a mem-initializer-id is ambiguous because it designates both
1180 // a direct non-virtual base class and an inherited virtual base
1181 // class, the mem-initializer is ill-formed.
1182 if (DirectBaseSpec && VirtualBaseSpec)
1183 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1184 << BaseType << SourceRange(IdLoc, RParenLoc);
1185 // C++ [base.class.init]p2:
1186 // Unless the mem-initializer-id names a nonstatic data membeer of the
1187 // constructor's class ot a direst or virtual base of that class, the
1188 // mem-initializer is ill-formed.
1189 if (!DirectBaseSpec && !VirtualBaseSpec)
1190 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1191 << BaseType << ClassDecl->getNameAsCString()
1192 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001193 }
1194
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001195 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001196 if (!BaseType->isDependentType() && !HasDependentArg) {
1197 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001198 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001199 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1200
1201 C = PerformInitializationByConstructor(BaseType,
1202 MultiExprArg(*this,
1203 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001204 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001205 Name, IK_Direct,
1206 ConstructorArgs);
1207 if (C) {
1208 // Take over the constructor arguments as our own.
1209 NumArgs = ConstructorArgs.size();
1210 Args = (Expr **)ConstructorArgs.take();
1211 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001212 }
1213
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001214 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1215 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1216 ExprTemporaries.clear();
1217
Mike Stump11289f42009-09-09 15:08:12 +00001218 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001219 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001220}
1221
Eli Friedman9cf6b592009-11-09 19:20:36 +00001222bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001223Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001224 CXXBaseOrMemberInitializer **Initializers,
1225 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001226 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001227 // We need to build the initializer AST according to order of construction
1228 // and not what user specified in the Initializers list.
1229 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1230 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1231 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1232 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001233 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001234
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001235 for (unsigned i = 0; i < NumInitializers; i++) {
1236 CXXBaseOrMemberInitializer *Member = Initializers[i];
1237 if (Member->isBaseInitializer()) {
1238 if (Member->getBaseClass()->isDependentType())
1239 HasDependentBaseInit = true;
1240 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1241 } else {
1242 AllBaseFields[Member->getMember()] = Member;
1243 }
1244 }
Mike Stump11289f42009-09-09 15:08:12 +00001245
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001246 if (HasDependentBaseInit) {
1247 // FIXME. This does not preserve the ordering of the initializers.
1248 // Try (with -Wreorder)
1249 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001250 // template<class X> struct B : A<X> {
1251 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001252 // int x1;
1253 // };
1254 // B<int> x;
1255 // On seeing one dependent type, we should essentially exit this routine
1256 // while preserving user-declared initializer list. When this routine is
1257 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001258 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001259
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001260 // If we have a dependent base initialization, we can't determine the
1261 // association between initializers and bases; just dump the known
1262 // initializers into the list, and don't try to deal with other bases.
1263 for (unsigned i = 0; i < NumInitializers; i++) {
1264 CXXBaseOrMemberInitializer *Member = Initializers[i];
1265 if (Member->isBaseInitializer())
1266 AllToInit.push_back(Member);
1267 }
1268 } else {
1269 // Push virtual bases before others.
1270 for (CXXRecordDecl::base_class_iterator VBase =
1271 ClassDecl->vbases_begin(),
1272 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1273 if (VBase->getType()->isDependentType())
1274 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001275 if (CXXBaseOrMemberInitializer *Value
1276 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001277 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001278 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001279 else {
Mike Stump11289f42009-09-09 15:08:12 +00001280 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001281 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001282 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001283 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001284 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001285 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1286 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1287 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001288 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001289 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001290 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001291 continue;
1292 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001293
Anders Carlsson561f7932009-10-29 15:46:07 +00001294 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1295 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1296 Constructor->getLocation(), CtorArgs))
1297 continue;
1298
1299 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1300
Anders Carlssonbdd12402009-11-13 20:11:49 +00001301 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1302 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1303 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001304 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001305 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1306 CtorArgs.takeAs<Expr>(),
1307 CtorArgs.size(), Ctor,
1308 SourceLocation(),
1309 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001310 AllToInit.push_back(Member);
1311 }
1312 }
Mike Stump11289f42009-09-09 15:08:12 +00001313
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001314 for (CXXRecordDecl::base_class_iterator Base =
1315 ClassDecl->bases_begin(),
1316 E = ClassDecl->bases_end(); Base != E; ++Base) {
1317 // Virtuals are in the virtual base list and already constructed.
1318 if (Base->isVirtual())
1319 continue;
1320 // Skip dependent types.
1321 if (Base->getType()->isDependentType())
1322 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001323 if (CXXBaseOrMemberInitializer *Value
1324 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001325 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001326 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001327 else {
Mike Stump11289f42009-09-09 15:08:12 +00001328 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001329 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001330 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001331 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001332 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001333 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1334 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1335 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001336 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001337 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001338 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001339 continue;
1340 }
1341
1342 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1343 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1344 Constructor->getLocation(), CtorArgs))
1345 continue;
1346
1347 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001348
Anders Carlssonbdd12402009-11-13 20:11:49 +00001349 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1350 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1351 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001352 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001353 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1354 CtorArgs.takeAs<Expr>(),
1355 CtorArgs.size(), Ctor,
1356 SourceLocation(),
1357 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001358 AllToInit.push_back(Member);
1359 }
1360 }
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001363 // non-static data members.
1364 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1365 E = ClassDecl->field_end(); Field != E; ++Field) {
1366 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001367 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001368 Field->getType()->getAs<RecordType>()) {
1369 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001370 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001371 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001372 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1373 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1374 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1375 // set to the anonymous union data member used in the initializer
1376 // list.
1377 Value->setMember(*Field);
1378 Value->setAnonUnionMember(*FA);
1379 AllToInit.push_back(Value);
1380 break;
1381 }
1382 }
1383 }
1384 continue;
1385 }
1386 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1387 AllToInit.push_back(Value);
1388 continue;
1389 }
Mike Stump11289f42009-09-09 15:08:12 +00001390
Eli Friedmand7686ef2009-11-09 01:05:47 +00001391 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001392 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001393
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001394 QualType FT = Context.getBaseElementType((*Field)->getType());
1395 if (const RecordType* RT = FT->getAs<RecordType>()) {
1396 CXXConstructorDecl *Ctor =
1397 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001398 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001399 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1400 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1401 << 1 << (*Field)->getDeclName();
1402 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001403 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001404 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001405 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001406 continue;
1407 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001408
1409 if (FT.isConstQualified() && Ctor->isTrivial()) {
1410 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1411 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1412 << 1 << (*Field)->getDeclName();
1413 Diag((*Field)->getLocation(), diag::note_declared_at);
1414 HadError = true;
1415 }
1416
1417 // Don't create initializers for trivial constructors, since they don't
1418 // actually need to be run.
1419 if (Ctor->isTrivial())
1420 continue;
1421
Anders Carlsson561f7932009-10-29 15:46:07 +00001422 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1423 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1424 Constructor->getLocation(), CtorArgs))
1425 continue;
1426
Anders Carlssonbdd12402009-11-13 20:11:49 +00001427 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1428 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1429 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001430 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001431 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1432 CtorArgs.size(), Ctor,
1433 SourceLocation(),
1434 SourceLocation());
1435
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001436 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001437 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001438 }
1439 else if (FT->isReferenceType()) {
1440 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001441 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1442 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001443 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001444 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001445 }
1446 else if (FT.isConstQualified()) {
1447 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001448 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1449 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001450 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001451 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001452 }
1453 }
Mike Stump11289f42009-09-09 15:08:12 +00001454
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001455 NumInitializers = AllToInit.size();
1456 if (NumInitializers > 0) {
1457 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1458 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1459 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001460
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001461 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1462 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1463 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1464 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001465
1466 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001467}
1468
Eli Friedman952c15d2009-07-21 19:28:10 +00001469static void *GetKeyForTopLevelField(FieldDecl *Field) {
1470 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001471 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001472 if (RT->getDecl()->isAnonymousStructOrUnion())
1473 return static_cast<void *>(RT->getDecl());
1474 }
1475 return static_cast<void *>(Field);
1476}
1477
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001478static void *GetKeyForBase(QualType BaseType) {
1479 if (const RecordType *RT = BaseType->getAs<RecordType>())
1480 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001481
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001482 assert(0 && "Unexpected base type!");
1483 return 0;
1484}
1485
Mike Stump11289f42009-09-09 15:08:12 +00001486static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001487 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001488 // For fields injected into the class via declaration of an anonymous union,
1489 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001490 if (Member->isMemberInitializer()) {
1491 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001492
Eli Friedmand7686ef2009-11-09 01:05:47 +00001493 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001494 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001495 // in AnonUnionMember field.
1496 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1497 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001498 if (Field->getDeclContext()->isRecord()) {
1499 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1500 if (RD->isAnonymousStructOrUnion())
1501 return static_cast<void *>(RD);
1502 }
1503 return static_cast<void *>(Field);
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001506 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001507}
1508
John McCallc90f6d72009-11-04 23:13:52 +00001509/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001510void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001511 SourceLocation ColonLoc,
1512 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001513 if (!ConstructorDecl)
1514 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001515
1516 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001517
1518 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001519 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001520
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001521 if (!Constructor) {
1522 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1523 return;
1524 }
Mike Stump11289f42009-09-09 15:08:12 +00001525
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001526 if (!Constructor->isDependentContext()) {
1527 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1528 bool err = false;
1529 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001530 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001531 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1532 void *KeyToMember = GetKeyForMember(Member);
1533 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1534 if (!PrevMember) {
1535 PrevMember = Member;
1536 continue;
1537 }
1538 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001539 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001540 diag::error_multiple_mem_initialization)
1541 << Field->getNameAsString();
1542 else {
1543 Type *BaseClass = Member->getBaseClass();
1544 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001545 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001546 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001547 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001548 }
1549 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1550 << 0;
1551 err = true;
1552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001554 if (err)
1555 return;
1556 }
Mike Stump11289f42009-09-09 15:08:12 +00001557
Eli Friedmand7686ef2009-11-09 01:05:47 +00001558 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001559 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001560 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001561
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001562 if (Constructor->isDependentContext())
1563 return;
Mike Stump11289f42009-09-09 15:08:12 +00001564
1565 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001566 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001567 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001568 Diagnostic::Ignored)
1569 return;
Mike Stump11289f42009-09-09 15:08:12 +00001570
Anders Carlssone0eebb32009-08-27 05:45:01 +00001571 // Also issue warning if order of ctor-initializer list does not match order
1572 // of 1) base class declarations and 2) order of non-static data members.
1573 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001574
Anders Carlssone0eebb32009-08-27 05:45:01 +00001575 CXXRecordDecl *ClassDecl
1576 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1577 // Push virtual bases before others.
1578 for (CXXRecordDecl::base_class_iterator VBase =
1579 ClassDecl->vbases_begin(),
1580 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001581 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001582
Anders Carlssone0eebb32009-08-27 05:45:01 +00001583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1584 E = ClassDecl->bases_end(); Base != E; ++Base) {
1585 // Virtuals are alread in the virtual base list and are constructed
1586 // first.
1587 if (Base->isVirtual())
1588 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001589 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
Anders Carlssone0eebb32009-08-27 05:45:01 +00001592 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1593 E = ClassDecl->field_end(); Field != E; ++Field)
1594 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001595
Anders Carlssone0eebb32009-08-27 05:45:01 +00001596 int Last = AllBaseOrMembers.size();
1597 int curIndex = 0;
1598 CXXBaseOrMemberInitializer *PrevMember = 0;
1599 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001600 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001601 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1602 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001603
Anders Carlssone0eebb32009-08-27 05:45:01 +00001604 for (; curIndex < Last; curIndex++)
1605 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1606 break;
1607 if (curIndex == Last) {
1608 assert(PrevMember && "Member not in member list?!");
1609 // Initializer as specified in ctor-initializer list is out of order.
1610 // Issue a warning diagnostic.
1611 if (PrevMember->isBaseInitializer()) {
1612 // Diagnostics is for an initialized base class.
1613 Type *BaseClass = PrevMember->getBaseClass();
1614 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001615 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001616 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001617 } else {
1618 FieldDecl *Field = PrevMember->getMember();
1619 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001620 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001621 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001622 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001623 // Also the note!
1624 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001625 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001626 diag::note_fieldorbase_initialized_here) << 0
1627 << Field->getNameAsString();
1628 else {
1629 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001630 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001631 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001632 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001633 }
1634 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001635 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001636 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001637 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001638 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001639 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001640}
1641
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001642void
Anders Carlssondee9a302009-11-17 04:44:12 +00001643Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1644 // Ignore dependent destructors.
1645 if (Destructor->isDependentContext())
1646 return;
1647
1648 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001649
Anders Carlssondee9a302009-11-17 04:44:12 +00001650 // Non-static data members.
1651 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1652 E = ClassDecl->field_end(); I != E; ++I) {
1653 FieldDecl *Field = *I;
1654
1655 QualType FieldType = Context.getBaseElementType(Field->getType());
1656
1657 const RecordType* RT = FieldType->getAs<RecordType>();
1658 if (!RT)
1659 continue;
1660
1661 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1662 if (FieldClassDecl->hasTrivialDestructor())
1663 continue;
1664
1665 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1666 MarkDeclarationReferenced(Destructor->getLocation(),
1667 const_cast<CXXDestructorDecl*>(Dtor));
1668 }
1669
1670 // Bases.
1671 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1672 E = ClassDecl->bases_end(); Base != E; ++Base) {
1673 // Ignore virtual bases.
1674 if (Base->isVirtual())
1675 continue;
1676
1677 // Ignore trivial destructors.
1678 CXXRecordDecl *BaseClassDecl
1679 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1680 if (BaseClassDecl->hasTrivialDestructor())
1681 continue;
1682
1683 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1684 MarkDeclarationReferenced(Destructor->getLocation(),
1685 const_cast<CXXDestructorDecl*>(Dtor));
1686 }
1687
1688 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001689 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1690 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001691 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001692 CXXRecordDecl *BaseClassDecl
1693 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1694 if (BaseClassDecl->hasTrivialDestructor())
1695 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001696
1697 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1698 MarkDeclarationReferenced(Destructor->getLocation(),
1699 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001700 }
1701}
1702
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001703void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001704 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001705 return;
Mike Stump11289f42009-09-09 15:08:12 +00001706
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001707 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001708
1709 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001710 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001711 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001712}
1713
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001714namespace {
1715 /// PureVirtualMethodCollector - traverses a class and its superclasses
1716 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001717 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001718 ASTContext &Context;
1719
Sebastian Redlb7d64912009-03-22 21:28:55 +00001720 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001721 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001722
1723 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001724 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001725
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001726 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001728 public:
Mike Stump11289f42009-09-09 15:08:12 +00001729 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001730 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001731
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001732 MethodList List;
1733 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001734
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001735 // Copy the temporary list to methods, and make sure to ignore any
1736 // null entries.
1737 for (size_t i = 0, e = List.size(); i != e; ++i) {
1738 if (List[i])
1739 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001740 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001743 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001744
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001745 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1746 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001747 };
Mike Stump11289f42009-09-09 15:08:12 +00001748
1749 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001750 MethodList& Methods) {
1751 // First, collect the pure virtual methods for the base classes.
1752 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1753 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001754 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001755 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001756 if (BaseDecl && BaseDecl->isAbstract())
1757 Collect(BaseDecl, Methods);
1758 }
1759 }
Mike Stump11289f42009-09-09 15:08:12 +00001760
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001761 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001762 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlsson3c012712009-05-17 00:00:05 +00001764 MethodSetTy OverriddenMethods;
1765 size_t MethodsSize = Methods.size();
1766
Mike Stump11289f42009-09-09 15:08:12 +00001767 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001768 i != e; ++i) {
1769 // Traverse the record, looking for methods.
1770 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001771 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001772 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001773 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Anders Carlsson700179432009-10-18 19:34:08 +00001775 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001776 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1777 E = MD->end_overridden_methods(); I != E; ++I) {
1778 // Keep track of the overridden methods.
1779 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001780 }
1781 }
1782 }
Mike Stump11289f42009-09-09 15:08:12 +00001783
1784 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001785 // overridden.
1786 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1787 if (OverriddenMethods.count(Methods[i]))
1788 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001791 }
1792}
Douglas Gregore8381c02008-11-05 04:29:56 +00001793
Anders Carlssoneabf7702009-08-27 00:13:57 +00001794
Mike Stump11289f42009-09-09 15:08:12 +00001795bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001796 unsigned DiagID, AbstractDiagSelID SelID,
1797 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001798 if (SelID == -1)
1799 return RequireNonAbstractType(Loc, T,
1800 PDiag(DiagID), CurrentRD);
1801 else
1802 return RequireNonAbstractType(Loc, T,
1803 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001804}
1805
Anders Carlssoneabf7702009-08-27 00:13:57 +00001806bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1807 const PartialDiagnostic &PD,
1808 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001809 if (!getLangOptions().CPlusPlus)
1810 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001811
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001812 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001813 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001814 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001815
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001816 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001817 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001818 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001819 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001821 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001822 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001823 }
Mike Stump11289f42009-09-09 15:08:12 +00001824
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001825 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001826 if (!RT)
1827 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001828
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001829 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1830 if (!RD)
1831 return false;
1832
Anders Carlssonb57738b2009-03-24 17:23:42 +00001833 if (CurrentRD && CurrentRD != RD)
1834 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001835
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001836 if (!RD->isAbstract())
1837 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Anders Carlssoneabf7702009-08-27 00:13:57 +00001839 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001840
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001841 // Check if we've already emitted the list of pure virtual functions for this
1842 // class.
1843 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1844 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001845
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001846 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001847
1848 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001849 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1850 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001851
1852 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001853 MD->getDeclName();
1854 }
1855
1856 if (!PureVirtualClassDiagSet)
1857 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1858 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001859
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001860 return true;
1861}
1862
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001863namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001864 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001865 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1866 Sema &SemaRef;
1867 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001868
Anders Carlssonb57738b2009-03-24 17:23:42 +00001869 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001870 bool Invalid = false;
1871
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001872 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1873 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001874 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001875
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001876 return Invalid;
1877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Anders Carlssonb57738b2009-03-24 17:23:42 +00001879 public:
1880 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1881 : SemaRef(SemaRef), AbstractClass(ac) {
1882 Visit(SemaRef.Context.getTranslationUnitDecl());
1883 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001884
Anders Carlssonb57738b2009-03-24 17:23:42 +00001885 bool VisitFunctionDecl(const FunctionDecl *FD) {
1886 if (FD->isThisDeclarationADefinition()) {
1887 // No need to do the check if we're in a definition, because it requires
1888 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001889 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001890 return VisitDeclContext(FD);
1891 }
Mike Stump11289f42009-09-09 15:08:12 +00001892
Anders Carlssonb57738b2009-03-24 17:23:42 +00001893 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001894 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001895 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001896 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1897 diag::err_abstract_type_in_decl,
1898 Sema::AbstractReturnType,
1899 AbstractClass);
1900
Mike Stump11289f42009-09-09 15:08:12 +00001901 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001902 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001903 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001904 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001905 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001906 VD->getOriginalType(),
1907 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001908 Sema::AbstractParamType,
1909 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001910 }
1911
1912 return Invalid;
1913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssonb57738b2009-03-24 17:23:42 +00001915 bool VisitDecl(const Decl* D) {
1916 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1917 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Anders Carlssonb57738b2009-03-24 17:23:42 +00001919 return false;
1920 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001921 };
1922}
1923
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001924void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001925 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001926 SourceLocation LBrac,
1927 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001928 if (!TagDecl)
1929 return;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001931 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001933 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001934 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001935
Chris Lattner83f095c2009-03-28 19:18:32 +00001936 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001937 if (!RD->isAbstract()) {
1938 // Collect all the pure virtual methods and see if this is an abstract
1939 // class after all.
1940 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001941 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001942 RD->setAbstract(true);
1943 }
Mike Stump11289f42009-09-09 15:08:12 +00001944
1945 if (RD->isAbstract())
Douglas Gregor120f6a62009-11-17 06:14:37 +00001946 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001947
Douglas Gregor3c74d412009-10-14 20:14:33 +00001948 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001949 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001950}
1951
Douglas Gregor05379422008-11-03 17:51:48 +00001952/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1953/// special functions, such as the default constructor, copy
1954/// constructor, or destructor, to the given C++ class (C++
1955/// [special]p1). This routine can only be executed just before the
1956/// definition of the class is complete.
1957void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001958 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001959 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001960
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001961 // FIXME: Implicit declarations have exception specifications, which are
1962 // the union of the specifications of the implicitly called functions.
1963
Douglas Gregor05379422008-11-03 17:51:48 +00001964 if (!ClassDecl->hasUserDeclaredConstructor()) {
1965 // C++ [class.ctor]p5:
1966 // A default constructor for a class X is a constructor of class X
1967 // that can be called without an argument. If there is no
1968 // user-declared constructor for class X, a default constructor is
1969 // implicitly declared. An implicitly-declared default constructor
1970 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001971 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001972 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001973 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001974 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001975 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001976 Context.getFunctionType(Context.VoidTy,
1977 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001978 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001979 /*isExplicit=*/false,
1980 /*isInline=*/true,
1981 /*isImplicitlyDeclared=*/true);
1982 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001983 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001984 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001985 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001986 }
1987
1988 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1989 // C++ [class.copy]p4:
1990 // If the class definition does not explicitly declare a copy
1991 // constructor, one is declared implicitly.
1992
1993 // C++ [class.copy]p5:
1994 // The implicitly-declared copy constructor for a class X will
1995 // have the form
1996 //
1997 // X::X(const X&)
1998 //
1999 // if
2000 bool HasConstCopyConstructor = true;
2001
2002 // -- each direct or virtual base class B of X has a copy
2003 // constructor whose first parameter is of type const B& or
2004 // const volatile B&, and
2005 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2006 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2007 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002008 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002009 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002010 = BaseClassDecl->hasConstCopyConstructor(Context);
2011 }
2012
2013 // -- for all the nonstatic data members of X that are of a
2014 // class type M (or array thereof), each such class type
2015 // has a copy constructor whose first parameter is of type
2016 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2018 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002019 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002020 QualType FieldType = (*Field)->getType();
2021 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2022 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002024 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002025 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002026 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002027 = FieldClassDecl->hasConstCopyConstructor(Context);
2028 }
2029 }
2030
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002031 // Otherwise, the implicitly declared copy constructor will have
2032 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002033 //
2034 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002035 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002036 if (HasConstCopyConstructor)
2037 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002038 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002039
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002040 // An implicitly-declared copy constructor is an inline public
2041 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002042 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002043 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002044 CXXConstructorDecl *CopyConstructor
2045 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002046 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002047 Context.getFunctionType(Context.VoidTy,
2048 &ArgType, 1,
2049 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002050 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002051 /*isExplicit=*/false,
2052 /*isInline=*/true,
2053 /*isImplicitlyDeclared=*/true);
2054 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002055 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002056 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002057
2058 // Add the parameter to the constructor.
2059 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2060 ClassDecl->getLocation(),
2061 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002062 ArgType, /*DInfo=*/0,
2063 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002064 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002065 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002066 }
2067
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002068 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2069 // Note: The following rules are largely analoguous to the copy
2070 // constructor rules. Note that virtual bases are not taken into account
2071 // for determining the argument type of the operator. Note also that
2072 // operators taking an object instead of a reference are allowed.
2073 //
2074 // C++ [class.copy]p10:
2075 // If the class definition does not explicitly declare a copy
2076 // assignment operator, one is declared implicitly.
2077 // The implicitly-defined copy assignment operator for a class X
2078 // will have the form
2079 //
2080 // X& X::operator=(const X&)
2081 //
2082 // if
2083 bool HasConstCopyAssignment = true;
2084
2085 // -- each direct base class B of X has a copy assignment operator
2086 // whose parameter is of type const B&, const volatile B& or B,
2087 // and
2088 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2089 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002090 assert(!Base->getType()->isDependentType() &&
2091 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002092 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002093 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002094 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002095 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002096 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002097 }
2098
2099 // -- for all the nonstatic data members of X that are of a class
2100 // type M (or array thereof), each such class type has a copy
2101 // assignment operator whose parameter is of type const M&,
2102 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002103 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2104 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002105 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002106 QualType FieldType = (*Field)->getType();
2107 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2108 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002109 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002110 const CXXRecordDecl *FieldClassDecl
2111 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002112 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002113 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002114 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002115 }
2116 }
2117
2118 // Otherwise, the implicitly declared copy assignment operator will
2119 // have the form
2120 //
2121 // X& X::operator=(X&)
2122 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002123 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002124 if (HasConstCopyAssignment)
2125 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002126 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002127
2128 // An implicitly-declared copy assignment operator is an inline public
2129 // member of its class.
2130 DeclarationName Name =
2131 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2132 CXXMethodDecl *CopyAssignment =
2133 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2134 Context.getFunctionType(RetType, &ArgType, 1,
2135 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002136 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002137 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002138 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002139 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002140 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002141
2142 // Add the parameter to the operator.
2143 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2144 ClassDecl->getLocation(),
2145 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002146 ArgType, /*DInfo=*/0,
2147 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002148 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002149
2150 // Don't call addedAssignmentOperator. There is no way to distinguish an
2151 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002152 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002153 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002154 }
2155
Douglas Gregor1349b452008-12-15 21:24:18 +00002156 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002157 // C++ [class.dtor]p2:
2158 // If a class has no user-declared destructor, a destructor is
2159 // declared implicitly. An implicitly-declared destructor is an
2160 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002161 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002162 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002163 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002164 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002165 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002166 Context.getFunctionType(Context.VoidTy,
2167 0, 0, false, 0),
2168 /*isInline=*/true,
2169 /*isImplicitlyDeclared=*/true);
2170 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002171 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002172 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002173 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002174
2175 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002176 }
Douglas Gregor05379422008-11-03 17:51:48 +00002177}
2178
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002179void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002180 Decl *D = TemplateD.getAs<Decl>();
2181 if (!D)
2182 return;
2183
2184 TemplateParameterList *Params = 0;
2185 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2186 Params = Template->getTemplateParameters();
2187 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2188 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2189 Params = PartialSpec->getTemplateParameters();
2190 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002191 return;
2192
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002193 for (TemplateParameterList::iterator Param = Params->begin(),
2194 ParamEnd = Params->end();
2195 Param != ParamEnd; ++Param) {
2196 NamedDecl *Named = cast<NamedDecl>(*Param);
2197 if (Named->getDeclName()) {
2198 S->AddDecl(DeclPtrTy::make(Named));
2199 IdResolver.AddDecl(Named);
2200 }
2201 }
2202}
2203
Douglas Gregor4d87df52008-12-16 21:30:33 +00002204/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2205/// parsing a top-level (non-nested) C++ class, and we are now
2206/// parsing those parts of the given Method declaration that could
2207/// not be parsed earlier (C++ [class.mem]p2), such as default
2208/// arguments. This action should enter the scope of the given
2209/// Method declaration as if we had just parsed the qualified method
2210/// name. However, it should not bring the parameters into scope;
2211/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002212void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002213 if (!MethodD)
2214 return;
Mike Stump11289f42009-09-09 15:08:12 +00002215
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002216 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002217
Douglas Gregor4d87df52008-12-16 21:30:33 +00002218 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002219 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002220 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002221 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2222 SS.setScopeRep(
2223 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002224 ActOnCXXEnterDeclaratorScope(S, SS);
2225}
2226
2227/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2228/// C++ method declaration. We're (re-)introducing the given
2229/// function parameter into scope for use in parsing later parts of
2230/// the method declaration. For example, we could see an
2231/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002232void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002233 if (!ParamD)
2234 return;
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattner83f095c2009-03-28 19:18:32 +00002236 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002237
2238 // If this parameter has an unparsed default argument, clear it out
2239 // to make way for the parsed default argument.
2240 if (Param->hasUnparsedDefaultArg())
2241 Param->setDefaultArg(0);
2242
Chris Lattner83f095c2009-03-28 19:18:32 +00002243 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002244 if (Param->getDeclName())
2245 IdResolver.AddDecl(Param);
2246}
2247
2248/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2249/// processing the delayed method declaration for Method. The method
2250/// declaration is now considered finished. There may be a separate
2251/// ActOnStartOfFunctionDef action later (not necessarily
2252/// immediately!) for this method, if it was also defined inside the
2253/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002254void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002255 if (!MethodD)
2256 return;
Mike Stump11289f42009-09-09 15:08:12 +00002257
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002258 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002259
Chris Lattner83f095c2009-03-28 19:18:32 +00002260 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002261 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002262 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002263 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2264 SS.setScopeRep(
2265 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002266 ActOnCXXExitDeclaratorScope(S, SS);
2267
2268 // Now that we have our default arguments, check the constructor
2269 // again. It could produce additional diagnostics or affect whether
2270 // the class has implicitly-declared destructors, among other
2271 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2273 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002274
2275 // Check the default arguments, which we may have added.
2276 if (!Method->isInvalidDecl())
2277 CheckCXXDefaultArguments(Method);
2278}
2279
Douglas Gregor831c93f2008-11-05 20:51:48 +00002280/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002281/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002282/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002283/// emit diagnostics and set the invalid bit to true. In any case, the type
2284/// will be updated to reflect a well-formed type for the constructor and
2285/// returned.
2286QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2287 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002288 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002289
2290 // C++ [class.ctor]p3:
2291 // A constructor shall not be virtual (10.3) or static (9.4). A
2292 // constructor can be invoked for a const, volatile or const
2293 // volatile object. A constructor shall not be declared const,
2294 // volatile, or const volatile (9.3.2).
2295 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002296 if (!D.isInvalidType())
2297 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2298 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2299 << SourceRange(D.getIdentifierLoc());
2300 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002301 }
2302 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002303 if (!D.isInvalidType())
2304 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2305 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2306 << SourceRange(D.getIdentifierLoc());
2307 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002308 SC = FunctionDecl::None;
2309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
Chris Lattner38378bf2009-04-25 08:28:21 +00002311 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2312 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002313 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002314 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2315 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002316 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002317 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2318 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002319 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002320 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2321 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002322 }
Mike Stump11289f42009-09-09 15:08:12 +00002323
Douglas Gregor831c93f2008-11-05 20:51:48 +00002324 // Rebuild the function type "R" without any type qualifiers (in
2325 // case any of the errors above fired) and with "void" as the
2326 // return type, since constructors don't have return types. We
2327 // *always* have to do this, because GetTypeForDeclarator will
2328 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002329 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002330 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2331 Proto->getNumArgs(),
2332 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002333}
2334
Douglas Gregor4d87df52008-12-16 21:30:33 +00002335/// CheckConstructor - Checks a fully-formed constructor for
2336/// well-formedness, issuing any diagnostics required. Returns true if
2337/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002338void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002339 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002340 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2341 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002342 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002343
2344 // C++ [class.copy]p3:
2345 // A declaration of a constructor for a class X is ill-formed if
2346 // its first parameter is of type (optionally cv-qualified) X and
2347 // either there are no other parameters or else all other
2348 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002349 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002350 ((Constructor->getNumParams() == 1) ||
2351 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002352 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2353 Constructor->getTemplateSpecializationKind()
2354 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002355 QualType ParamType = Constructor->getParamDecl(0)->getType();
2356 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2357 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002358 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2359 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002360 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002361
2362 // FIXME: Rather that making the constructor invalid, we should endeavor
2363 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002364 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002365 }
2366 }
Mike Stump11289f42009-09-09 15:08:12 +00002367
Douglas Gregor4d87df52008-12-16 21:30:33 +00002368 // Notify the class that we've added a constructor.
2369 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002370}
2371
Anders Carlsson26a807d2009-11-30 21:24:50 +00002372/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2373/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002374bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002375 CXXRecordDecl *RD = Destructor->getParent();
2376
2377 if (Destructor->isVirtual()) {
2378 SourceLocation Loc;
2379
2380 if (!Destructor->isImplicit())
2381 Loc = Destructor->getLocation();
2382 else
2383 Loc = RD->getLocation();
2384
2385 // If we have a virtual destructor, look up the deallocation function
2386 FunctionDecl *OperatorDelete = 0;
2387 DeclarationName Name =
2388 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002389 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002390 return true;
2391
2392 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002393 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002394
2395 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002396}
2397
Mike Stump11289f42009-09-09 15:08:12 +00002398static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002399FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2400 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2401 FTI.ArgInfo[0].Param &&
2402 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2403}
2404
Douglas Gregor831c93f2008-11-05 20:51:48 +00002405/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2406/// the well-formednes of the destructor declarator @p D with type @p
2407/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002408/// emit diagnostics and set the declarator to invalid. Even if this happens,
2409/// will be updated to reflect a well-formed type for the destructor and
2410/// returned.
2411QualType Sema::CheckDestructorDeclarator(Declarator &D,
2412 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002413 // C++ [class.dtor]p1:
2414 // [...] A typedef-name that names a class is a class-name
2415 // (7.1.3); however, a typedef-name that names a class shall not
2416 // be used as the identifier in the declarator for a destructor
2417 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002418 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002419 if (isa<TypedefType>(DeclaratorType)) {
2420 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002421 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002422 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002423 }
2424
2425 // C++ [class.dtor]p2:
2426 // A destructor is used to destroy objects of its class type. A
2427 // destructor takes no parameters, and no return type can be
2428 // specified for it (not even void). The address of a destructor
2429 // shall not be taken. A destructor shall not be static. A
2430 // destructor can be invoked for a const, volatile or const
2431 // volatile object. A destructor shall not be declared const,
2432 // volatile or const volatile (9.3.2).
2433 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002434 if (!D.isInvalidType())
2435 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2436 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2437 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002438 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002439 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002440 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002441 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002442 // Destructors don't have return types, but the parser will
2443 // happily parse something like:
2444 //
2445 // class X {
2446 // float ~X();
2447 // };
2448 //
2449 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002450 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2451 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2452 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattner38378bf2009-04-25 08:28:21 +00002455 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2456 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002457 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002458 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2459 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002460 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002461 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2462 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002463 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002464 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2465 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002466 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002467 }
2468
2469 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002470 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002471 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2472
2473 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002474 FTI.freeArgs();
2475 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002476 }
2477
Mike Stump11289f42009-09-09 15:08:12 +00002478 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002479 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002480 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002481 D.setInvalidType();
2482 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002483
2484 // Rebuild the function type "R" without any type qualifiers or
2485 // parameters (in case any of the errors above fired) and with
2486 // "void" as the return type, since destructors don't have return
2487 // types. We *always* have to do this, because GetTypeForDeclarator
2488 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002489 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002490}
2491
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002492/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2493/// well-formednes of the conversion function declarator @p D with
2494/// type @p R. If there are any errors in the declarator, this routine
2495/// will emit diagnostics and return true. Otherwise, it will return
2496/// false. Either way, the type @p R will be updated to reflect a
2497/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002498void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002499 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002500 // C++ [class.conv.fct]p1:
2501 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002502 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002503 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002504 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002505 if (!D.isInvalidType())
2506 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2507 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2508 << SourceRange(D.getIdentifierLoc());
2509 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002510 SC = FunctionDecl::None;
2511 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002512 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002513 // Conversion functions don't have return types, but the parser will
2514 // happily parse something like:
2515 //
2516 // class X {
2517 // float operator bool();
2518 // };
2519 //
2520 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002521 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2523 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002524 }
2525
2526 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002527 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002528 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2529
2530 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002531 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002532 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002533 }
2534
Mike Stump11289f42009-09-09 15:08:12 +00002535 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002536 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002537 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002538 D.setInvalidType();
2539 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002540
2541 // C++ [class.conv.fct]p4:
2542 // The conversion-type-id shall not represent a function type nor
2543 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002544 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002545 if (ConvType->isArrayType()) {
2546 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2547 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002548 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002549 } else if (ConvType->isFunctionType()) {
2550 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2551 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002552 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002553 }
2554
2555 // Rebuild the function type "R" without any parameters (in case any
2556 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002557 // return type.
2558 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002559 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002560
Douglas Gregor5fb53972009-01-14 15:45:31 +00002561 // C++0x explicit conversion operators.
2562 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002563 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002564 diag::warn_explicit_conversion_functions)
2565 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002566}
2567
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002568/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2569/// the declaration of the given C++ conversion function. This routine
2570/// is responsible for recording the conversion function in the C++
2571/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002572Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002573 assert(Conversion && "Expected to receive a conversion function declaration");
2574
Douglas Gregor4287b372008-12-12 08:25:50 +00002575 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002576
2577 // Make sure we aren't redeclaring the conversion function.
2578 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002579
2580 // C++ [class.conv.fct]p1:
2581 // [...] A conversion function is never used to convert a
2582 // (possibly cv-qualified) object to the (possibly cv-qualified)
2583 // same object type (or a reference to it), to a (possibly
2584 // cv-qualified) base class of that type (or a reference to it),
2585 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002586 // FIXME: Suppress this warning if the conversion function ends up being a
2587 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002588 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002589 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002590 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002591 ConvType = ConvTypeRef->getPointeeType();
2592 if (ConvType->isRecordType()) {
2593 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2594 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002595 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002596 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002597 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002598 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002599 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002600 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002601 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002602 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002603 }
2604
Douglas Gregor1dc98262008-12-26 15:00:45 +00002605 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002606 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002607 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002608 = Conversion->getDescribedFunctionTemplate())
2609 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002610 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2611 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002612 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002613 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002614 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002615 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002616 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002617 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002618
Chris Lattner83f095c2009-03-28 19:18:32 +00002619 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002620}
2621
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002622//===----------------------------------------------------------------------===//
2623// Namespace Handling
2624//===----------------------------------------------------------------------===//
2625
2626/// ActOnStartNamespaceDef - This is called at the start of a namespace
2627/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002628Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2629 SourceLocation IdentLoc,
2630 IdentifierInfo *II,
2631 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002632 NamespaceDecl *Namespc =
2633 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2634 Namespc->setLBracLoc(LBrace);
2635
2636 Scope *DeclRegionScope = NamespcScope->getParent();
2637
2638 if (II) {
2639 // C++ [namespace.def]p2:
2640 // The identifier in an original-namespace-definition shall not have been
2641 // previously defined in the declarative region in which the
2642 // original-namespace-definition appears. The identifier in an
2643 // original-namespace-definition is the name of the namespace. Subsequently
2644 // in that declarative region, it is treated as an original-namespace-name.
2645
John McCall9f3059a2009-10-09 21:13:30 +00002646 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002647 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002648 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002649
Douglas Gregor91f84212008-12-11 16:49:14 +00002650 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2651 // This is an extended namespace definition.
2652 // Attach this namespace decl to the chain of extended namespace
2653 // definitions.
2654 OrigNS->setNextNamespace(Namespc);
2655 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002656
Mike Stump11289f42009-09-09 15:08:12 +00002657 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002658 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002659 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002660 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002661 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002662 } else if (PrevDecl) {
2663 // This is an invalid name redefinition.
2664 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2665 << Namespc->getDeclName();
2666 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2667 Namespc->setInvalidDecl();
2668 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002669 } else if (II->isStr("std") &&
2670 CurContext->getLookupContext()->isTranslationUnit()) {
2671 // This is the first "real" definition of the namespace "std", so update
2672 // our cache of the "std" namespace to point at this definition.
2673 if (StdNamespace) {
2674 // We had already defined a dummy namespace "std". Link this new
2675 // namespace definition to the dummy namespace "std".
2676 StdNamespace->setNextNamespace(Namespc);
2677 StdNamespace->setLocation(IdentLoc);
2678 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2679 }
2680
2681 // Make our StdNamespace cache point at the first real definition of the
2682 // "std" namespace.
2683 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002684 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002685
2686 PushOnScopeChains(Namespc, DeclRegionScope);
2687 } else {
John McCall4fa53422009-10-01 00:25:31 +00002688 // Anonymous namespaces.
2689
2690 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2691 // behaves as if it were replaced by
2692 // namespace unique { /* empty body */ }
2693 // using namespace unique;
2694 // namespace unique { namespace-body }
2695 // where all occurrences of 'unique' in a translation unit are
2696 // replaced by the same identifier and this identifier differs
2697 // from all other identifiers in the entire program.
2698
2699 // We just create the namespace with an empty name and then add an
2700 // implicit using declaration, just like the standard suggests.
2701 //
2702 // CodeGen enforces the "universally unique" aspect by giving all
2703 // declarations semantically contained within an anonymous
2704 // namespace internal linkage.
2705
2706 assert(Namespc->isAnonymousNamespace());
2707 CurContext->addDecl(Namespc);
2708
2709 UsingDirectiveDecl* UD
2710 = UsingDirectiveDecl::Create(Context, CurContext,
2711 /* 'using' */ LBrace,
2712 /* 'namespace' */ SourceLocation(),
2713 /* qualifier */ SourceRange(),
2714 /* NNS */ NULL,
2715 /* identifier */ SourceLocation(),
2716 Namespc,
2717 /* Ancestor */ CurContext);
2718 UD->setImplicit();
2719 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002720 }
2721
2722 // Although we could have an invalid decl (i.e. the namespace name is a
2723 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002724 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2725 // for the namespace has the declarations that showed up in that particular
2726 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002727 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002728 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002729}
2730
Sebastian Redla6602e92009-11-23 15:34:23 +00002731/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2732/// is a namespace alias, returns the namespace it points to.
2733static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2734 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2735 return AD->getNamespace();
2736 return dyn_cast_or_null<NamespaceDecl>(D);
2737}
2738
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002739/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2740/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002741void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2742 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002743 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2744 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2745 Namespc->setRBracLoc(RBrace);
2746 PopDeclContext();
2747}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002748
Chris Lattner83f095c2009-03-28 19:18:32 +00002749Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2750 SourceLocation UsingLoc,
2751 SourceLocation NamespcLoc,
2752 const CXXScopeSpec &SS,
2753 SourceLocation IdentLoc,
2754 IdentifierInfo *NamespcName,
2755 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002756 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2757 assert(NamespcName && "Invalid NamespcName.");
2758 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002759 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002760
Douglas Gregor889ceb72009-02-03 19:21:40 +00002761 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002762
Douglas Gregor34074322009-01-14 22:20:51 +00002763 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002764 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2765 LookupParsedName(R, S, &SS);
2766 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002767 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002768
John McCall9f3059a2009-10-09 21:13:30 +00002769 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002770 NamedDecl *Named = R.getFoundDecl();
2771 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2772 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002773 // C++ [namespace.udir]p1:
2774 // A using-directive specifies that the names in the nominated
2775 // namespace can be used in the scope in which the
2776 // using-directive appears after the using-directive. During
2777 // unqualified name lookup (3.4.1), the names appear as if they
2778 // were declared in the nearest enclosing namespace which
2779 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002780 // namespace. [Note: in this context, "contains" means "contains
2781 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002782
2783 // Find enclosing context containing both using-directive and
2784 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002785 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002786 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2787 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2788 CommonAncestor = CommonAncestor->getParent();
2789
Sebastian Redla6602e92009-11-23 15:34:23 +00002790 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002791 SS.getRange(),
2792 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002793 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002794 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002795 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002796 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002797 }
2798
Douglas Gregor889ceb72009-02-03 19:21:40 +00002799 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002800 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002801 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002802}
2803
2804void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2805 // If scope has associated entity, then using directive is at namespace
2806 // or translation unit scope. We add UsingDirectiveDecls, into
2807 // it's lookup structure.
2808 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002809 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002810 else
2811 // Otherwise it is block-sope. using-directives will affect lookup
2812 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002813 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002814}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002815
Douglas Gregorfec52632009-06-20 00:51:54 +00002816
2817Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002818 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002819 SourceLocation UsingLoc,
2820 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002821 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002822 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002823 bool IsTypeName,
2824 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002825 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002826
Douglas Gregor220f4272009-11-04 16:30:06 +00002827 switch (Name.getKind()) {
2828 case UnqualifiedId::IK_Identifier:
2829 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002830 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002831 case UnqualifiedId::IK_ConversionFunctionId:
2832 break;
2833
2834 case UnqualifiedId::IK_ConstructorName:
2835 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2836 << SS.getRange();
2837 return DeclPtrTy();
2838
2839 case UnqualifiedId::IK_DestructorName:
2840 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2841 << SS.getRange();
2842 return DeclPtrTy();
2843
2844 case UnqualifiedId::IK_TemplateId:
2845 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2846 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2847 return DeclPtrTy();
2848 }
2849
2850 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3f746822009-11-17 05:59:44 +00002851 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002852 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002853 TargetName, AttrList,
2854 /* IsInstantiation */ false,
2855 IsTypeName, TypenameLoc);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002856 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002857 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002858 UD->setAccess(AS);
2859 }
Mike Stump11289f42009-09-09 15:08:12 +00002860
Anders Carlsson696a3f12009-08-28 05:40:36 +00002861 return DeclPtrTy::make(UD);
2862}
2863
John McCall3f746822009-11-17 05:59:44 +00002864/// Builds a shadow declaration corresponding to a 'using' declaration.
2865static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2866 AccessSpecifier AS,
2867 UsingDecl *UD, NamedDecl *Orig) {
2868 // FIXME: diagnose hiding, collisions
2869
2870 // If we resolved to another shadow declaration, just coalesce them.
2871 if (isa<UsingShadowDecl>(Orig)) {
2872 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2873 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2874 }
2875
2876 UsingShadowDecl *Shadow
2877 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2878 UD->getLocation(), UD, Orig);
2879 UD->addShadowDecl(Shadow);
2880
2881 if (S)
2882 SemaRef.PushOnScopeChains(Shadow, S);
2883 else
2884 SemaRef.CurContext->addDecl(Shadow);
2885 Shadow->setAccess(AS);
2886
2887 return Shadow;
2888}
2889
John McCalle61f2ba2009-11-18 02:36:19 +00002890/// Builds a using declaration.
2891///
2892/// \param IsInstantiation - Whether this call arises from an
2893/// instantiation of an unresolved using declaration. We treat
2894/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002895NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2896 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002897 const CXXScopeSpec &SS,
2898 SourceLocation IdentLoc,
2899 DeclarationName Name,
2900 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002901 bool IsInstantiation,
2902 bool IsTypeName,
2903 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002904 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2905 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002906
Anders Carlssonf038fc22009-08-28 05:49:21 +00002907 // FIXME: We ignore attributes for now.
2908 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002909
Anders Carlsson59140b32009-08-28 03:16:11 +00002910 if (SS.isEmpty()) {
2911 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002912 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002913 }
Mike Stump11289f42009-09-09 15:08:12 +00002914
2915 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002916 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2917
John McCall84c16cf2009-11-12 03:15:40 +00002918 DeclContext *LookupContext = computeDeclContext(SS);
2919 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00002920 if (IsTypeName) {
2921 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2922 UsingLoc, TypenameLoc,
2923 SS.getRange(), NNS,
2924 IdentLoc, Name);
2925 } else {
2926 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2927 UsingLoc, SS.getRange(), NNS,
2928 IdentLoc, Name);
2929 }
Anders Carlssonf038fc22009-08-28 05:49:21 +00002930 }
Mike Stump11289f42009-09-09 15:08:12 +00002931
Anders Carlsson59140b32009-08-28 03:16:11 +00002932 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2933 // C++0x N2914 [namespace.udecl]p3:
2934 // A using-declaration used as a member-declaration shall refer to a member
2935 // of a base class of the class being defined, shall refer to a member of an
2936 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002937 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002938 // a member of a base class of the class being defined.
John McCall3f746822009-11-17 05:59:44 +00002939
John McCall84c16cf2009-11-12 03:15:40 +00002940 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2941 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00002942 Diag(SS.getRange().getBegin(),
2943 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2944 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002945 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002946 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002947 } else {
2948 // C++0x N2914 [namespace.udecl]p8:
2949 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00002950 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002951 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002952 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002953 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002954 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002955 }
2956
John McCall3f746822009-11-17 05:59:44 +00002957 // Look up the target name. Unlike most lookups, we do not want to
2958 // hide tag declarations: tag names are visible through the using
2959 // declaration even if hidden by ordinary names.
John McCall27b18f82009-11-17 02:14:36 +00002960 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00002961
2962 // We don't hide tags behind ordinary decls if we're in a
2963 // non-dependent context, but in a dependent context, this is
2964 // important for the stability of two-phase lookup.
2965 if (!IsInstantiation)
2966 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00002967
John McCall27b18f82009-11-17 02:14:36 +00002968 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00002969
John McCall9f3059a2009-10-09 21:13:30 +00002970 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002971 Diag(IdentLoc, diag::err_no_member)
2972 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002973 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002974 }
2975
John McCall3f746822009-11-17 05:59:44 +00002976 if (R.isAmbiguous())
2977 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002978
John McCalle61f2ba2009-11-18 02:36:19 +00002979 if (IsTypeName) {
2980 // If we asked for a typename and got a non-type decl, error out.
2981 if (R.getResultKind() != LookupResult::Found
2982 || !isa<TypeDecl>(R.getFoundDecl())) {
2983 Diag(IdentLoc, diag::err_using_typename_non_type);
2984 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2985 Diag((*I)->getUnderlyingDecl()->getLocation(),
2986 diag::note_using_decl_target);
2987 return 0;
2988 }
2989 } else {
2990 // If we asked for a non-typename and we got a type, error out,
2991 // but only if this is an instantiation of an unresolved using
2992 // decl. Otherwise just silently find the type name.
2993 if (IsInstantiation &&
2994 R.getResultKind() == LookupResult::Found &&
2995 isa<TypeDecl>(R.getFoundDecl())) {
2996 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
2997 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
2998 return 0;
2999 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003000 }
3001
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003002 // C++0x N2914 [namespace.udecl]p6:
3003 // A using-declaration shall not name a namespace.
John McCall3f746822009-11-17 05:59:44 +00003004 if (R.getResultKind() == LookupResult::Found
3005 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003006 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3007 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003008 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010
John McCall3f746822009-11-17 05:59:44 +00003011 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3012 SS.getRange(), UsingLoc, NNS, Name,
3013 IsTypeName);
3014
3015 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3016 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3017
3018 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003019}
3020
Mike Stump11289f42009-09-09 15:08:12 +00003021Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003022 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003023 SourceLocation AliasLoc,
3024 IdentifierInfo *Alias,
3025 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003026 SourceLocation IdentLoc,
3027 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003028
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003029 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003030 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3031 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003032
Anders Carlssondca83c42009-03-28 06:23:46 +00003033 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003034 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003035 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003036 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003037 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003038 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003039 if (!R.isAmbiguous() && !R.empty() &&
3040 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003041 return DeclPtrTy();
3042 }
Mike Stump11289f42009-09-09 15:08:12 +00003043
Anders Carlssondca83c42009-03-28 06:23:46 +00003044 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3045 diag::err_redefinition_different_kind;
3046 Diag(AliasLoc, DiagID) << Alias;
3047 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003048 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003049 }
3050
John McCall27b18f82009-11-17 02:14:36 +00003051 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003052 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003053
John McCall9f3059a2009-10-09 21:13:30 +00003054 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003055 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003056 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003057 }
Mike Stump11289f42009-09-09 15:08:12 +00003058
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003059 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003060 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3061 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003062 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003063 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003064
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003065 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003066 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003067}
3068
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003069void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3070 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003071 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3072 !Constructor->isUsed()) &&
3073 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003074
Eli Friedman9cf6b592009-11-09 19:20:36 +00003075 CXXRecordDecl *ClassDecl
3076 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3077 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003078
Eli Friedman9cf6b592009-11-09 19:20:36 +00003079 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003080 Diag(CurrentLocation, diag::note_member_synthesized_at)
3081 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003082 Constructor->setInvalidDecl();
3083 } else {
3084 Constructor->setUsed();
3085 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00003086
3087 MaybeMarkVirtualImplicitMembersReferenced(CurrentLocation, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003088}
3089
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003090void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003091 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003092 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3093 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003094 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003095 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3096 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003097 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003098 // implicitly defined, all the implicitly-declared default destructors
3099 // for its base class and its non-static data members shall have been
3100 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003101 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3102 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003103 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003104 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003105 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003106 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003107 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3108 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3109 else
Mike Stump11289f42009-09-09 15:08:12 +00003110 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003111 "DefineImplicitDestructor - missing dtor in a base class");
3112 }
3113 }
Mike Stump11289f42009-09-09 15:08:12 +00003114
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003115 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3116 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003117 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3118 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3119 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003120 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003121 CXXRecordDecl *FieldClassDecl
3122 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3123 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003124 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003125 const_cast<CXXDestructorDecl*>(
3126 FieldClassDecl->getDestructor(Context)))
3127 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3128 else
Mike Stump11289f42009-09-09 15:08:12 +00003129 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003130 "DefineImplicitDestructor - missing dtor in class of a data member");
3131 }
3132 }
3133 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003134
3135 // FIXME: If CheckDestructor fails, we should emit a note about where the
3136 // implicit destructor was needed.
3137 if (CheckDestructor(Destructor)) {
3138 Diag(CurrentLocation, diag::note_member_synthesized_at)
3139 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3140
3141 Destructor->setInvalidDecl();
3142 return;
3143 }
3144
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003145 Destructor->setUsed();
3146}
3147
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003148void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3149 CXXMethodDecl *MethodDecl) {
3150 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3151 MethodDecl->getOverloadedOperator() == OO_Equal &&
3152 !MethodDecl->isUsed()) &&
3153 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003154
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003155 CXXRecordDecl *ClassDecl
3156 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003157
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003158 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003159 // Before the implicitly-declared copy assignment operator for a class is
3160 // implicitly defined, all implicitly-declared copy assignment operators
3161 // for its direct base classes and its nonstatic data members shall have
3162 // been implicitly defined.
3163 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003164 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3165 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003166 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003167 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003168 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003169 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3170 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3171 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003172 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3173 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003174 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3175 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3176 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003177 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003178 CXXRecordDecl *FieldClassDecl
3179 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003180 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003181 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3182 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003183 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003184 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003185 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3186 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003187 Diag(CurrentLocation, diag::note_first_required_here);
3188 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003189 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003190 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003191 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3192 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003193 Diag(CurrentLocation, diag::note_first_required_here);
3194 err = true;
3195 }
3196 }
3197 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003198 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003199}
3200
3201CXXMethodDecl *
3202Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3203 CXXRecordDecl *ClassDecl) {
3204 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3205 QualType RHSType(LHSType);
3206 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003207 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003208 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003209 RHSType = Context.getCVRQualifiedType(RHSType,
3210 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003211 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3212 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003213 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003214 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3215 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003216 SourceLocation()));
3217 Expr *Args[2] = { &*LHS, &*RHS };
3218 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003219 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003220 CandidateSet);
3221 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003222 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003223 ClassDecl->getLocation(), Best) == OR_Success)
3224 return cast<CXXMethodDecl>(Best->Function);
3225 assert(false &&
3226 "getAssignOperatorMethod - copy assignment operator method not found");
3227 return 0;
3228}
3229
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003230void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3231 CXXConstructorDecl *CopyConstructor,
3232 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003233 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003234 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3235 !CopyConstructor->isUsed()) &&
3236 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003237
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003238 CXXRecordDecl *ClassDecl
3239 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3240 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003241 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003242 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003243 // implicitly defined, all the implicitly-declared copy constructors
3244 // for its base class and its non-static data members shall have been
3245 // implicitly defined.
3246 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3247 Base != ClassDecl->bases_end(); ++Base) {
3248 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003249 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003250 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003251 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003252 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003253 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003254 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3255 FieldEnd = ClassDecl->field_end();
3256 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003257 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3258 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3259 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003260 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003261 CXXRecordDecl *FieldClassDecl
3262 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003263 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003264 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003265 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003266 }
3267 }
3268 CopyConstructor->setUsed();
3269}
3270
Anders Carlsson6eb55572009-08-25 05:12:04 +00003271Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003272Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003273 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003274 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003275 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003276
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003277 // C++ [class.copy]p15:
3278 // Whenever a temporary class object is copied using a copy constructor, and
3279 // this object and the copy have the same cv-unqualified type, an
3280 // implementation is permitted to treat the original and the copy as two
3281 // different ways of referring to the same object and not perform a copy at
3282 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003283
Anders Carlsson250aada2009-08-16 05:13:48 +00003284 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003285 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003286 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003287 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3288 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003289 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3290 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3291 E = ICE->getSubExpr();
3292
Anders Carlsson250aada2009-08-16 05:13:48 +00003293 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3294 Elidable = true;
3295 }
Mike Stump11289f42009-09-09 15:08:12 +00003296
3297 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003298 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003299}
3300
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003301/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3302/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003303Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003304Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3305 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003306 MultiExprArg ExprArgs) {
3307 unsigned NumExprs = ExprArgs.size();
3308 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003309
Douglas Gregor27381f32009-11-23 12:27:39 +00003310 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003311 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3312 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003313}
3314
Anders Carlsson574315a2009-08-27 05:08:22 +00003315Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003316Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3317 QualType Ty,
3318 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003319 MultiExprArg Args,
3320 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003321 unsigned NumExprs = Args.size();
3322 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregor27381f32009-11-23 12:27:39 +00003324 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003325 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3326 TyBeginLoc, Exprs,
3327 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003328}
3329
3330
Mike Stump11289f42009-09-09 15:08:12 +00003331bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003332 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003333 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003334 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003335 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003336 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003337 if (TempResult.isInvalid())
3338 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003339
Anders Carlsson6eb55572009-08-25 05:12:04 +00003340 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003341 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003342 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003343 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003344
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003345 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003346}
3347
Mike Stump11289f42009-09-09 15:08:12 +00003348void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003349 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003350 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003351 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003352 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003353 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003354 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003355}
3356
Mike Stump11289f42009-09-09 15:08:12 +00003357/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003358/// ActOnDeclarator, when a C++ direct initializer is present.
3359/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003360void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3361 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003362 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003363 SourceLocation *CommaLocs,
3364 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003365 unsigned NumExprs = Exprs.size();
3366 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003367 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003368
3369 // If there is no declaration, there was an error parsing it. Just ignore
3370 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003371 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003372 return;
Mike Stump11289f42009-09-09 15:08:12 +00003373
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003374 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3375 if (!VDecl) {
3376 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3377 RealDecl->setInvalidDecl();
3378 return;
3379 }
3380
Douglas Gregor402250f2009-08-26 21:14:46 +00003381 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003382 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003383 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3384 //
3385 // Clients that want to distinguish between the two forms, can check for
3386 // direct initializer using VarDecl::hasCXXDirectInitializer().
3387 // A major benefit is that clients that don't particularly care about which
3388 // exactly form was it (like the CodeGen) can handle both cases without
3389 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003390
Douglas Gregor402250f2009-08-26 21:14:46 +00003391 // If either the declaration has a dependent type or if any of the expressions
3392 // is type-dependent, we represent the initialization via a ParenListExpr for
3393 // later use during template instantiation.
3394 if (VDecl->getType()->isDependentType() ||
3395 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3396 // Let clients know that initialization was done with a direct initializer.
3397 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003398
Douglas Gregor402250f2009-08-26 21:14:46 +00003399 // Store the initialization expressions as a ParenListExpr.
3400 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003401 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003402 new (Context) ParenListExpr(Context, LParenLoc,
3403 (Expr **)Exprs.release(),
3404 NumExprs, RParenLoc));
3405 return;
3406 }
Mike Stump11289f42009-09-09 15:08:12 +00003407
Douglas Gregor402250f2009-08-26 21:14:46 +00003408
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003409 // C++ 8.5p11:
3410 // The form of initialization (using parentheses or '=') is generally
3411 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003412 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003413 QualType DeclInitType = VDecl->getType();
3414 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003415 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003416
Douglas Gregor4044d992009-03-24 16:43:20 +00003417 // FIXME: This isn't the right place to complete the type.
3418 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3419 diag::err_typecheck_decl_incomplete_type)) {
3420 VDecl->setInvalidDecl();
3421 return;
3422 }
3423
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003424 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003425 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3426
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003427 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003428 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003429 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003430 VDecl->getLocation(),
3431 SourceRange(VDecl->getLocation(),
3432 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003433 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003434 IK_Direct,
3435 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003436 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003437 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003438 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003439 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003440 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003441 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003442 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003443 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003444 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003445 return;
3446 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003447
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003448 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003449 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3450 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003451 RealDecl->setInvalidDecl();
3452 return;
3453 }
3454
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003455 // Let clients know that initialization was done with a direct initializer.
3456 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003457
3458 assert(NumExprs == 1 && "Expected 1 expression");
3459 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003460 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3461 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003462}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003463
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003464/// \brief Add the applicable constructor candidates for an initialization
3465/// by constructor.
3466static void AddConstructorInitializationCandidates(Sema &SemaRef,
3467 QualType ClassType,
3468 Expr **Args,
3469 unsigned NumArgs,
3470 Sema::InitializationKind Kind,
3471 OverloadCandidateSet &CandidateSet) {
3472 // C++ [dcl.init]p14:
3473 // If the initialization is direct-initialization, or if it is
3474 // copy-initialization where the cv-unqualified version of the
3475 // source type is the same class as, or a derived class of, the
3476 // class of the destination, constructors are considered. The
3477 // applicable constructors are enumerated (13.3.1.3), and the
3478 // best one is chosen through overload resolution (13.3). The
3479 // constructor so selected is called to initialize the object,
3480 // with the initializer expression(s) as its argument(s). If no
3481 // constructor applies, or the overload resolution is ambiguous,
3482 // the initialization is ill-formed.
3483 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3484 assert(ClassRec && "Can only initialize a class type here");
3485
3486 // FIXME: When we decide not to synthesize the implicitly-declared
3487 // constructors, we'll need to make them appear here.
3488
3489 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3490 DeclarationName ConstructorName
3491 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3492 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3493 DeclContext::lookup_const_iterator Con, ConEnd;
3494 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3495 Con != ConEnd; ++Con) {
3496 // Find the constructor (which may be a template).
3497 CXXConstructorDecl *Constructor = 0;
3498 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3499 if (ConstructorTmpl)
3500 Constructor
3501 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3502 else
3503 Constructor = cast<CXXConstructorDecl>(*Con);
3504
3505 if ((Kind == Sema::IK_Direct) ||
3506 (Kind == Sema::IK_Copy &&
3507 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3508 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3509 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003510 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3511 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003512 Args, NumArgs, CandidateSet);
3513 else
3514 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3515 }
3516 }
3517}
3518
3519/// \brief Attempt to perform initialization by constructor
3520/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3521/// copy-initialization.
3522///
3523/// This routine determines whether initialization by constructor is possible,
3524/// but it does not emit any diagnostics in the case where the initialization
3525/// is ill-formed.
3526///
3527/// \param ClassType the type of the object being initialized, which must have
3528/// class type.
3529///
3530/// \param Args the arguments provided to initialize the object
3531///
3532/// \param NumArgs the number of arguments provided to initialize the object
3533///
3534/// \param Kind the type of initialization being performed
3535///
3536/// \returns the constructor used to initialize the object, if successful.
3537/// Otherwise, emits a diagnostic and returns NULL.
3538CXXConstructorDecl *
3539Sema::TryInitializationByConstructor(QualType ClassType,
3540 Expr **Args, unsigned NumArgs,
3541 SourceLocation Loc,
3542 InitializationKind Kind) {
3543 // Build the overload candidate set
3544 OverloadCandidateSet CandidateSet;
3545 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3546 CandidateSet);
3547
3548 // Determine whether we found a constructor we can use.
3549 OverloadCandidateSet::iterator Best;
3550 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3551 case OR_Success:
3552 case OR_Deleted:
3553 // We found a constructor. Return it.
3554 return cast<CXXConstructorDecl>(Best->Function);
3555
3556 case OR_No_Viable_Function:
3557 case OR_Ambiguous:
3558 // Overload resolution failed. Return nothing.
3559 return 0;
3560 }
3561
3562 // Silence GCC warning
3563 return 0;
3564}
3565
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003566/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3567/// may occur as part of direct-initialization or copy-initialization.
3568///
3569/// \param ClassType the type of the object being initialized, which must have
3570/// class type.
3571///
3572/// \param ArgsPtr the arguments provided to initialize the object
3573///
3574/// \param Loc the source location where the initialization occurs
3575///
3576/// \param Range the source range that covers the entire initialization
3577///
3578/// \param InitEntity the name of the entity being initialized, if known
3579///
3580/// \param Kind the type of initialization being performed
3581///
3582/// \param ConvertedArgs a vector that will be filled in with the
3583/// appropriately-converted arguments to the constructor (if initialization
3584/// succeeded).
3585///
3586/// \returns the constructor used to initialize the object, if successful.
3587/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003588CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003589Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003590 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003591 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003592 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003593 InitializationKind Kind,
3594 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003595
3596 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003597 Expr **Args = (Expr **)ArgsPtr.get();
3598 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003599 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003600 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3601 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003602
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003603 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003604 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003605 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003606 // We found a constructor. Break out so that we can convert the arguments
3607 // appropriately.
3608 break;
Mike Stump11289f42009-09-09 15:08:12 +00003609
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003610 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003611 if (InitEntity)
3612 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003613 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003614 else
3615 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003616 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003617 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003618 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003619
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003620 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003621 if (InitEntity)
3622 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3623 else
3624 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003625 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3626 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003627
3628 case OR_Deleted:
3629 if (InitEntity)
3630 Diag(Loc, diag::err_ovl_deleted_init)
3631 << Best->Function->isDeleted()
3632 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003633 else {
3634 const CXXRecordDecl *RD =
3635 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003636 Diag(Loc, diag::err_ovl_deleted_init)
3637 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003638 << RD->getDeclName() << Range;
3639 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003640 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3641 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003642 }
Mike Stump11289f42009-09-09 15:08:12 +00003643
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003644 // Convert the arguments, fill in default arguments, etc.
3645 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3646 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3647 return 0;
3648
3649 return Constructor;
3650}
3651
3652/// \brief Given a constructor and the set of arguments provided for the
3653/// constructor, convert the arguments and add any required default arguments
3654/// to form a proper call to this constructor.
3655///
3656/// \returns true if an error occurred, false otherwise.
3657bool
3658Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3659 MultiExprArg ArgsPtr,
3660 SourceLocation Loc,
3661 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3662 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3663 unsigned NumArgs = ArgsPtr.size();
3664 Expr **Args = (Expr **)ArgsPtr.get();
3665
3666 const FunctionProtoType *Proto
3667 = Constructor->getType()->getAs<FunctionProtoType>();
3668 assert(Proto && "Constructor without a prototype?");
3669 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003670
3671 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003672 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003673 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003674 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003675 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003676
3677 VariadicCallType CallType =
3678 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3679 llvm::SmallVector<Expr *, 8> AllArgs;
3680 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3681 Proto, 0, Args, NumArgs, AllArgs,
3682 CallType);
3683 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3684 ConvertedArgs.push_back(AllArgs[i]);
3685 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003686}
3687
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003688/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3689/// determine whether they are reference-related,
3690/// reference-compatible, reference-compatible with added
3691/// qualification, or incompatible, for use in C++ initialization by
3692/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3693/// type, and the first type (T1) is the pointee type of the reference
3694/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003695Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003696Sema::CompareReferenceRelationship(SourceLocation Loc,
3697 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003698 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003699 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003700 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003701 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003702
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003703 QualType T1 = Context.getCanonicalType(OrigT1);
3704 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003705 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3706 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003707
3708 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003709 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003710 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003711 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003712 if (UnqualT1 == UnqualT2)
3713 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003714 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3715 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3716 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003717 DerivedToBase = true;
3718 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003719 return Ref_Incompatible;
3720
3721 // At this point, we know that T1 and T2 are reference-related (at
3722 // least).
3723
3724 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003725 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003726 // reference-related to T2 and cv1 is the same cv-qualification
3727 // as, or greater cv-qualification than, cv2. For purposes of
3728 // overload resolution, cases for which cv1 is greater
3729 // cv-qualification than cv2 are identified as
3730 // reference-compatible with added qualification (see 13.3.3.2).
3731 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3732 return Ref_Compatible;
3733 else if (T1.isMoreQualifiedThan(T2))
3734 return Ref_Compatible_With_Added_Qualification;
3735 else
3736 return Ref_Related;
3737}
3738
3739/// CheckReferenceInit - Check the initialization of a reference
3740/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3741/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003742/// list), and DeclType is the type of the declaration. When ICS is
3743/// non-null, this routine will compute the implicit conversion
3744/// sequence according to C++ [over.ics.ref] and will not produce any
3745/// diagnostics; when ICS is null, it will emit diagnostics when any
3746/// errors are found. Either way, a return value of true indicates
3747/// that there was a failure, a return value of false indicates that
3748/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003749///
3750/// When @p SuppressUserConversions, user-defined conversions are
3751/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003752/// When @p AllowExplicit, we also permit explicit user-defined
3753/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003754/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003755/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3756/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003757bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003758Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003759 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003760 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003761 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003762 ImplicitConversionSequence *ICS,
3763 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003764 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3765
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003766 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003767 QualType T2 = Init->getType();
3768
Douglas Gregorcd695e52008-11-10 20:40:00 +00003769 // If the initializer is the address of an overloaded function, try
3770 // to resolve the overloaded function. If all goes well, T2 is the
3771 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003772 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003773 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003774 ICS != 0);
3775 if (Fn) {
3776 // Since we're performing this reference-initialization for
3777 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003778 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003779 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003780 return true;
3781
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003782 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003783 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003784
3785 T2 = Fn->getType();
3786 }
3787 }
3788
Douglas Gregor786ab212008-10-29 02:00:59 +00003789 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003790 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003791 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003792 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3793 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003794 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003795 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003796
3797 // Most paths end in a failed conversion.
3798 if (ICS)
3799 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003800
3801 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003802 // A reference to type "cv1 T1" is initialized by an expression
3803 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003804
3805 // -- If the initializer expression
3806
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003807 // Rvalue references cannot bind to lvalues (N2812).
3808 // There is absolutely no situation where they can. In particular, note that
3809 // this is ill-formed, even if B has a user-defined conversion to A&&:
3810 // B b;
3811 // A&& r = b;
3812 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3813 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003814 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003815 << Init->getSourceRange();
3816 return true;
3817 }
3818
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003819 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003820 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3821 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003822 //
3823 // Note that the bit-field check is skipped if we are just computing
3824 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003825 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003826 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003827 BindsDirectly = true;
3828
Douglas Gregor786ab212008-10-29 02:00:59 +00003829 if (ICS) {
3830 // C++ [over.ics.ref]p1:
3831 // When a parameter of reference type binds directly (8.5.3)
3832 // to an argument expression, the implicit conversion sequence
3833 // is the identity conversion, unless the argument expression
3834 // has a type that is a derived class of the parameter type,
3835 // in which case the implicit conversion sequence is a
3836 // derived-to-base Conversion (13.3.3.1).
3837 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3838 ICS->Standard.First = ICK_Identity;
3839 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3840 ICS->Standard.Third = ICK_Identity;
3841 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3842 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003843 ICS->Standard.ReferenceBinding = true;
3844 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003845 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003846 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003847
3848 // Nothing more to do: the inaccessibility/ambiguity check for
3849 // derived-to-base conversions is suppressed when we're
3850 // computing the implicit conversion sequence (C++
3851 // [over.best.ics]p2).
3852 return false;
3853 } else {
3854 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003855 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3856 if (DerivedToBase)
3857 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003858 else if(CheckExceptionSpecCompatibility(Init, T1))
3859 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003860 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003861 }
3862 }
3863
3864 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003865 // implicitly converted to an lvalue of type "cv3 T3,"
3866 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003867 // 92) (this conversion is selected by enumerating the
3868 // applicable conversion functions (13.3.1.6) and choosing
3869 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003870 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003871 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003872 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003873 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003874
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003875 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00003876 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003877 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003878 for (UnresolvedSet::iterator I = Conversions->begin(),
3879 E = Conversions->end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00003880 FunctionTemplateDecl *ConvTemplate
John McCalld14a8642009-11-21 08:51:07 +00003881 = dyn_cast<FunctionTemplateDecl>(*I);
Douglas Gregor05155d82009-08-21 23:19:43 +00003882 CXXConversionDecl *Conv;
3883 if (ConvTemplate)
3884 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3885 else
John McCalld14a8642009-11-21 08:51:07 +00003886 Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003887
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003888 // If the conversion function doesn't return a reference type,
3889 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003890 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003891 (AllowExplicit || !Conv->isExplicit())) {
3892 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003893 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003894 CandidateSet);
3895 else
3896 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3897 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003898 }
3899
3900 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003901 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003902 case OR_Success:
3903 // This is a direct binding.
3904 BindsDirectly = true;
3905
3906 if (ICS) {
3907 // C++ [over.ics.ref]p1:
3908 //
3909 // [...] If the parameter binds directly to the result of
3910 // applying a conversion function to the argument
3911 // expression, the implicit conversion sequence is a
3912 // user-defined conversion sequence (13.3.3.1.2), with the
3913 // second standard conversion sequence either an identity
3914 // conversion or, if the conversion function returns an
3915 // entity of a type that is a derived class of the parameter
3916 // type, a derived-to-base Conversion.
3917 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3918 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3919 ICS->UserDefined.After = Best->FinalConversion;
3920 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003921 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003922 assert(ICS->UserDefined.After.ReferenceBinding &&
3923 ICS->UserDefined.After.DirectBinding &&
3924 "Expected a direct reference binding!");
3925 return false;
3926 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003927 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003928 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003929 CastExpr::CK_UserDefinedConversion,
3930 cast<CXXMethodDecl>(Best->Function),
3931 Owned(Init));
3932 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003933
3934 if (CheckExceptionSpecCompatibility(Init, T1))
3935 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003936 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3937 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003938 }
3939 break;
3940
3941 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003942 if (ICS) {
3943 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3944 Cand != CandidateSet.end(); ++Cand)
3945 if (Cand->Viable)
3946 ICS->ConversionFunctionSet.push_back(Cand->Function);
3947 break;
3948 }
3949 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3950 << Init->getSourceRange();
3951 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003952 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003953
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003954 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003955 case OR_Deleted:
3956 // There was no suitable conversion, or we found a deleted
3957 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003958 break;
3959 }
3960 }
Mike Stump11289f42009-09-09 15:08:12 +00003961
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003962 if (BindsDirectly) {
3963 // C++ [dcl.init.ref]p4:
3964 // [...] In all cases where the reference-related or
3965 // reference-compatible relationship of two types is used to
3966 // establish the validity of a reference binding, and T1 is a
3967 // base class of T2, a program that necessitates such a binding
3968 // is ill-formed if T1 is an inaccessible (clause 11) or
3969 // ambiguous (10.2) base class of T2.
3970 //
3971 // Note that we only check this condition when we're allowed to
3972 // complain about errors, because we should not be checking for
3973 // ambiguity (or inaccessibility) unless the reference binding
3974 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003975 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003976 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00003977 Init->getSourceRange(),
3978 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00003979 else
3980 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003981 }
3982
3983 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003984 // type (i.e., cv1 shall be const), or the reference shall be an
3985 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003986 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003987 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003988 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003989 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3990 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003991 return true;
3992 }
3993
3994 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003995 // class type, and "cv1 T1" is reference-compatible with
3996 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003997 // following ways (the choice is implementation-defined):
3998 //
3999 // -- The reference is bound to the object represented by
4000 // the rvalue (see 3.10) or to a sub-object within that
4001 // object.
4002 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004003 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004004 // a constructor is called to copy the entire rvalue
4005 // object into the temporary. The reference is bound to
4006 // the temporary or to a sub-object within the
4007 // temporary.
4008 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004009 // The constructor that would be used to make the copy
4010 // shall be callable whether or not the copy is actually
4011 // done.
4012 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004013 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004014 // freedom, so we will always take the first option and never build
4015 // a temporary in this case. FIXME: We will, however, have to check
4016 // for the presence of a copy constructor in C++98/03 mode.
4017 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004018 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4019 if (ICS) {
4020 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4021 ICS->Standard.First = ICK_Identity;
4022 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4023 ICS->Standard.Third = ICK_Identity;
4024 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4025 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004026 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004027 ICS->Standard.DirectBinding = false;
4028 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004029 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004030 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004031 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4032 if (DerivedToBase)
4033 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004034 else if(CheckExceptionSpecCompatibility(Init, T1))
4035 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004036 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004037 }
4038 return false;
4039 }
4040
Eli Friedman44b83ee2009-08-05 19:21:58 +00004041 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004042 // initialized from the initializer expression using the
4043 // rules for a non-reference copy initialization (8.5). The
4044 // reference is then bound to the temporary. If T1 is
4045 // reference-related to T2, cv1 must be the same
4046 // cv-qualification as, or greater cv-qualification than,
4047 // cv2; otherwise, the program is ill-formed.
4048 if (RefRelationship == Ref_Related) {
4049 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4050 // we would be reference-compatible or reference-compatible with
4051 // added qualification. But that wasn't the case, so the reference
4052 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004053 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004054 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004055 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4056 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004057 return true;
4058 }
4059
Douglas Gregor576e98c2009-01-30 23:27:23 +00004060 // If at least one of the types is a class type, the types are not
4061 // related, and we aren't allowed any user conversions, the
4062 // reference binding fails. This case is important for breaking
4063 // recursion, since TryImplicitConversion below will attempt to
4064 // create a temporary through the use of a copy constructor.
4065 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4066 (T1->isRecordType() || T2->isRecordType())) {
4067 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004068 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004069 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4070 return true;
4071 }
4072
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004073 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004074 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004075 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004076 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004077 // When a parameter of reference type is not bound directly to
4078 // an argument expression, the conversion sequence is the one
4079 // required to convert the argument expression to the
4080 // underlying type of the reference according to
4081 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4082 // to copy-initializing a temporary of the underlying type with
4083 // the argument expression. Any difference in top-level
4084 // cv-qualification is subsumed by the initialization itself
4085 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004086 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4087 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004088 /*ForceRValue=*/false,
4089 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004090
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004091 // Of course, that's still a reference binding.
4092 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4093 ICS->Standard.ReferenceBinding = true;
4094 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004095 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004096 ImplicitConversionSequence::UserDefinedConversion) {
4097 ICS->UserDefined.After.ReferenceBinding = true;
4098 ICS->UserDefined.After.RRefBinding = isRValRef;
4099 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004100 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4101 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004102 ImplicitConversionSequence Conversions;
4103 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4104 false, false,
4105 Conversions);
4106 if (badConversion) {
4107 if ((Conversions.ConversionKind ==
4108 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004109 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004110 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004111 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4112 for (int j = Conversions.ConversionFunctionSet.size()-1;
4113 j >= 0; j--) {
4114 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4115 Diag(Func->getLocation(), diag::err_ovl_candidate);
4116 }
4117 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004118 else {
4119 if (isRValRef)
4120 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4121 << Init->getSourceRange();
4122 else
4123 Diag(DeclLoc, diag::err_invalid_initialization)
4124 << DeclType << Init->getType() << Init->getSourceRange();
4125 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004126 }
4127 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004128 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004129}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004130
4131/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4132/// of this overloaded operator is well-formed. If so, returns false;
4133/// otherwise, emits appropriate diagnostics and returns true.
4134bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004135 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004136 "Expected an overloaded operator declaration");
4137
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004138 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4139
Mike Stump11289f42009-09-09 15:08:12 +00004140 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004141 // The allocation and deallocation functions, operator new,
4142 // operator new[], operator delete and operator delete[], are
4143 // described completely in 3.7.3. The attributes and restrictions
4144 // found in the rest of this subclause do not apply to them unless
4145 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004146 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004147 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004148 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004149
4150 if (Op == OO_New || Op == OO_Array_New) {
4151 bool ret = false;
4152 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4153 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4154 QualType T = Context.getCanonicalType((*Param)->getType());
4155 if (!T->isDependentType() && SizeTy != T) {
4156 Diag(FnDecl->getLocation(),
4157 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4158 << SizeTy;
4159 ret = true;
4160 }
4161 }
4162 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4163 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4164 return Diag(FnDecl->getLocation(),
4165 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004166 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004167 return ret;
4168 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004169
4170 // C++ [over.oper]p6:
4171 // An operator function shall either be a non-static member
4172 // function or be a non-member function and have at least one
4173 // parameter whose type is a class, a reference to a class, an
4174 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004175 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4176 if (MethodDecl->isStatic())
4177 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004178 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004179 } else {
4180 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004181 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4182 ParamEnd = FnDecl->param_end();
4183 Param != ParamEnd; ++Param) {
4184 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004185 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4186 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004187 ClassOrEnumParam = true;
4188 break;
4189 }
4190 }
4191
Douglas Gregord69246b2008-11-17 16:14:12 +00004192 if (!ClassOrEnumParam)
4193 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004194 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004195 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004196 }
4197
4198 // C++ [over.oper]p8:
4199 // An operator function cannot have default arguments (8.3.6),
4200 // except where explicitly stated below.
4201 //
Mike Stump11289f42009-09-09 15:08:12 +00004202 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004203 // (C++ [over.call]p1).
4204 if (Op != OO_Call) {
4205 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4206 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004207 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004208 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004209 diag::err_operator_overload_default_arg)
4210 << FnDecl->getDeclName();
4211 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004212 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004213 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004214 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004215 }
4216 }
4217
Douglas Gregor6cf08062008-11-10 13:38:07 +00004218 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4219 { false, false, false }
4220#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4221 , { Unary, Binary, MemberOnly }
4222#include "clang/Basic/OperatorKinds.def"
4223 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004224
Douglas Gregor6cf08062008-11-10 13:38:07 +00004225 bool CanBeUnaryOperator = OperatorUses[Op][0];
4226 bool CanBeBinaryOperator = OperatorUses[Op][1];
4227 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004228
4229 // C++ [over.oper]p8:
4230 // [...] Operator functions cannot have more or fewer parameters
4231 // than the number required for the corresponding operator, as
4232 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004233 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004234 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004235 if (Op != OO_Call &&
4236 ((NumParams == 1 && !CanBeUnaryOperator) ||
4237 (NumParams == 2 && !CanBeBinaryOperator) ||
4238 (NumParams < 1) || (NumParams > 2))) {
4239 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004240 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004241 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004242 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004243 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004244 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004245 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004246 assert(CanBeBinaryOperator &&
4247 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004248 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004249 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004250
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004251 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004252 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004253 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004254
Douglas Gregord69246b2008-11-17 16:14:12 +00004255 // Overloaded operators other than operator() cannot be variadic.
4256 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004257 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004258 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004259 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004260 }
4261
4262 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004263 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4264 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004265 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004266 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004267 }
4268
4269 // C++ [over.inc]p1:
4270 // The user-defined function called operator++ implements the
4271 // prefix and postfix ++ operator. If this function is a member
4272 // function with no parameters, or a non-member function with one
4273 // parameter of class or enumeration type, it defines the prefix
4274 // increment operator ++ for objects of that type. If the function
4275 // is a member function with one parameter (which shall be of type
4276 // int) or a non-member function with two parameters (the second
4277 // of which shall be of type int), it defines the postfix
4278 // increment operator ++ for objects of that type.
4279 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4280 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4281 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004282 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004283 ParamIsInt = BT->getKind() == BuiltinType::Int;
4284
Chris Lattner2b786902008-11-21 07:50:02 +00004285 if (!ParamIsInt)
4286 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004287 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004288 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004289 }
4290
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004291 // Notify the class if it got an assignment operator.
4292 if (Op == OO_Equal) {
4293 // Would have returned earlier otherwise.
4294 assert(isa<CXXMethodDecl>(FnDecl) &&
4295 "Overloaded = not member, but not filtered.");
4296 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4297 Method->getParent()->addedAssignmentOperator(Context, Method);
4298 }
4299
Douglas Gregord69246b2008-11-17 16:14:12 +00004300 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004301}
Chris Lattner3b024a32008-12-17 07:09:26 +00004302
Douglas Gregor07665a62009-01-05 19:45:36 +00004303/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4304/// linkage specification, including the language and (if present)
4305/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4306/// the location of the language string literal, which is provided
4307/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4308/// the '{' brace. Otherwise, this linkage specification does not
4309/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004310Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4311 SourceLocation ExternLoc,
4312 SourceLocation LangLoc,
4313 const char *Lang,
4314 unsigned StrSize,
4315 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004316 LinkageSpecDecl::LanguageIDs Language;
4317 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4318 Language = LinkageSpecDecl::lang_c;
4319 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4320 Language = LinkageSpecDecl::lang_cxx;
4321 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004322 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004323 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004324 }
Mike Stump11289f42009-09-09 15:08:12 +00004325
Chris Lattner438e5012008-12-17 07:13:27 +00004326 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004327
Douglas Gregor07665a62009-01-05 19:45:36 +00004328 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004329 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004330 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004331 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004332 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004333 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004334}
4335
Douglas Gregor07665a62009-01-05 19:45:36 +00004336/// ActOnFinishLinkageSpecification - Completely the definition of
4337/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4338/// valid, it's the position of the closing '}' brace in a linkage
4339/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004340Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4341 DeclPtrTy LinkageSpec,
4342 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004343 if (LinkageSpec)
4344 PopDeclContext();
4345 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004346}
4347
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004348/// \brief Perform semantic analysis for the variable declaration that
4349/// occurs within a C++ catch clause, returning the newly-created
4350/// variable.
4351VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004352 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004353 IdentifierInfo *Name,
4354 SourceLocation Loc,
4355 SourceRange Range) {
4356 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004357
4358 // Arrays and functions decay.
4359 if (ExDeclType->isArrayType())
4360 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4361 else if (ExDeclType->isFunctionType())
4362 ExDeclType = Context.getPointerType(ExDeclType);
4363
4364 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4365 // The exception-declaration shall not denote a pointer or reference to an
4366 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004367 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004368 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004369 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004370 Invalid = true;
4371 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004372
Sebastian Redl54c04d42008-12-22 19:15:10 +00004373 QualType BaseType = ExDeclType;
4374 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004375 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004376 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004377 BaseType = Ptr->getPointeeType();
4378 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004379 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004380 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004381 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004382 BaseType = Ref->getPointeeType();
4383 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004384 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004385 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004386 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004387 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004388 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004389
Mike Stump11289f42009-09-09 15:08:12 +00004390 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004391 RequireNonAbstractType(Loc, ExDeclType,
4392 diag::err_abstract_type_in_decl,
4393 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004394 Invalid = true;
4395
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004396 // FIXME: Need to test for ability to copy-construct and destroy the
4397 // exception variable.
4398
Sebastian Redl9b244a82008-12-22 21:35:02 +00004399 // FIXME: Need to check for abstract classes.
4400
Mike Stump11289f42009-09-09 15:08:12 +00004401 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004402 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004403
4404 if (Invalid)
4405 ExDecl->setInvalidDecl();
4406
4407 return ExDecl;
4408}
4409
4410/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4411/// handler.
4412Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004413 DeclaratorInfo *DInfo = 0;
4414 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004415
4416 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004417 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004418 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004419 // The scope should be freshly made just for us. There is just no way
4420 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004421 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004422 if (PrevDecl->isTemplateParameter()) {
4423 // Maybe we will complain about the shadowed template parameter.
4424 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004425 }
4426 }
4427
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004428 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004429 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4430 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004431 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004432 }
4433
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004434 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004435 D.getIdentifier(),
4436 D.getIdentifierLoc(),
4437 D.getDeclSpec().getSourceRange());
4438
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004439 if (Invalid)
4440 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004441
Sebastian Redl54c04d42008-12-22 19:15:10 +00004442 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004443 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004444 PushOnScopeChains(ExDecl, S);
4445 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004446 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004447
Douglas Gregor758a8692009-06-17 21:51:59 +00004448 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004449 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004450}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004451
Mike Stump11289f42009-09-09 15:08:12 +00004452Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004453 ExprArg assertexpr,
4454 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004455 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004456 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004457 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4458
Anders Carlsson54b26982009-03-14 00:33:21 +00004459 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4460 llvm::APSInt Value(32);
4461 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4462 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4463 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004464 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004465 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004466
Anders Carlsson54b26982009-03-14 00:33:21 +00004467 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004468 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004469 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004470 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004471 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004472 }
4473 }
Mike Stump11289f42009-09-09 15:08:12 +00004474
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004475 assertexpr.release();
4476 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004477 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004478 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004479
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004480 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004481 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004482}
Sebastian Redlf769df52009-03-24 22:27:57 +00004483
John McCall11083da2009-09-16 22:47:08 +00004484/// Handle a friend type declaration. This works in tandem with
4485/// ActOnTag.
4486///
4487/// Notes on friend class templates:
4488///
4489/// We generally treat friend class declarations as if they were
4490/// declaring a class. So, for example, the elaborated type specifier
4491/// in a friend declaration is required to obey the restrictions of a
4492/// class-head (i.e. no typedefs in the scope chain), template
4493/// parameters are required to match up with simple template-ids, &c.
4494/// However, unlike when declaring a template specialization, it's
4495/// okay to refer to a template specialization without an empty
4496/// template parameter declaration, e.g.
4497/// friend class A<T>::B<unsigned>;
4498/// We permit this as a special case; if there are any template
4499/// parameters present at all, require proper matching, i.e.
4500/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004501Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004502 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004503 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004504
4505 assert(DS.isFriendSpecified());
4506 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4507
John McCall11083da2009-09-16 22:47:08 +00004508 // Try to convert the decl specifier to a type. This works for
4509 // friend templates because ActOnTag never produces a ClassTemplateDecl
4510 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004511 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004512 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4513 if (TheDeclarator.isInvalidType())
4514 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004515
John McCall11083da2009-09-16 22:47:08 +00004516 // This is definitely an error in C++98. It's probably meant to
4517 // be forbidden in C++0x, too, but the specification is just
4518 // poorly written.
4519 //
4520 // The problem is with declarations like the following:
4521 // template <T> friend A<T>::foo;
4522 // where deciding whether a class C is a friend or not now hinges
4523 // on whether there exists an instantiation of A that causes
4524 // 'foo' to equal C. There are restrictions on class-heads
4525 // (which we declare (by fiat) elaborated friend declarations to
4526 // be) that makes this tractable.
4527 //
4528 // FIXME: handle "template <> friend class A<T>;", which
4529 // is possibly well-formed? Who even knows?
4530 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4531 Diag(Loc, diag::err_tagless_friend_type_template)
4532 << DS.getSourceRange();
4533 return DeclPtrTy();
4534 }
4535
John McCallaa74a0c2009-08-28 07:59:38 +00004536 // C++ [class.friend]p2:
4537 // An elaborated-type-specifier shall be used in a friend declaration
4538 // for a class.*
4539 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004540 // This is one of the rare places in Clang where it's legitimate to
4541 // ask about the "spelling" of the type.
4542 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4543 // If we evaluated the type to a record type, suggest putting
4544 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004545 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004546 RecordDecl *RD = RT->getDecl();
4547
4548 std::string InsertionText = std::string(" ") + RD->getKindName();
4549
John McCallc3987482009-10-07 23:34:25 +00004550 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4551 << (unsigned) RD->getTagKind()
4552 << T
4553 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004554 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4555 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004556 return DeclPtrTy();
4557 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004558 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4559 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004560 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004561 }
4562 }
4563
John McCallc3987482009-10-07 23:34:25 +00004564 // Enum types cannot be friends.
4565 if (T->getAs<EnumType>()) {
4566 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4567 << SourceRange(DS.getFriendSpecLoc());
4568 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004569 }
John McCallaa74a0c2009-08-28 07:59:38 +00004570
John McCallaa74a0c2009-08-28 07:59:38 +00004571 // C++98 [class.friend]p1: A friend of a class is a function
4572 // or class that is not a member of the class . . .
4573 // But that's a silly restriction which nobody implements for
4574 // inner classes, and C++0x removes it anyway, so we only report
4575 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004576 if (!getLangOptions().CPlusPlus0x)
4577 if (const RecordType *RT = T->getAs<RecordType>())
4578 if (RT->getDecl()->getDeclContext() == CurContext)
4579 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004580
John McCall11083da2009-09-16 22:47:08 +00004581 Decl *D;
4582 if (TempParams.size())
4583 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4584 TempParams.size(),
4585 (TemplateParameterList**) TempParams.release(),
4586 T.getTypePtr(),
4587 DS.getFriendSpecLoc());
4588 else
4589 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4590 DS.getFriendSpecLoc());
4591 D->setAccess(AS_public);
4592 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004593
John McCall11083da2009-09-16 22:47:08 +00004594 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004595}
4596
John McCall2f212b32009-09-11 21:02:39 +00004597Sema::DeclPtrTy
4598Sema::ActOnFriendFunctionDecl(Scope *S,
4599 Declarator &D,
4600 bool IsDefinition,
4601 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004602 const DeclSpec &DS = D.getDeclSpec();
4603
4604 assert(DS.isFriendSpecified());
4605 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4606
4607 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004608 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004609 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004610
4611 // C++ [class.friend]p1
4612 // A friend of a class is a function or class....
4613 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004614 // It *doesn't* see through dependent types, which is correct
4615 // according to [temp.arg.type]p3:
4616 // If a declaration acquires a function type through a
4617 // type dependent on a template-parameter and this causes
4618 // a declaration that does not use the syntactic form of a
4619 // function declarator to have a function type, the program
4620 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004621 if (!T->isFunctionType()) {
4622 Diag(Loc, diag::err_unexpected_friend);
4623
4624 // It might be worthwhile to try to recover by creating an
4625 // appropriate declaration.
4626 return DeclPtrTy();
4627 }
4628
4629 // C++ [namespace.memdef]p3
4630 // - If a friend declaration in a non-local class first declares a
4631 // class or function, the friend class or function is a member
4632 // of the innermost enclosing namespace.
4633 // - The name of the friend is not found by simple name lookup
4634 // until a matching declaration is provided in that namespace
4635 // scope (either before or after the class declaration granting
4636 // friendship).
4637 // - If a friend function is called, its name may be found by the
4638 // name lookup that considers functions from namespaces and
4639 // classes associated with the types of the function arguments.
4640 // - When looking for a prior declaration of a class or a function
4641 // declared as a friend, scopes outside the innermost enclosing
4642 // namespace scope are not considered.
4643
John McCallaa74a0c2009-08-28 07:59:38 +00004644 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4645 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004646 assert(Name);
4647
John McCall07e91c02009-08-06 02:15:43 +00004648 // The context we found the declaration in, or in which we should
4649 // create the declaration.
4650 DeclContext *DC;
4651
4652 // FIXME: handle local classes
4653
4654 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004655 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4656 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004657 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004658 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004659 DC = computeDeclContext(ScopeQual);
4660
4661 // FIXME: handle dependent contexts
4662 if (!DC) return DeclPtrTy();
4663
John McCall1f82f242009-11-18 22:49:29 +00004664 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004665
4666 // If searching in that context implicitly found a declaration in
4667 // a different context, treat it like it wasn't found at all.
4668 // TODO: better diagnostics for this case. Suggesting the right
4669 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004670 // FIXME: getRepresentativeDecl() is not right here at all
4671 if (Previous.empty() ||
4672 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004673 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004674 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4675 return DeclPtrTy();
4676 }
4677
4678 // C++ [class.friend]p1: A friend of a class is a function or
4679 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004680 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004681 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4682
John McCall07e91c02009-08-06 02:15:43 +00004683 // Otherwise walk out to the nearest namespace scope looking for matches.
4684 } else {
4685 // TODO: handle local class contexts.
4686
4687 DC = CurContext;
4688 while (true) {
4689 // Skip class contexts. If someone can cite chapter and verse
4690 // for this behavior, that would be nice --- it's what GCC and
4691 // EDG do, and it seems like a reasonable intent, but the spec
4692 // really only says that checks for unqualified existing
4693 // declarations should stop at the nearest enclosing namespace,
4694 // not that they should only consider the nearest enclosing
4695 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004696 while (DC->isRecord())
4697 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004698
John McCall1f82f242009-11-18 22:49:29 +00004699 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004700
4701 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004702 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004703 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004704
John McCall07e91c02009-08-06 02:15:43 +00004705 if (DC->isFileContext()) break;
4706 DC = DC->getParent();
4707 }
4708
4709 // C++ [class.friend]p1: A friend of a class is a function or
4710 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004711 // C++0x changes this for both friend types and functions.
4712 // Most C++ 98 compilers do seem to give an error here, so
4713 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004714 if (!Previous.empty() && DC->Equals(CurContext)
4715 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004716 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4717 }
4718
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004719 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004720 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004721 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4722 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4723 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004724 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004725 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4726 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004727 return DeclPtrTy();
4728 }
John McCall07e91c02009-08-06 02:15:43 +00004729 }
4730
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004731 bool Redeclaration = false;
John McCall1f82f242009-11-18 22:49:29 +00004732 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004733 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004734 IsDefinition,
4735 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004736 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004737
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004738 assert(ND->getDeclContext() == DC);
4739 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004740
John McCall759e32b2009-08-31 22:39:49 +00004741 // Add the function declaration to the appropriate lookup tables,
4742 // adjusting the redeclarations list as necessary. We don't
4743 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004744 //
John McCall759e32b2009-08-31 22:39:49 +00004745 // Also update the scope-based lookup if the target context's
4746 // lookup context is in lexical scope.
4747 if (!CurContext->isDependentContext()) {
4748 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004749 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004750 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004751 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004752 }
John McCallaa74a0c2009-08-28 07:59:38 +00004753
4754 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004755 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004756 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004757 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004758 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004759
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004760 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004761}
4762
Chris Lattner83f095c2009-03-28 19:18:32 +00004763void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004764 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004765
Chris Lattner83f095c2009-03-28 19:18:32 +00004766 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004767 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4768 if (!Fn) {
4769 Diag(DelLoc, diag::err_deleted_non_function);
4770 return;
4771 }
4772 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4773 Diag(DelLoc, diag::err_deleted_decl_not_first);
4774 Diag(Prev->getLocation(), diag::note_previous_declaration);
4775 // If the declaration wasn't the first, we delete the function anyway for
4776 // recovery.
4777 }
4778 Fn->setDeleted();
4779}
Sebastian Redl4c018662009-04-27 21:33:24 +00004780
4781static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4782 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4783 ++CI) {
4784 Stmt *SubStmt = *CI;
4785 if (!SubStmt)
4786 continue;
4787 if (isa<ReturnStmt>(SubStmt))
4788 Self.Diag(SubStmt->getSourceRange().getBegin(),
4789 diag::err_return_in_constructor_handler);
4790 if (!isa<Expr>(SubStmt))
4791 SearchForReturnInStmt(Self, SubStmt);
4792 }
4793}
4794
4795void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4796 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4797 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4798 SearchForReturnInStmt(*this, Handler);
4799 }
4800}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004801
Mike Stump11289f42009-09-09 15:08:12 +00004802bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004803 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004804 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4805 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004806
4807 QualType CNewTy = Context.getCanonicalType(NewTy);
4808 QualType COldTy = Context.getCanonicalType(OldTy);
4809
Mike Stump11289f42009-09-09 15:08:12 +00004810 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004811 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004812 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004813
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004814 // Check if the return types are covariant
4815 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004816
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004817 /// Both types must be pointers or references to classes.
4818 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4819 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4820 NewClassTy = NewPT->getPointeeType();
4821 OldClassTy = OldPT->getPointeeType();
4822 }
4823 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4824 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4825 NewClassTy = NewRT->getPointeeType();
4826 OldClassTy = OldRT->getPointeeType();
4827 }
4828 }
Mike Stump11289f42009-09-09 15:08:12 +00004829
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004830 // The return types aren't either both pointers or references to a class type.
4831 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004832 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004833 diag::err_different_return_type_for_overriding_virtual_function)
4834 << New->getDeclName() << NewTy << OldTy;
4835 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004836
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004837 return true;
4838 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004839
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004840 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004841 // Check if the new class derives from the old class.
4842 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4843 Diag(New->getLocation(),
4844 diag::err_covariant_return_not_derived)
4845 << New->getDeclName() << NewTy << OldTy;
4846 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4847 return true;
4848 }
Mike Stump11289f42009-09-09 15:08:12 +00004849
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004850 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004851 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004852 diag::err_covariant_return_inaccessible_base,
4853 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4854 // FIXME: Should this point to the return type?
4855 New->getLocation(), SourceRange(), New->getDeclName())) {
4856 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4857 return true;
4858 }
4859 }
Mike Stump11289f42009-09-09 15:08:12 +00004860
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004861 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004862 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004863 Diag(New->getLocation(),
4864 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004865 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004866 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4867 return true;
4868 };
Mike Stump11289f42009-09-09 15:08:12 +00004869
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004870
4871 // The new class type must have the same or less qualifiers as the old type.
4872 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4873 Diag(New->getLocation(),
4874 diag::err_covariant_return_type_class_type_more_qualified)
4875 << New->getDeclName() << NewTy << OldTy;
4876 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4877 return true;
4878 };
Mike Stump11289f42009-09-09 15:08:12 +00004879
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004880 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004881}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004882
Alexis Hunt96d5c762009-11-21 08:43:09 +00004883bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4884 const CXXMethodDecl *Old)
4885{
4886 if (Old->hasAttr<FinalAttr>()) {
4887 Diag(New->getLocation(), diag::err_final_function_overridden)
4888 << New->getDeclName();
4889 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4890 return true;
4891 }
4892
4893 return false;
4894}
4895
Douglas Gregor21920e372009-12-01 17:24:26 +00004896/// \brief Mark the given method pure.
4897///
4898/// \param Method the method to be marked pure.
4899///
4900/// \param InitRange the source range that covers the "0" initializer.
4901bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
4902 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
4903 Method->setPure();
4904
4905 // A class is abstract if at least one function is pure virtual.
4906 Method->getParent()->setAbstract(true);
4907 return false;
4908 }
4909
4910 if (!Method->isInvalidDecl())
4911 Diag(Method->getLocation(), diag::err_non_virtual_pure)
4912 << Method->getDeclName() << InitRange;
4913 return true;
4914}
4915
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004916/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4917/// initializer for the declaration 'Dcl'.
4918/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4919/// static data member of class X, names should be looked up in the scope of
4920/// class X.
4921void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004922 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004923
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004924 Decl *D = Dcl.getAs<Decl>();
4925 // If there is no declaration, there was an error parsing it.
4926 if (D == 0)
4927 return;
4928
4929 // Check whether it is a declaration with a nested name specifier like
4930 // int foo::bar;
4931 if (!D->isOutOfLine())
4932 return;
Mike Stump11289f42009-09-09 15:08:12 +00004933
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004934 // C++ [basic.lookup.unqual]p13
4935 //
4936 // A name used in the definition of a static data member of class X
4937 // (after the qualified-id of the static member) is looked up as if the name
4938 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004939
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004940 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004941 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004942}
4943
4944/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4945/// initializer for the declaration 'Dcl'.
4946void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004947 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004948
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004949 Decl *D = Dcl.getAs<Decl>();
4950 // If there is no declaration, there was an error parsing it.
4951 if (D == 0)
4952 return;
4953
4954 // Check whether it is a declaration with a nested name specifier like
4955 // int foo::bar;
4956 if (!D->isOutOfLine())
4957 return;
4958
4959 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004960 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004961}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00004962
4963/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
4964/// C++ if/switch/while/for statement.
4965/// e.g: "if (int x = f()) {...}"
4966Action::DeclResult
4967Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
4968 // C++ 6.4p2:
4969 // The declarator shall not specify a function or an array.
4970 // The type-specifier-seq shall not contain typedef and shall not declare a
4971 // new class or enumeration.
4972 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4973 "Parser allowed 'typedef' as storage class of condition decl.");
4974
4975 DeclaratorInfo *DInfo = 0;
4976 TagDecl *OwnedTag = 0;
4977 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
4978
4979 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
4980 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
4981 // would be created and CXXConditionDeclExpr wants a VarDecl.
4982 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
4983 << D.getSourceRange();
4984 return DeclResult();
4985 } else if (OwnedTag && OwnedTag->isDefinition()) {
4986 // The type-specifier-seq shall not declare a new class or enumeration.
4987 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
4988 }
4989
4990 DeclPtrTy Dcl = ActOnDeclarator(S, D);
4991 if (!Dcl)
4992 return DeclResult();
4993
4994 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
4995 VD->setDeclaredInCondition(true);
4996 return Dcl;
4997}
Anders Carlssonf98849e2009-12-02 17:15:43 +00004998
4999void Sema::MaybeMarkVirtualImplicitMembersReferenced(SourceLocation Loc,
5000 CXXMethodDecl *MD) {
5001 // Ignore dependent types.
5002 if (MD->isDependentContext())
5003 return;
5004
5005 CXXRecordDecl *RD = MD->getParent();
5006 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5007 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
5008
5009 if (!KeyFunction) {
5010 // This record does not have a key function, so we assume that the vtable
5011 // will be emitted when it's used by the constructor.
5012 if (!isa<CXXConstructorDecl>(MD))
5013 return;
5014 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5015 // We don't have the right key function.
5016 return;
5017 }
5018
5019 if (CXXDestructorDecl *Dtor = RD->getDestructor(Context)) {
5020 if (Dtor->isImplicit() && Dtor->isVirtual())
5021 MarkDeclarationReferenced(Loc, Dtor);
5022 }
5023
5024 // FIXME: Need to handle the virtual assignment operator here too.
5025}