blob: 237a869f9084566687cc9b3251b7ac1328e4a8be [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000019#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000020#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000021#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000022#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000025#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000027#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000028#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000029#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000030#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000031
32using namespace clang;
33
Chris Lattner8123a952008-04-10 02:22:51 +000034//===----------------------------------------------------------------------===//
35// CheckDefaultArgumentVisitor
36//===----------------------------------------------------------------------===//
37
Chris Lattner9e979552008-04-12 23:52:44 +000038namespace {
39 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
40 /// the default argument of a parameter to determine whether it
41 /// contains any ill-formed subexpressions. For example, this will
42 /// diagnose the use of local variables or parameters within the
43 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000044 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000045 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000046 Expr *DefaultArg;
47 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 public:
Mike Stump1eb44332009-09-09 15:08:12 +000050 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000051 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-04-12 23:52:44 +000053 bool VisitExpr(Expr *Node);
54 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000055 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000056 };
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 /// VisitExpr - Visit all of the children of this expression.
59 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
60 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000061 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000062 E = Node->child_end(); I != E; ++I)
63 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000064 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000065 }
66
Chris Lattner9e979552008-04-12 23:52:44 +000067 /// VisitDeclRefExpr - Visit a reference to a declaration, to
68 /// determine whether this declaration can be used in the default
69 /// argument expression.
70 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000072 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
73 // C++ [dcl.fct.default]p9
74 // Default arguments are evaluated each time the function is
75 // called. The order of evaluation of function arguments is
76 // unspecified. Consequently, parameters of a function shall not
77 // be used in default argument expressions, even if they are not
78 // evaluated. Parameters of a function declared before a default
79 // argument expression are in scope and can hide namespace and
80 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000081 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000082 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000083 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000084 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000085 // C++ [dcl.fct.default]p7
86 // Local variables shall not be used in default argument
87 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000088 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000089 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000091 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000092 }
Chris Lattner8123a952008-04-10 02:22:51 +000093
Douglas Gregor3996f232008-11-04 13:41:56 +000094 return false;
95 }
Chris Lattner9e979552008-04-12 23:52:44 +000096
Douglas Gregor796da182008-11-04 14:32:21 +000097 /// VisitCXXThisExpr - Visit a C++ "this" expression.
98 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
99 // C++ [dcl.fct.default]p8:
100 // The keyword this shall not be used in a default argument of a
101 // member function.
102 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_this)
104 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106}
107
Anders Carlssoned961f92009-08-25 02:29:20 +0000108bool
109Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000110 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000111 QualType ParamType = Param->getType();
112
Anders Carlsson5653ca52009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000127 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000128 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000129 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000130
131 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Anders Carlssoned961f92009-08-25 02:29:20 +0000133 // Okay: add the default argument to the parameter
134 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Anders Carlssoned961f92009-08-25 02:29:20 +0000136 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlsson9351c172009-08-25 03:18:48 +0000138 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000139}
140
Chris Lattner8123a952008-04-10 02:22:51 +0000141/// ActOnParamDefaultArgument - Check whether the default argument
142/// provided for a function parameter is well-formed. If so, attach it
143/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000144void
Mike Stump1eb44332009-09-09 15:08:12 +0000145Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000146 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000147 if (!param || !defarg.get())
148 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Chris Lattnerb28317a2009-03-28 19:18:32 +0000150 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000151 UnparsedDefaultArgLocs.erase(Param);
152
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000153 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000154 QualType ParamType = Param->getType();
155
156 // Default arguments are only permitted in C++
157 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000158 Diag(EqualLoc, diag::err_param_default_argument)
159 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000160 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000161 return;
162 }
163
Anders Carlsson66e30672009-08-25 01:02:06 +0000164 // Check that the default argument is well-formed
165 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
166 if (DefaultArgChecker.Visit(DefaultArg.get())) {
167 Param->setInvalidDecl();
168 return;
169 }
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Anders Carlssoned961f92009-08-25 02:29:20 +0000171 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000172}
173
Douglas Gregor61366e92008-12-24 00:01:03 +0000174/// ActOnParamUnparsedDefaultArgument - We've seen a default
175/// argument for a function parameter, but we can't parse it yet
176/// because we're inside a class definition. Note that this default
177/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000178void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000179 SourceLocation EqualLoc,
180 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000181 if (!param)
182 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnerb28317a2009-03-28 19:18:32 +0000184 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000185 if (Param)
186 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Anders Carlsson5e300d12009-06-12 16:51:40 +0000188 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000189}
190
Douglas Gregor72b505b2008-12-16 21:30:33 +0000191/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
192/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000193void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000194 if (!param)
195 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Anders Carlsson5e300d12009-06-12 16:51:40 +0000197 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Anders Carlsson5e300d12009-06-12 16:51:40 +0000199 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000202}
203
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000204/// CheckExtraCXXDefaultArguments - Check for any extra default
205/// arguments in the declarator, which is not a function declaration
206/// or definition and therefore is not permitted to have default
207/// arguments. This routine should be invoked for every declarator
208/// that is not a function declaration or definition.
209void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
210 // C++ [dcl.fct.default]p3
211 // A default argument expression shall be specified only in the
212 // parameter-declaration-clause of a function declaration or in a
213 // template-parameter (14.1). It shall not be specified for a
214 // parameter pack. If it is specified in a
215 // parameter-declaration-clause, it shall not occur within a
216 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000217 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000218 DeclaratorChunk &chunk = D.getTypeObject(i);
219 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000220 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
221 ParmVarDecl *Param =
222 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000223 if (Param->hasUnparsedDefaultArg()) {
224 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000225 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
226 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
227 delete Toks;
228 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000229 } else if (Param->getDefaultArg()) {
230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << Param->getDefaultArg()->getSourceRange();
232 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000233 }
234 }
235 }
236 }
237}
238
Chris Lattner3d1cee32008-04-08 05:04:30 +0000239// MergeCXXFunctionDecl - Merge two declarations of the same C++
240// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000241// type. Subroutine of MergeFunctionDecl. Returns true if there was an
242// error, false otherwise.
243bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
244 bool Invalid = false;
245
Chris Lattner3d1cee32008-04-08 05:04:30 +0000246 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000247 // For non-template functions, default arguments can be added in
248 // later declarations of a function in the same
249 // scope. Declarations in different scopes have completely
250 // distinct sets of default arguments. That is, declarations in
251 // inner scopes do not acquire default arguments from
252 // declarations in outer scopes, and vice versa. In a given
253 // function declaration, all parameters subsequent to a
254 // parameter with a default argument shall have default
255 // arguments supplied in this or previous declarations. A
256 // default argument shall not be redefined by a later
257 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000258 //
259 // C++ [dcl.fct.default]p6:
260 // Except for member functions of class templates, the default arguments
261 // in a member function definition that appears outside of the class
262 // definition are added to the set of default arguments provided by the
263 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000264 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
265 ParmVarDecl *OldParam = Old->getParamDecl(p);
266 ParmVarDecl *NewParam = New->getParamDecl(p);
267
Douglas Gregor6cc15182009-09-11 18:44:32 +0000268 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000269 // FIXME: If the parameter doesn't have an identifier then the location
270 // points to the '=' which means that the fixit hint won't remove any
271 // extra spaces between the type and the '='.
272 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000273 if (NewParam->getIdentifier())
274 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000275
Mike Stump1eb44332009-09-09 15:08:12 +0000276 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000277 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000278 << NewParam->getDefaultArgRange()
279 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
280 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000281
282 // Look for the function declaration where the default argument was
283 // actually written, which may be a declaration prior to Old.
284 for (FunctionDecl *Older = Old->getPreviousDeclaration();
285 Older; Older = Older->getPreviousDeclaration()) {
286 if (!Older->getParamDecl(p)->hasDefaultArg())
287 break;
288
289 OldParam = Older->getParamDecl(p);
290 }
291
292 Diag(OldParam->getLocation(), diag::note_previous_definition)
293 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000294 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000295 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000296 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000297 if (OldParam->hasUninstantiatedDefaultArg())
298 NewParam->setUninstantiatedDefaultArg(
299 OldParam->getUninstantiatedDefaultArg());
300 else
301 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000302 } else if (NewParam->hasDefaultArg()) {
303 if (New->getDescribedFunctionTemplate()) {
304 // Paragraph 4, quoted above, only applies to non-template functions.
305 Diag(NewParam->getLocation(),
306 diag::err_param_default_argument_template_redecl)
307 << NewParam->getDefaultArgRange();
308 Diag(Old->getLocation(), diag::note_template_prev_declaration)
309 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000310 } else if (New->getTemplateSpecializationKind()
311 != TSK_ImplicitInstantiation &&
312 New->getTemplateSpecializationKind() != TSK_Undeclared) {
313 // C++ [temp.expr.spec]p21:
314 // Default function arguments shall not be specified in a declaration
315 // or a definition for one of the following explicit specializations:
316 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000317 // - the explicit specialization of a member function template;
318 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000319 // template where the class template specialization to which the
320 // member function specialization belongs is implicitly
321 // instantiated.
322 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
323 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
324 << New->getDeclName()
325 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000326 } else if (New->getDeclContext()->isDependentContext()) {
327 // C++ [dcl.fct.default]p6 (DR217):
328 // Default arguments for a member function of a class template shall
329 // be specified on the initial declaration of the member function
330 // within the class template.
331 //
332 // Reading the tea leaves a bit in DR217 and its reference to DR205
333 // leads me to the conclusion that one cannot add default function
334 // arguments for an out-of-line definition of a member function of a
335 // dependent type.
336 int WhichKind = 2;
337 if (CXXRecordDecl *Record
338 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
339 if (Record->getDescribedClassTemplate())
340 WhichKind = 0;
341 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
342 WhichKind = 1;
343 else
344 WhichKind = 2;
345 }
346
347 Diag(NewParam->getLocation(),
348 diag::err_param_default_argument_member_template_redecl)
349 << WhichKind
350 << NewParam->getDefaultArgRange();
351 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000352 }
353 }
354
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000355 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000356 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
357 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000358 Invalid = true;
359 }
360
Douglas Gregorcda9c672009-02-16 17:45:42 +0000361 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000362}
363
364/// CheckCXXDefaultArguments - Verify that the default arguments for a
365/// function declaration are well-formed according to C++
366/// [dcl.fct.default].
367void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
368 unsigned NumParams = FD->getNumParams();
369 unsigned p;
370
371 // Find first parameter with a default argument
372 for (p = 0; p < NumParams; ++p) {
373 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000374 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000375 break;
376 }
377
378 // C++ [dcl.fct.default]p4:
379 // In a given function declaration, all parameters
380 // subsequent to a parameter with a default argument shall
381 // have default arguments supplied in this or previous
382 // declarations. A default argument shall not be redefined
383 // by a later declaration (not even to the same value).
384 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000385 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000386 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000387 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 if (Param->isInvalidDecl())
389 /* We already complained about this parameter. */;
390 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000391 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000392 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000393 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000394 else
Mike Stump1eb44332009-09-09 15:08:12 +0000395 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 LastMissingDefaultArg = p;
399 }
400 }
401
402 if (LastMissingDefaultArg > 0) {
403 // Some default arguments were missing. Clear out all of the
404 // default arguments up to (and including) the last missing
405 // default argument, so that we leave the function parameters
406 // in a semantically valid state.
407 for (p = 0; p <= LastMissingDefaultArg; ++p) {
408 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000409 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000410 if (!Param->hasUnparsedDefaultArg())
411 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 Param->setDefaultArg(0);
413 }
414 }
415 }
416}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000417
Douglas Gregorb48fe382008-10-31 09:07:45 +0000418/// isCurrentClassName - Determine whether the identifier II is the
419/// name of the class type currently being defined. In the case of
420/// nested classes, this will only return true if II is the name of
421/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000422bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
423 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000424 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000425 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000426 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
428 } else
429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
430
431 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000432 return &II == CurDecl->getIdentifier();
433 else
434 return false;
435}
436
Mike Stump1eb44332009-09-09 15:08:12 +0000437/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000438///
439/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
440/// and returns NULL otherwise.
441CXXBaseSpecifier *
442Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
443 SourceRange SpecifierRange,
444 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000445 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000446 SourceLocation BaseLoc) {
447 // C++ [class.union]p1:
448 // A union shall not have base classes.
449 if (Class->isUnion()) {
450 Diag(Class->getLocation(), diag::err_base_clause_on_union)
451 << SpecifierRange;
452 return 0;
453 }
454
455 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000456 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000457 Class->getTagKind() == RecordDecl::TK_class,
458 Access, BaseType);
459
460 // Base specifiers must be record types.
461 if (!BaseType->isRecordType()) {
462 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
463 return 0;
464 }
465
466 // C++ [class.union]p1:
467 // A union shall not be used as a base class.
468 if (BaseType->isUnionType()) {
469 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.derived]p2:
474 // The class-name in a base-specifier shall not be an incompletely
475 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000476 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000477 PDiag(diag::err_incomplete_base_class)
478 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000479 return 0;
480
Eli Friedman1d954f62009-08-15 21:55:26 +0000481 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000482 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000483 assert(BaseDecl && "Record type has no declaration");
484 BaseDecl = BaseDecl->getDefinition(Context);
485 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000486 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
487 assert(CXXBaseDecl && "Base type is not a C++ type");
488 if (!CXXBaseDecl->isEmpty())
489 Class->setEmpty(false);
490 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000491 Class->setPolymorphic(true);
492
493 // C++ [dcl.init.aggr]p1:
494 // An aggregate is [...] a class with [...] no base classes [...].
495 Class->setAggregate(false);
496 Class->setPOD(false);
497
Anders Carlsson347ba892009-04-16 00:08:20 +0000498 if (Virtual) {
499 // C++ [class.ctor]p5:
500 // A constructor is trivial if its class has no virtual base classes.
501 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000502
503 // C++ [class.copy]p6:
504 // A copy constructor is trivial if its class has no virtual base classes.
505 Class->setHasTrivialCopyConstructor(false);
506
507 // C++ [class.copy]p11:
508 // A copy assignment operator is trivial if its class has no virtual
509 // base classes.
510 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000511
512 // C++0x [meta.unary.prop] is_empty:
513 // T is a class type, but not a union type, with ... no virtual base
514 // classes
515 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000516 } else {
517 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000518 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000519 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000520 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
521 Class->setHasTrivialConstructor(false);
522
523 // C++ [class.copy]p6:
524 // A copy constructor is trivial if all the direct base classes of its
525 // class have trivial copy constructors.
526 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
527 Class->setHasTrivialCopyConstructor(false);
528
529 // C++ [class.copy]p11:
530 // A copy assignment operator is trivial if all the direct base classes
531 // of its class have trivial copy assignment operators.
532 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
533 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000534 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000535
536 // C++ [class.ctor]p3:
537 // A destructor is trivial if all the direct base classes of its class
538 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000539 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
540 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Douglas Gregor2943aed2009-03-03 04:44:36 +0000542 // Create the base specifier.
543 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000544 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
545 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 Access, BaseType);
547}
548
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000549/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
550/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000551/// example:
552/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000553/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000554Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000555Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000556 bool Virtual, AccessSpecifier Access,
557 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000558 if (!classdecl)
559 return true;
560
Douglas Gregor40808ce2009-03-09 23:48:35 +0000561 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000562 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000563 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000564 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
565 Virtual, Access,
566 BaseType, BaseLoc))
567 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregor2943aed2009-03-03 04:44:36 +0000569 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000570}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572/// \brief Performs the actual work of attaching the given base class
573/// specifiers to a C++ class.
574bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
575 unsigned NumBases) {
576 if (NumBases == 0)
577 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000578
579 // Used to keep track of which base types we have already seen, so
580 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000581 // that the key is always the unqualified canonical type of the base
582 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
584
585 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000586 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000587 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000588 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000589 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000590 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000591 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000592
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000593 if (KnownBaseTypes[NewBaseType]) {
594 // C++ [class.mi]p3:
595 // A class shall not be specified as a direct base class of a
596 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000598 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000599 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000600 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000601
602 // Delete the duplicate base class specifier; we're going to
603 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000604 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000605
606 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000607 } else {
608 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 KnownBaseTypes[NewBaseType] = Bases[idx];
610 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000611 }
612 }
613
614 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000615 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000616
617 // Delete the remaining (good) base class specifiers, since their
618 // data has been copied into the CXXRecordDecl.
619 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000620 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621
622 return Invalid;
623}
624
625/// ActOnBaseSpecifiers - Attach the given base specifiers to the
626/// class, after checking whether there are any duplicate base
627/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000628void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 unsigned NumBases) {
630 if (!ClassDecl || !Bases || !NumBases)
631 return;
632
633 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000634 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000636}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000637
Douglas Gregora8f32e02009-10-06 17:59:45 +0000638/// \brief Determine whether the type \p Derived is a C++ class that is
639/// derived from the type \p Base.
640bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
641 if (!getLangOptions().CPlusPlus)
642 return false;
643
644 const RecordType *DerivedRT = Derived->getAs<RecordType>();
645 if (!DerivedRT)
646 return false;
647
648 const RecordType *BaseRT = Base->getAs<RecordType>();
649 if (!BaseRT)
650 return false;
651
652 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
653 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
654 return DerivedRD->isDerivedFrom(BaseRD);
655}
656
657/// \brief Determine whether the type \p Derived is a C++ class that is
658/// derived from the type \p Base.
659bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
660 if (!getLangOptions().CPlusPlus)
661 return false;
662
663 const RecordType *DerivedRT = Derived->getAs<RecordType>();
664 if (!DerivedRT)
665 return false;
666
667 const RecordType *BaseRT = Base->getAs<RecordType>();
668 if (!BaseRT)
669 return false;
670
671 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
672 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
673 return DerivedRD->isDerivedFrom(BaseRD, Paths);
674}
675
676/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
677/// conversion (where Derived and Base are class types) is
678/// well-formed, meaning that the conversion is unambiguous (and
679/// that all of the base classes are accessible). Returns true
680/// and emits a diagnostic if the code is ill-formed, returns false
681/// otherwise. Loc is the location where this routine should point to
682/// if there is an error, and Range is the source range to highlight
683/// if there is an error.
684bool
685Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
686 unsigned InaccessibleBaseID,
687 unsigned AmbigiousBaseConvID,
688 SourceLocation Loc, SourceRange Range,
689 DeclarationName Name) {
690 // First, determine whether the path from Derived to Base is
691 // ambiguous. This is slightly more expensive than checking whether
692 // the Derived to Base conversion exists, because here we need to
693 // explore multiple paths to determine if there is an ambiguity.
694 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
695 /*DetectVirtual=*/false);
696 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
697 assert(DerivationOkay &&
698 "Can only be used with a derived-to-base conversion");
699 (void)DerivationOkay;
700
701 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000702 if (InaccessibleBaseID == 0)
703 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704 // Check that the base class can be accessed.
705 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
706 Name);
707 }
708
709 // We know that the derived-to-base conversion is ambiguous, and
710 // we're going to produce a diagnostic. Perform the derived-to-base
711 // search just one more time to compute all of the possible paths so
712 // that we can print them out. This is more expensive than any of
713 // the previous derived-to-base checks we've done, but at this point
714 // performance isn't as much of an issue.
715 Paths.clear();
716 Paths.setRecordingPaths(true);
717 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
718 assert(StillOkay && "Can only be used with a derived-to-base conversion");
719 (void)StillOkay;
720
721 // Build up a textual representation of the ambiguous paths, e.g.,
722 // D -> B -> A, that will be used to illustrate the ambiguous
723 // conversions in the diagnostic. We only print one of the paths
724 // to each base class subobject.
725 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
726
727 Diag(Loc, AmbigiousBaseConvID)
728 << Derived << Base << PathDisplayStr << Range << Name;
729 return true;
730}
731
732bool
733Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000734 SourceLocation Loc, SourceRange Range,
735 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000736 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000737 IgnoreAccess ? 0 :
738 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000739 diag::err_ambiguous_derived_to_base_conv,
740 Loc, Range, DeclarationName());
741}
742
743
744/// @brief Builds a string representing ambiguous paths from a
745/// specific derived class to different subobjects of the same base
746/// class.
747///
748/// This function builds a string that can be used in error messages
749/// to show the different paths that one can take through the
750/// inheritance hierarchy to go from the derived class to different
751/// subobjects of a base class. The result looks something like this:
752/// @code
753/// struct D -> struct B -> struct A
754/// struct D -> struct C -> struct A
755/// @endcode
756std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
757 std::string PathDisplayStr;
758 std::set<unsigned> DisplayedPaths;
759 for (CXXBasePaths::paths_iterator Path = Paths.begin();
760 Path != Paths.end(); ++Path) {
761 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
762 // We haven't displayed a path to this particular base
763 // class subobject yet.
764 PathDisplayStr += "\n ";
765 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
766 for (CXXBasePath::const_iterator Element = Path->begin();
767 Element != Path->end(); ++Element)
768 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
769 }
770 }
771
772 return PathDisplayStr;
773}
774
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000775//===----------------------------------------------------------------------===//
776// C++ class member Handling
777//===----------------------------------------------------------------------===//
778
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000779/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
780/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
781/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000782/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000783Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000784Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000785 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000786 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000787 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000788 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000789 Expr *BitWidth = static_cast<Expr*>(BW);
790 Expr *Init = static_cast<Expr*>(InitExpr);
791 SourceLocation Loc = D.getIdentifierLoc();
792
Sebastian Redl669d5d72008-11-14 23:42:31 +0000793 bool isFunc = D.isFunctionDeclarator();
794
John McCall67d1a672009-08-06 02:15:43 +0000795 assert(!DS.isFriendSpecified());
796
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000797 // C++ 9.2p6: A member shall not be declared to have automatic storage
798 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000799 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
800 // data members and cannot be applied to names declared const or static,
801 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000802 switch (DS.getStorageClassSpec()) {
803 case DeclSpec::SCS_unspecified:
804 case DeclSpec::SCS_typedef:
805 case DeclSpec::SCS_static:
806 // FALL THROUGH.
807 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000808 case DeclSpec::SCS_mutable:
809 if (isFunc) {
810 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000811 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000812 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000813 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Sebastian Redla11f42f2008-11-17 23:24:37 +0000815 // FIXME: It would be nicer if the keyword was ignored only for this
816 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000817 D.getMutableDeclSpec().ClearStorageClassSpecs();
818 } else {
819 QualType T = GetTypeForDeclarator(D, S);
820 diag::kind err = static_cast<diag::kind>(0);
821 if (T->isReferenceType())
822 err = diag::err_mutable_reference;
823 else if (T.isConstQualified())
824 err = diag::err_mutable_const;
825 if (err != 0) {
826 if (DS.getStorageClassSpecLoc().isValid())
827 Diag(DS.getStorageClassSpecLoc(), err);
828 else
829 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000830 // FIXME: It would be nicer if the keyword was ignored only for this
831 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000832 D.getMutableDeclSpec().ClearStorageClassSpecs();
833 }
834 }
835 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000836 default:
837 if (DS.getStorageClassSpecLoc().isValid())
838 Diag(DS.getStorageClassSpecLoc(),
839 diag::err_storageclass_invalid_for_member);
840 else
841 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
842 D.getMutableDeclSpec().ClearStorageClassSpecs();
843 }
844
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000845 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000846 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000847 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000848 // Check also for this case:
849 //
850 // typedef int f();
851 // f a;
852 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000853 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000854 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000855 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000856
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
858 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000859 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000860
861 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000862 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000863 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000864 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
865 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000866 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000867 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000868 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
869 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000870 if (!Member) {
871 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000872 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000873 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000874
875 // Non-instance-fields can't have a bitfield.
876 if (BitWidth) {
877 if (Member->isInvalidDecl()) {
878 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000879 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000880 // C++ 9.6p3: A bit-field shall not be a static member.
881 // "static member 'A' cannot be a bit-field"
882 Diag(Loc, diag::err_static_not_bitfield)
883 << Name << BitWidth->getSourceRange();
884 } else if (isa<TypedefDecl>(Member)) {
885 // "typedef member 'x' cannot be a bit-field"
886 Diag(Loc, diag::err_typedef_not_bitfield)
887 << Name << BitWidth->getSourceRange();
888 } else {
889 // A function typedef ("typedef int f(); f a;").
890 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
891 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000892 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000893 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000894 }
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner8b963ef2009-03-05 23:01:03 +0000896 DeleteExpr(BitWidth);
897 BitWidth = 0;
898 Member->setInvalidDecl();
899 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000900
901 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Douglas Gregor37b372b2009-08-20 22:52:58 +0000903 // If we have declared a member function template, set the access of the
904 // templated declaration as well.
905 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
906 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000907 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000908
Douglas Gregor10bd3682008-11-17 22:58:34 +0000909 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000910
Douglas Gregor021c3b32009-03-11 23:00:04 +0000911 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000912 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000913 if (Deleted) // FIXME: Source location is not very good.
914 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000915
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000917 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000918 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000919 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000920 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921}
922
Douglas Gregor7ad83902008-11-05 04:29:56 +0000923/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000924Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000925Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000926 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000927 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000928 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000929 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000930 SourceLocation IdLoc,
931 SourceLocation LParenLoc,
932 ExprTy **Args, unsigned NumArgs,
933 SourceLocation *CommaLocs,
934 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000935 if (!ConstructorD)
936 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000938 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
940 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000941 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000942 if (!Constructor) {
943 // The user wrote a constructor initializer on a function that is
944 // not a C++ constructor. Ignore the error for now, because we may
945 // have more member initializers coming; we'll diagnose it just
946 // once in ActOnMemInitializers.
947 return true;
948 }
949
950 CXXRecordDecl *ClassDecl = Constructor->getParent();
951
952 // C++ [class.base.init]p2:
953 // Names in a mem-initializer-id are looked up in the scope of the
954 // constructor’s class and, if not found in that scope, are looked
955 // up in the scope containing the constructor’s
956 // definition. [Note: if the constructor’s class contains a member
957 // with the same name as a direct or virtual base class of the
958 // class, a mem-initializer-id naming the member or base class and
959 // composed of a single identifier refers to the class member. A
960 // mem-initializer-id for the hidden base class may be specified
961 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000962 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000963 // Look for a member, first.
964 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000965 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000966 = ClassDecl->lookup(MemberOrBase);
967 if (Result.first != Result.second)
968 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000970 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000971
Eli Friedman59c04372009-07-29 19:44:27 +0000972 if (Member)
973 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
974 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000975 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000976 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000977 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000978 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000979 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000980 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
981 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000983 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000984
Eli Friedman59c04372009-07-29 19:44:27 +0000985 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
986 RParenLoc, ClassDecl);
987}
988
John McCallb4190042009-11-04 23:02:40 +0000989/// Checks an initializer expression for use of uninitialized fields, such as
990/// containing the field that is being initialized. Returns true if there is an
991/// uninitialized field was used an updates the SourceLocation parameter; false
992/// otherwise.
993static bool InitExprContainsUninitializedFields(const Stmt* S,
994 const FieldDecl* LhsField,
995 SourceLocation* L) {
996 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
997 if (ME) {
998 const NamedDecl* RhsField = ME->getMemberDecl();
999 if (RhsField == LhsField) {
1000 // Initializing a field with itself. Throw a warning.
1001 // But wait; there are exceptions!
1002 // Exception #1: The field may not belong to this record.
1003 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1004 const Expr* base = ME->getBase();
1005 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1006 // Even though the field matches, it does not belong to this record.
1007 return false;
1008 }
1009 // None of the exceptions triggered; return true to indicate an
1010 // uninitialized field was used.
1011 *L = ME->getMemberLoc();
1012 return true;
1013 }
1014 }
1015 bool found = false;
1016 for (Stmt::const_child_iterator it = S->child_begin();
1017 it != S->child_end() && found == false;
1018 ++it) {
1019 if (isa<CallExpr>(S)) {
1020 // Do not descend into function calls or constructors, as the use
1021 // of an uninitialized field may be valid. One would have to inspect
1022 // the contents of the function/ctor to determine if it is safe or not.
1023 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1024 // may be safe, depending on what the function/ctor does.
1025 continue;
1026 }
1027 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1028 }
1029 return found;
1030}
1031
Eli Friedman59c04372009-07-29 19:44:27 +00001032Sema::MemInitResult
1033Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1034 unsigned NumArgs, SourceLocation IdLoc,
1035 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001036 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1037 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1038 ExprTemporaries.clear();
1039
John McCallb4190042009-11-04 23:02:40 +00001040 // Diagnose value-uses of fields to initialize themselves, e.g.
1041 // foo(foo)
1042 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001043 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001044 for (unsigned i = 0; i < NumArgs; ++i) {
1045 SourceLocation L;
1046 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1047 // FIXME: Return true in the case when other fields are used before being
1048 // uninitialized. For example, let this field be the i'th field. When
1049 // initializing the i'th field, throw a warning if any of the >= i'th
1050 // fields are used, as they are not yet initialized.
1051 // Right now we are only handling the case where the i'th field uses
1052 // itself in its initializer.
1053 Diag(L, diag::warn_field_is_uninit);
1054 }
1055 }
1056
Eli Friedman59c04372009-07-29 19:44:27 +00001057 bool HasDependentArg = false;
1058 for (unsigned i = 0; i < NumArgs; i++)
1059 HasDependentArg |= Args[i]->isTypeDependent();
1060
1061 CXXConstructorDecl *C = 0;
1062 QualType FieldType = Member->getType();
1063 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1064 FieldType = Array->getElementType();
1065 if (FieldType->isDependentType()) {
1066 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001067 } else if (FieldType->isRecordType()) {
1068 // Member is a record (struct/union/class), so pass the initializer
1069 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001070 if (!HasDependentArg) {
1071 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1072
1073 C = PerformInitializationByConstructor(FieldType,
1074 MultiExprArg(*this,
1075 (void**)Args,
1076 NumArgs),
1077 IdLoc,
1078 SourceRange(IdLoc, RParenLoc),
1079 Member->getDeclName(), IK_Direct,
1080 ConstructorArgs);
1081
1082 if (C) {
1083 // Take over the constructor arguments as our own.
1084 NumArgs = ConstructorArgs.size();
1085 Args = (Expr **)ConstructorArgs.take();
1086 }
1087 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001088 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001089 // The member type is not a record type (or an array of record
1090 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001091 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001092 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1093 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001094 Expr *NewExp;
1095 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001096 if (FieldType->isReferenceType()) {
1097 Diag(IdLoc, diag::err_null_intialized_reference_member)
1098 << Member->getDeclName();
1099 return Diag(Member->getLocation(), diag::note_declared_at);
1100 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001101 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1102 NumArgs = 1;
1103 }
1104 else
1105 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001106 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1107 return true;
1108 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001109 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001110
1111 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1112 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1113 ExprTemporaries.clear();
1114
Eli Friedman59c04372009-07-29 19:44:27 +00001115 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +00001116 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001117 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001118}
1119
1120Sema::MemInitResult
1121Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1122 unsigned NumArgs, SourceLocation IdLoc,
1123 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1124 bool HasDependentArg = false;
1125 for (unsigned i = 0; i < NumArgs; i++)
1126 HasDependentArg |= Args[i]->isTypeDependent();
1127
1128 if (!BaseType->isDependentType()) {
1129 if (!BaseType->isRecordType())
1130 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1131 << BaseType << SourceRange(IdLoc, RParenLoc);
1132
1133 // C++ [class.base.init]p2:
1134 // [...] Unless the mem-initializer-id names a nonstatic data
1135 // member of the constructor’s class or a direct or virtual base
1136 // of that class, the mem-initializer is ill-formed. A
1137 // mem-initializer-list can initialize a base class using any
1138 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Eli Friedman59c04372009-07-29 19:44:27 +00001140 // First, check for a direct base class.
1141 const CXXBaseSpecifier *DirectBaseSpec = 0;
1142 for (CXXRecordDecl::base_class_const_iterator Base =
1143 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001144 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001145 // We found a direct base of this type. That's what we're
1146 // initializing.
1147 DirectBaseSpec = &*Base;
1148 break;
1149 }
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Eli Friedman59c04372009-07-29 19:44:27 +00001152 // Check for a virtual base class.
1153 // FIXME: We might be able to short-circuit this if we know in advance that
1154 // there are no virtual bases.
1155 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1156 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1157 // We haven't found a base yet; search the class hierarchy for a
1158 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001159 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1160 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001161 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001162 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001163 Path != Paths.end(); ++Path) {
1164 if (Path->back().Base->isVirtual()) {
1165 VirtualBaseSpec = Path->back().Base;
1166 break;
1167 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001168 }
1169 }
1170 }
Eli Friedman59c04372009-07-29 19:44:27 +00001171
1172 // C++ [base.class.init]p2:
1173 // If a mem-initializer-id is ambiguous because it designates both
1174 // a direct non-virtual base class and an inherited virtual base
1175 // class, the mem-initializer is ill-formed.
1176 if (DirectBaseSpec && VirtualBaseSpec)
1177 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1178 << BaseType << SourceRange(IdLoc, RParenLoc);
1179 // C++ [base.class.init]p2:
1180 // Unless the mem-initializer-id names a nonstatic data membeer of the
1181 // constructor's class ot a direst or virtual base of that class, the
1182 // mem-initializer is ill-formed.
1183 if (!DirectBaseSpec && !VirtualBaseSpec)
1184 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1185 << BaseType << ClassDecl->getNameAsCString()
1186 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001187 }
1188
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001189 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001190 if (!BaseType->isDependentType() && !HasDependentArg) {
1191 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001192 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001193 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1194
1195 C = PerformInitializationByConstructor(BaseType,
1196 MultiExprArg(*this,
1197 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +00001198 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001199 Name, IK_Direct,
1200 ConstructorArgs);
1201 if (C) {
1202 // Take over the constructor arguments as our own.
1203 NumArgs = ConstructorArgs.size();
1204 Args = (Expr **)ConstructorArgs.take();
1205 }
Eli Friedman59c04372009-07-29 19:44:27 +00001206 }
1207
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001208 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1209 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1210 ExprTemporaries.clear();
1211
Mike Stump1eb44332009-09-09 15:08:12 +00001212 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +00001213 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001214}
1215
Eli Friedman80c30da2009-11-09 19:20:36 +00001216bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001217Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001218 CXXBaseOrMemberInitializer **Initializers,
1219 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001220 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001221 // We need to build the initializer AST according to order of construction
1222 // and not what user specified in the Initializers list.
1223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1224 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1225 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1226 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001227 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001229 for (unsigned i = 0; i < NumInitializers; i++) {
1230 CXXBaseOrMemberInitializer *Member = Initializers[i];
1231 if (Member->isBaseInitializer()) {
1232 if (Member->getBaseClass()->isDependentType())
1233 HasDependentBaseInit = true;
1234 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1235 } else {
1236 AllBaseFields[Member->getMember()] = Member;
1237 }
1238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001240 if (HasDependentBaseInit) {
1241 // FIXME. This does not preserve the ordering of the initializers.
1242 // Try (with -Wreorder)
1243 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001244 // template<class X> struct B : A<X> {
1245 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001246 // int x1;
1247 // };
1248 // B<int> x;
1249 // On seeing one dependent type, we should essentially exit this routine
1250 // while preserving user-declared initializer list. When this routine is
1251 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001252 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001254 // If we have a dependent base initialization, we can't determine the
1255 // association between initializers and bases; just dump the known
1256 // initializers into the list, and don't try to deal with other bases.
1257 for (unsigned i = 0; i < NumInitializers; i++) {
1258 CXXBaseOrMemberInitializer *Member = Initializers[i];
1259 if (Member->isBaseInitializer())
1260 AllToInit.push_back(Member);
1261 }
1262 } else {
1263 // Push virtual bases before others.
1264 for (CXXRecordDecl::base_class_iterator VBase =
1265 ClassDecl->vbases_begin(),
1266 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1267 if (VBase->getType()->isDependentType())
1268 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001269 if (CXXBaseOrMemberInitializer *Value
1270 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001271 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001272 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001273 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001274 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001275 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001276 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001277 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001278 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001279 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1280 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1281 << 0 << VBase->getType();
1282 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1283 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001284 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001285 continue;
1286 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001287
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001288 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1289 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1290 Constructor->getLocation(), CtorArgs))
1291 continue;
1292
1293 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1294
Anders Carlsson8db68da2009-11-13 20:11:49 +00001295 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1296 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1297 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001298 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001299 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1300 CtorArgs.takeAs<Expr>(),
1301 CtorArgs.size(), Ctor,
1302 SourceLocation(),
1303 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001304 AllToInit.push_back(Member);
1305 }
1306 }
Mike Stump1eb44332009-09-09 15:08:12 +00001307
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001308 for (CXXRecordDecl::base_class_iterator Base =
1309 ClassDecl->bases_begin(),
1310 E = ClassDecl->bases_end(); Base != E; ++Base) {
1311 // Virtuals are in the virtual base list and already constructed.
1312 if (Base->isVirtual())
1313 continue;
1314 // Skip dependent types.
1315 if (Base->getType()->isDependentType())
1316 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001317 if (CXXBaseOrMemberInitializer *Value
1318 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001319 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001320 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001321 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001322 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001323 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001324 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001325 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001326 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001327 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1328 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1329 << 0 << Base->getType();
1330 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1331 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001332 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001333 continue;
1334 }
1335
1336 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1337 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1338 Constructor->getLocation(), CtorArgs))
1339 continue;
1340
1341 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001342
Anders Carlsson8db68da2009-11-13 20:11:49 +00001343 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1344 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1345 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001346 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001347 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1348 CtorArgs.takeAs<Expr>(),
1349 CtorArgs.size(), Ctor,
1350 SourceLocation(),
1351 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001352 AllToInit.push_back(Member);
1353 }
1354 }
1355 }
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001357 // non-static data members.
1358 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1359 E = ClassDecl->field_end(); Field != E; ++Field) {
1360 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001361 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001362 Field->getType()->getAs<RecordType>()) {
1363 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001364 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001365 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001366 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1367 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1368 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1369 // set to the anonymous union data member used in the initializer
1370 // list.
1371 Value->setMember(*Field);
1372 Value->setAnonUnionMember(*FA);
1373 AllToInit.push_back(Value);
1374 break;
1375 }
1376 }
1377 }
1378 continue;
1379 }
1380 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1381 AllToInit.push_back(Value);
1382 continue;
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Eli Friedman49c16da2009-11-09 01:05:47 +00001385 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001386 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001387
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001388 QualType FT = Context.getBaseElementType((*Field)->getType());
1389 if (const RecordType* RT = FT->getAs<RecordType>()) {
1390 CXXConstructorDecl *Ctor =
1391 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001392 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001393 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1394 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1395 << 1 << (*Field)->getDeclName();
1396 Diag(Field->getLocation(), diag::note_field_decl);
1397 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1398 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001399 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001400 continue;
1401 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001402
1403 if (FT.isConstQualified() && Ctor->isTrivial()) {
1404 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1405 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1406 << 1 << (*Field)->getDeclName();
1407 Diag((*Field)->getLocation(), diag::note_declared_at);
1408 HadError = true;
1409 }
1410
1411 // Don't create initializers for trivial constructors, since they don't
1412 // actually need to be run.
1413 if (Ctor->isTrivial())
1414 continue;
1415
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001416 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1417 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1418 Constructor->getLocation(), CtorArgs))
1419 continue;
1420
Anders Carlsson8db68da2009-11-13 20:11:49 +00001421 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1422 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1423 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001424 CXXBaseOrMemberInitializer *Member =
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001425 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1426 CtorArgs.size(), Ctor,
1427 SourceLocation(),
1428 SourceLocation());
1429
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001430 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001431 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001432 }
1433 else if (FT->isReferenceType()) {
1434 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001435 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1436 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001437 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001438 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001439 }
1440 else if (FT.isConstQualified()) {
1441 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001442 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1443 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001444 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001445 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001446 }
1447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001449 NumInitializers = AllToInit.size();
1450 if (NumInitializers > 0) {
1451 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1452 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1453 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001455 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1456 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1457 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1458 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001459
1460 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001461}
1462
Eli Friedman6347f422009-07-21 19:28:10 +00001463static void *GetKeyForTopLevelField(FieldDecl *Field) {
1464 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001465 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001466 if (RT->getDecl()->isAnonymousStructOrUnion())
1467 return static_cast<void *>(RT->getDecl());
1468 }
1469 return static_cast<void *>(Field);
1470}
1471
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001472static void *GetKeyForBase(QualType BaseType) {
1473 if (const RecordType *RT = BaseType->getAs<RecordType>())
1474 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001476 assert(0 && "Unexpected base type!");
1477 return 0;
1478}
1479
Mike Stump1eb44332009-09-09 15:08:12 +00001480static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001481 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001482 // For fields injected into the class via declaration of an anonymous union,
1483 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001484 if (Member->isMemberInitializer()) {
1485 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Eli Friedman49c16da2009-11-09 01:05:47 +00001487 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001489 // in AnonUnionMember field.
1490 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1491 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001492 if (Field->getDeclContext()->isRecord()) {
1493 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1494 if (RD->isAnonymousStructOrUnion())
1495 return static_cast<void *>(RD);
1496 }
1497 return static_cast<void *>(Field);
1498 }
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001500 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001501}
1502
John McCall6aee6212009-11-04 23:13:52 +00001503/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001504void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001505 SourceLocation ColonLoc,
1506 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001507 if (!ConstructorDecl)
1508 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001509
1510 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
1512 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001513 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Anders Carlssona7b35212009-03-25 02:58:17 +00001515 if (!Constructor) {
1516 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1517 return;
1518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001520 if (!Constructor->isDependentContext()) {
1521 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1522 bool err = false;
1523 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001524 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001525 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1526 void *KeyToMember = GetKeyForMember(Member);
1527 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1528 if (!PrevMember) {
1529 PrevMember = Member;
1530 continue;
1531 }
1532 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001533 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001534 diag::error_multiple_mem_initialization)
1535 << Field->getNameAsString();
1536 else {
1537 Type *BaseClass = Member->getBaseClass();
1538 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001539 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001540 diag::error_multiple_base_initialization)
John McCallbf1cc052009-09-29 23:03:30 +00001541 << QualType(BaseClass, 0);
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001542 }
1543 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1544 << 0;
1545 err = true;
1546 }
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001548 if (err)
1549 return;
1550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Eli Friedman49c16da2009-11-09 01:05:47 +00001552 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001553 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001554 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001556 if (Constructor->isDependentContext())
1557 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
1559 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001560 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001561 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001562 Diagnostic::Ignored)
1563 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001565 // Also issue warning if order of ctor-initializer list does not match order
1566 // of 1) base class declarations and 2) order of non-static data members.
1567 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001569 CXXRecordDecl *ClassDecl
1570 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1571 // Push virtual bases before others.
1572 for (CXXRecordDecl::base_class_iterator VBase =
1573 ClassDecl->vbases_begin(),
1574 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001575 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001577 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1578 E = ClassDecl->bases_end(); Base != E; ++Base) {
1579 // Virtuals are alread in the virtual base list and are constructed
1580 // first.
1581 if (Base->isVirtual())
1582 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001583 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001586 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1587 E = ClassDecl->field_end(); Field != E; ++Field)
1588 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001590 int Last = AllBaseOrMembers.size();
1591 int curIndex = 0;
1592 CXXBaseOrMemberInitializer *PrevMember = 0;
1593 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001594 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001595 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1596 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001597
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001598 for (; curIndex < Last; curIndex++)
1599 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1600 break;
1601 if (curIndex == Last) {
1602 assert(PrevMember && "Member not in member list?!");
1603 // Initializer as specified in ctor-initializer list is out of order.
1604 // Issue a warning diagnostic.
1605 if (PrevMember->isBaseInitializer()) {
1606 // Diagnostics is for an initialized base class.
1607 Type *BaseClass = PrevMember->getBaseClass();
1608 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001609 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001610 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001611 } else {
1612 FieldDecl *Field = PrevMember->getMember();
1613 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001614 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001615 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001616 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001617 // Also the note!
1618 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001619 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001620 diag::note_fieldorbase_initialized_here) << 0
1621 << Field->getNameAsString();
1622 else {
1623 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001624 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001625 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001626 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001627 }
1628 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001629 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001630 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001631 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001632 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001633 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001634}
1635
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001636void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001637Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1638 // Ignore dependent destructors.
1639 if (Destructor->isDependentContext())
1640 return;
1641
1642 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Anders Carlsson9f853df2009-11-17 04:44:12 +00001644 // Non-static data members.
1645 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1646 E = ClassDecl->field_end(); I != E; ++I) {
1647 FieldDecl *Field = *I;
1648
1649 QualType FieldType = Context.getBaseElementType(Field->getType());
1650
1651 const RecordType* RT = FieldType->getAs<RecordType>();
1652 if (!RT)
1653 continue;
1654
1655 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1656 if (FieldClassDecl->hasTrivialDestructor())
1657 continue;
1658
1659 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1660 MarkDeclarationReferenced(Destructor->getLocation(),
1661 const_cast<CXXDestructorDecl*>(Dtor));
1662 }
1663
1664 // Bases.
1665 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1666 E = ClassDecl->bases_end(); Base != E; ++Base) {
1667 // Ignore virtual bases.
1668 if (Base->isVirtual())
1669 continue;
1670
1671 // Ignore trivial destructors.
1672 CXXRecordDecl *BaseClassDecl
1673 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1674 if (BaseClassDecl->hasTrivialDestructor())
1675 continue;
1676
1677 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1678 MarkDeclarationReferenced(Destructor->getLocation(),
1679 const_cast<CXXDestructorDecl*>(Dtor));
1680 }
1681
1682 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001683 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1684 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001685 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001686 CXXRecordDecl *BaseClassDecl
1687 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1688 if (BaseClassDecl->hasTrivialDestructor())
1689 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001690
1691 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1692 MarkDeclarationReferenced(Destructor->getLocation(),
1693 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001694 }
1695}
1696
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001697void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001698 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001699 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001701 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
1703 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001704 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001705 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001706}
1707
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001708namespace {
1709 /// PureVirtualMethodCollector - traverses a class and its superclasses
1710 /// and determines if it has any pure virtual methods.
1711 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1712 ASTContext &Context;
1713
Sebastian Redldfe292d2009-03-22 21:28:55 +00001714 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001715 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001716
1717 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001718 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001720 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001722 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001723 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001724 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001726 MethodList List;
1727 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001729 // Copy the temporary list to methods, and make sure to ignore any
1730 // null entries.
1731 for (size_t i = 0, e = List.size(); i != e; ++i) {
1732 if (List[i])
1733 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001734 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001737 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001739 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1740 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001741 };
Mike Stump1eb44332009-09-09 15:08:12 +00001742
1743 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001744 MethodList& Methods) {
1745 // First, collect the pure virtual methods for the base classes.
1746 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1747 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001748 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001749 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001750 if (BaseDecl && BaseDecl->isAbstract())
1751 Collect(BaseDecl, Methods);
1752 }
1753 }
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001755 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001756 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001758 MethodSetTy OverriddenMethods;
1759 size_t MethodsSize = Methods.size();
1760
Mike Stump1eb44332009-09-09 15:08:12 +00001761 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001762 i != e; ++i) {
1763 // Traverse the record, looking for methods.
1764 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001765 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001766 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001767 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Anders Carlsson27823022009-10-18 19:34:08 +00001769 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001770 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1771 E = MD->end_overridden_methods(); I != E; ++I) {
1772 // Keep track of the overridden methods.
1773 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001774 }
1775 }
1776 }
Mike Stump1eb44332009-09-09 15:08:12 +00001777
1778 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001779 // overridden.
1780 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1781 if (OverriddenMethods.count(Methods[i]))
1782 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001783 }
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001785 }
1786}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001787
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001788
Mike Stump1eb44332009-09-09 15:08:12 +00001789bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001790 unsigned DiagID, AbstractDiagSelID SelID,
1791 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001792 if (SelID == -1)
1793 return RequireNonAbstractType(Loc, T,
1794 PDiag(DiagID), CurrentRD);
1795 else
1796 return RequireNonAbstractType(Loc, T,
1797 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001798}
1799
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001800bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1801 const PartialDiagnostic &PD,
1802 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001803 if (!getLangOptions().CPlusPlus)
1804 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Anders Carlsson11f21a02009-03-23 19:10:31 +00001806 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001807 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001808 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Ted Kremenek6217b802009-07-29 21:53:49 +00001810 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001811 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001812 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001813 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001815 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001816 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Ted Kremenek6217b802009-07-29 21:53:49 +00001819 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001820 if (!RT)
1821 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001823 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1824 if (!RD)
1825 return false;
1826
Anders Carlssone65a3c82009-03-24 17:23:42 +00001827 if (CurrentRD && CurrentRD != RD)
1828 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001830 if (!RD->isAbstract())
1831 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001833 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001835 // Check if we've already emitted the list of pure virtual functions for this
1836 // class.
1837 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1838 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001840 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
1842 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001843 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1844 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001845
1846 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001847 MD->getDeclName();
1848 }
1849
1850 if (!PureVirtualClassDiagSet)
1851 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1852 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001854 return true;
1855}
1856
Anders Carlsson8211eff2009-03-24 01:19:16 +00001857namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001858 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001859 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1860 Sema &SemaRef;
1861 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Anders Carlssone65a3c82009-03-24 17:23:42 +00001863 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001864 bool Invalid = false;
1865
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001866 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1867 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001868 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001869
Anders Carlsson8211eff2009-03-24 01:19:16 +00001870 return Invalid;
1871 }
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Anders Carlssone65a3c82009-03-24 17:23:42 +00001873 public:
1874 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1875 : SemaRef(SemaRef), AbstractClass(ac) {
1876 Visit(SemaRef.Context.getTranslationUnitDecl());
1877 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001878
Anders Carlssone65a3c82009-03-24 17:23:42 +00001879 bool VisitFunctionDecl(const FunctionDecl *FD) {
1880 if (FD->isThisDeclarationADefinition()) {
1881 // No need to do the check if we're in a definition, because it requires
1882 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001883 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001884 return VisitDeclContext(FD);
1885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Anders Carlssone65a3c82009-03-24 17:23:42 +00001887 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001888 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001889 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001890 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1891 diag::err_abstract_type_in_decl,
1892 Sema::AbstractReturnType,
1893 AbstractClass);
1894
Mike Stump1eb44332009-09-09 15:08:12 +00001895 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001896 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001897 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001898 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001899 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001900 VD->getOriginalType(),
1901 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001902 Sema::AbstractParamType,
1903 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001904 }
1905
1906 return Invalid;
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Anders Carlssone65a3c82009-03-24 17:23:42 +00001909 bool VisitDecl(const Decl* D) {
1910 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1911 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Anders Carlssone65a3c82009-03-24 17:23:42 +00001913 return false;
1914 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001915 };
1916}
1917
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001918void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001919 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001920 SourceLocation LBrac,
1921 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001922 if (!TagDecl)
1923 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Douglas Gregor42af25f2009-05-11 19:58:34 +00001925 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001926 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001927 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001928 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001929
Chris Lattnerb28317a2009-03-28 19:18:32 +00001930 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001931 if (!RD->isAbstract()) {
1932 // Collect all the pure virtual methods and see if this is an abstract
1933 // class after all.
1934 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001935 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001936 RD->setAbstract(true);
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
1939 if (RD->isAbstract())
Douglas Gregor6490ae52009-11-17 06:14:37 +00001940 (void)AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Douglas Gregor663b5a02009-10-14 20:14:33 +00001942 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001943 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001944}
1945
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001946/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1947/// special functions, such as the default constructor, copy
1948/// constructor, or destructor, to the given C++ class (C++
1949/// [special]p1). This routine can only be executed just before the
1950/// definition of the class is complete.
1951void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001952 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001953 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001954
Sebastian Redl465226e2009-05-27 22:11:52 +00001955 // FIXME: Implicit declarations have exception specifications, which are
1956 // the union of the specifications of the implicitly called functions.
1957
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001958 if (!ClassDecl->hasUserDeclaredConstructor()) {
1959 // C++ [class.ctor]p5:
1960 // A default constructor for a class X is a constructor of class X
1961 // that can be called without an argument. If there is no
1962 // user-declared constructor for class X, a default constructor is
1963 // implicitly declared. An implicitly-declared default constructor
1964 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001965 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001966 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001967 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001968 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001969 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001970 Context.getFunctionType(Context.VoidTy,
1971 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001972 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001973 /*isExplicit=*/false,
1974 /*isInline=*/true,
1975 /*isImplicitlyDeclared=*/true);
1976 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001977 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001978 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001979 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001980 }
1981
1982 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1983 // C++ [class.copy]p4:
1984 // If the class definition does not explicitly declare a copy
1985 // constructor, one is declared implicitly.
1986
1987 // C++ [class.copy]p5:
1988 // The implicitly-declared copy constructor for a class X will
1989 // have the form
1990 //
1991 // X::X(const X&)
1992 //
1993 // if
1994 bool HasConstCopyConstructor = true;
1995
1996 // -- each direct or virtual base class B of X has a copy
1997 // constructor whose first parameter is of type const B& or
1998 // const volatile B&, and
1999 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2000 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2001 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002002 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002003 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002004 = BaseClassDecl->hasConstCopyConstructor(Context);
2005 }
2006
2007 // -- for all the nonstatic data members of X that are of a
2008 // class type M (or array thereof), each such class type
2009 // has a copy constructor whose first parameter is of type
2010 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002011 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2012 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002013 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002014 QualType FieldType = (*Field)->getType();
2015 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2016 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002017 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002018 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002019 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002020 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002021 = FieldClassDecl->hasConstCopyConstructor(Context);
2022 }
2023 }
2024
Sebastian Redl64b45f72009-01-05 20:52:13 +00002025 // Otherwise, the implicitly declared copy constructor will have
2026 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002027 //
2028 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002029 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002030 if (HasConstCopyConstructor)
2031 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002032 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002033
Sebastian Redl64b45f72009-01-05 20:52:13 +00002034 // An implicitly-declared copy constructor is an inline public
2035 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002036 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002037 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002038 CXXConstructorDecl *CopyConstructor
2039 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002040 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002041 Context.getFunctionType(Context.VoidTy,
2042 &ArgType, 1,
2043 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002044 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002045 /*isExplicit=*/false,
2046 /*isInline=*/true,
2047 /*isImplicitlyDeclared=*/true);
2048 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002049 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002050 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002051
2052 // Add the parameter to the constructor.
2053 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2054 ClassDecl->getLocation(),
2055 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002056 ArgType, /*DInfo=*/0,
2057 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002058 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002059 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002060 }
2061
Sebastian Redl64b45f72009-01-05 20:52:13 +00002062 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2063 // Note: The following rules are largely analoguous to the copy
2064 // constructor rules. Note that virtual bases are not taken into account
2065 // for determining the argument type of the operator. Note also that
2066 // operators taking an object instead of a reference are allowed.
2067 //
2068 // C++ [class.copy]p10:
2069 // If the class definition does not explicitly declare a copy
2070 // assignment operator, one is declared implicitly.
2071 // The implicitly-defined copy assignment operator for a class X
2072 // will have the form
2073 //
2074 // X& X::operator=(const X&)
2075 //
2076 // if
2077 bool HasConstCopyAssignment = true;
2078
2079 // -- each direct base class B of X has a copy assignment operator
2080 // whose parameter is of type const B&, const volatile B& or B,
2081 // and
2082 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2083 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002084 assert(!Base->getType()->isDependentType() &&
2085 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002086 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002087 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002088 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002089 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002090 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002091 }
2092
2093 // -- for all the nonstatic data members of X that are of a class
2094 // type M (or array thereof), each such class type has a copy
2095 // assignment operator whose parameter is of type const M&,
2096 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002097 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2098 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002099 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002100 QualType FieldType = (*Field)->getType();
2101 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2102 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002103 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002104 const CXXRecordDecl *FieldClassDecl
2105 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002106 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002107 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002108 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002109 }
2110 }
2111
2112 // Otherwise, the implicitly declared copy assignment operator will
2113 // have the form
2114 //
2115 // X& X::operator=(X&)
2116 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002117 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002118 if (HasConstCopyAssignment)
2119 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002120 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002121
2122 // An implicitly-declared copy assignment operator is an inline public
2123 // member of its class.
2124 DeclarationName Name =
2125 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2126 CXXMethodDecl *CopyAssignment =
2127 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2128 Context.getFunctionType(RetType, &ArgType, 1,
2129 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002130 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002131 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002132 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002133 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002134 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002135
2136 // Add the parameter to the operator.
2137 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2138 ClassDecl->getLocation(),
2139 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002140 ArgType, /*DInfo=*/0,
2141 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002142 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002143
2144 // Don't call addedAssignmentOperator. There is no way to distinguish an
2145 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002146 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002147 }
2148
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002149 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002150 // C++ [class.dtor]p2:
2151 // If a class has no user-declared destructor, a destructor is
2152 // declared implicitly. An implicitly-declared destructor is an
2153 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002154 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002155 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002156 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002157 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002158 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002159 Context.getFunctionType(Context.VoidTy,
2160 0, 0, false, 0),
2161 /*isInline=*/true,
2162 /*isImplicitlyDeclared=*/true);
2163 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002164 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002165 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002166 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002167 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002168}
2169
Douglas Gregor6569d682009-05-27 23:11:45 +00002170void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002171 Decl *D = TemplateD.getAs<Decl>();
2172 if (!D)
2173 return;
2174
2175 TemplateParameterList *Params = 0;
2176 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2177 Params = Template->getTemplateParameters();
2178 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2179 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2180 Params = PartialSpec->getTemplateParameters();
2181 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002182 return;
2183
Douglas Gregor6569d682009-05-27 23:11:45 +00002184 for (TemplateParameterList::iterator Param = Params->begin(),
2185 ParamEnd = Params->end();
2186 Param != ParamEnd; ++Param) {
2187 NamedDecl *Named = cast<NamedDecl>(*Param);
2188 if (Named->getDeclName()) {
2189 S->AddDecl(DeclPtrTy::make(Named));
2190 IdResolver.AddDecl(Named);
2191 }
2192 }
2193}
2194
Douglas Gregor72b505b2008-12-16 21:30:33 +00002195/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2196/// parsing a top-level (non-nested) C++ class, and we are now
2197/// parsing those parts of the given Method declaration that could
2198/// not be parsed earlier (C++ [class.mem]p2), such as default
2199/// arguments. This action should enter the scope of the given
2200/// Method declaration as if we had just parsed the qualified method
2201/// name. However, it should not bring the parameters into scope;
2202/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002203void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002204 if (!MethodD)
2205 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002207 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Douglas Gregor72b505b2008-12-16 21:30:33 +00002209 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002210 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002211 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002212 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2213 SS.setScopeRep(
2214 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002215 ActOnCXXEnterDeclaratorScope(S, SS);
2216}
2217
2218/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2219/// C++ method declaration. We're (re-)introducing the given
2220/// function parameter into scope for use in parsing later parts of
2221/// the method declaration. For example, we could see an
2222/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002223void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002224 if (!ParamD)
2225 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Chris Lattnerb28317a2009-03-28 19:18:32 +00002227 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002228
2229 // If this parameter has an unparsed default argument, clear it out
2230 // to make way for the parsed default argument.
2231 if (Param->hasUnparsedDefaultArg())
2232 Param->setDefaultArg(0);
2233
Chris Lattnerb28317a2009-03-28 19:18:32 +00002234 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002235 if (Param->getDeclName())
2236 IdResolver.AddDecl(Param);
2237}
2238
2239/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2240/// processing the delayed method declaration for Method. The method
2241/// declaration is now considered finished. There may be a separate
2242/// ActOnStartOfFunctionDef action later (not necessarily
2243/// immediately!) for this method, if it was also defined inside the
2244/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002245void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002246 if (!MethodD)
2247 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002249 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Chris Lattnerb28317a2009-03-28 19:18:32 +00002251 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002252 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002253 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002254 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2255 SS.setScopeRep(
2256 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002257 ActOnCXXExitDeclaratorScope(S, SS);
2258
2259 // Now that we have our default arguments, check the constructor
2260 // again. It could produce additional diagnostics or affect whether
2261 // the class has implicitly-declared destructors, among other
2262 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002263 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2264 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002265
2266 // Check the default arguments, which we may have added.
2267 if (!Method->isInvalidDecl())
2268 CheckCXXDefaultArguments(Method);
2269}
2270
Douglas Gregor42a552f2008-11-05 20:51:48 +00002271/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002272/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002273/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002274/// emit diagnostics and set the invalid bit to true. In any case, the type
2275/// will be updated to reflect a well-formed type for the constructor and
2276/// returned.
2277QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2278 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002279 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002280
2281 // C++ [class.ctor]p3:
2282 // A constructor shall not be virtual (10.3) or static (9.4). A
2283 // constructor can be invoked for a const, volatile or const
2284 // volatile object. A constructor shall not be declared const,
2285 // volatile, or const volatile (9.3.2).
2286 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002287 if (!D.isInvalidType())
2288 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2289 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2290 << SourceRange(D.getIdentifierLoc());
2291 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002292 }
2293 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002294 if (!D.isInvalidType())
2295 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2296 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2297 << SourceRange(D.getIdentifierLoc());
2298 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002299 SC = FunctionDecl::None;
2300 }
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Chris Lattner65401802009-04-25 08:28:21 +00002302 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2303 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002304 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002305 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2306 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002307 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002308 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2309 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002310 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002311 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2312 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002313 }
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Douglas Gregor42a552f2008-11-05 20:51:48 +00002315 // Rebuild the function type "R" without any type qualifiers (in
2316 // case any of the errors above fired) and with "void" as the
2317 // return type, since constructors don't have return types. We
2318 // *always* have to do this, because GetTypeForDeclarator will
2319 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002320 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002321 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2322 Proto->getNumArgs(),
2323 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002324}
2325
Douglas Gregor72b505b2008-12-16 21:30:33 +00002326/// CheckConstructor - Checks a fully-formed constructor for
2327/// well-formedness, issuing any diagnostics required. Returns true if
2328/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002329void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002330 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002331 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2332 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002333 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002334
2335 // C++ [class.copy]p3:
2336 // A declaration of a constructor for a class X is ill-formed if
2337 // its first parameter is of type (optionally cv-qualified) X and
2338 // either there are no other parameters or else all other
2339 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002340 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002341 ((Constructor->getNumParams() == 1) ||
2342 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002343 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2344 Constructor->getTemplateSpecializationKind()
2345 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002346 QualType ParamType = Constructor->getParamDecl(0)->getType();
2347 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2348 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002349 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2350 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002351 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002352
2353 // FIXME: Rather that making the constructor invalid, we should endeavor
2354 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002355 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002356 }
2357 }
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Douglas Gregor72b505b2008-12-16 21:30:33 +00002359 // Notify the class that we've added a constructor.
2360 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002361}
2362
Anders Carlsson6d701392009-11-15 22:49:34 +00002363/// CheckDestructor - Checks a fully-formed destructor for
2364/// well-formedness, issuing any diagnostics required.
2365void Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2366 CXXRecordDecl *RD = Destructor->getParent();
2367
2368 if (Destructor->isVirtual()) {
2369 SourceLocation Loc;
2370
2371 if (!Destructor->isImplicit())
2372 Loc = Destructor->getLocation();
2373 else
2374 Loc = RD->getLocation();
2375
2376 // If we have a virtual destructor, look up the deallocation function
2377 FunctionDecl *OperatorDelete = 0;
2378 DeclarationName Name =
2379 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2380 if (!FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2381 Destructor->setOperatorDelete(OperatorDelete);
2382 }
2383}
2384
Mike Stump1eb44332009-09-09 15:08:12 +00002385static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002386FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2387 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2388 FTI.ArgInfo[0].Param &&
2389 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2390}
2391
Douglas Gregor42a552f2008-11-05 20:51:48 +00002392/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2393/// the well-formednes of the destructor declarator @p D with type @p
2394/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002395/// emit diagnostics and set the declarator to invalid. Even if this happens,
2396/// will be updated to reflect a well-formed type for the destructor and
2397/// returned.
2398QualType Sema::CheckDestructorDeclarator(Declarator &D,
2399 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002400 // C++ [class.dtor]p1:
2401 // [...] A typedef-name that names a class is a class-name
2402 // (7.1.3); however, a typedef-name that names a class shall not
2403 // be used as the identifier in the declarator for a destructor
2404 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002405 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002406 if (isa<TypedefType>(DeclaratorType)) {
2407 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002408 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002409 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002410 }
2411
2412 // C++ [class.dtor]p2:
2413 // A destructor is used to destroy objects of its class type. A
2414 // destructor takes no parameters, and no return type can be
2415 // specified for it (not even void). The address of a destructor
2416 // shall not be taken. A destructor shall not be static. A
2417 // destructor can be invoked for a const, volatile or const
2418 // volatile object. A destructor shall not be declared const,
2419 // volatile or const volatile (9.3.2).
2420 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002421 if (!D.isInvalidType())
2422 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2423 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2424 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002425 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002426 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002427 }
Chris Lattner65401802009-04-25 08:28:21 +00002428 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002429 // Destructors don't have return types, but the parser will
2430 // happily parse something like:
2431 //
2432 // class X {
2433 // float ~X();
2434 // };
2435 //
2436 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002437 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2438 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2439 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002440 }
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Chris Lattner65401802009-04-25 08:28:21 +00002442 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2443 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002444 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002445 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2446 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002447 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002448 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2449 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002450 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002451 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2452 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002453 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002454 }
2455
2456 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002457 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002458 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2459
2460 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002461 FTI.freeArgs();
2462 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002463 }
2464
Mike Stump1eb44332009-09-09 15:08:12 +00002465 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002466 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002467 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002468 D.setInvalidType();
2469 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002470
2471 // Rebuild the function type "R" without any type qualifiers or
2472 // parameters (in case any of the errors above fired) and with
2473 // "void" as the return type, since destructors don't have return
2474 // types. We *always* have to do this, because GetTypeForDeclarator
2475 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002476 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002477}
2478
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002479/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2480/// well-formednes of the conversion function declarator @p D with
2481/// type @p R. If there are any errors in the declarator, this routine
2482/// will emit diagnostics and return true. Otherwise, it will return
2483/// false. Either way, the type @p R will be updated to reflect a
2484/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002485void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002486 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002487 // C++ [class.conv.fct]p1:
2488 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002489 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002490 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002491 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002492 if (!D.isInvalidType())
2493 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2494 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2495 << SourceRange(D.getIdentifierLoc());
2496 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002497 SC = FunctionDecl::None;
2498 }
Chris Lattner6e475012009-04-25 08:35:12 +00002499 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002500 // Conversion functions don't have return types, but the parser will
2501 // happily parse something like:
2502 //
2503 // class X {
2504 // float operator bool();
2505 // };
2506 //
2507 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002508 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2509 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2510 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002511 }
2512
2513 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002514 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002515 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2516
2517 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002518 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002519 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002520 }
2521
Mike Stump1eb44332009-09-09 15:08:12 +00002522 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002523 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002524 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002525 D.setInvalidType();
2526 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002527
2528 // C++ [class.conv.fct]p4:
2529 // The conversion-type-id shall not represent a function type nor
2530 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002531 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002532 if (ConvType->isArrayType()) {
2533 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2534 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002535 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002536 } else if (ConvType->isFunctionType()) {
2537 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2538 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002539 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002540 }
2541
2542 // Rebuild the function type "R" without any parameters (in case any
2543 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002544 // return type.
2545 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002546 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002547
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002548 // C++0x explicit conversion operators.
2549 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002550 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002551 diag::warn_explicit_conversion_functions)
2552 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002553}
2554
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002555/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2556/// the declaration of the given C++ conversion function. This routine
2557/// is responsible for recording the conversion function in the C++
2558/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002559Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002560 assert(Conversion && "Expected to receive a conversion function declaration");
2561
Douglas Gregor9d350972008-12-12 08:25:50 +00002562 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002563
2564 // Make sure we aren't redeclaring the conversion function.
2565 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002566
2567 // C++ [class.conv.fct]p1:
2568 // [...] A conversion function is never used to convert a
2569 // (possibly cv-qualified) object to the (possibly cv-qualified)
2570 // same object type (or a reference to it), to a (possibly
2571 // cv-qualified) base class of that type (or a reference to it),
2572 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002573 // FIXME: Suppress this warning if the conversion function ends up being a
2574 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002575 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002577 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002578 ConvType = ConvTypeRef->getPointeeType();
2579 if (ConvType->isRecordType()) {
2580 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2581 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002582 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002583 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002584 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002585 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002586 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002587 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002588 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002589 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002590 }
2591
Douglas Gregor70316a02008-12-26 15:00:45 +00002592 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002593 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002594 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002595 = Conversion->getDescribedFunctionTemplate())
2596 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002597 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002598 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002599 Conv = Conversions->function_begin(),
2600 ConvEnd = Conversions->function_end();
2601 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002602 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002603 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002604 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002605 }
2606 }
2607 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002608 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002609 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002610 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002611 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002612 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002613
Chris Lattnerb28317a2009-03-28 19:18:32 +00002614 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002615}
2616
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002617//===----------------------------------------------------------------------===//
2618// Namespace Handling
2619//===----------------------------------------------------------------------===//
2620
2621/// ActOnStartNamespaceDef - This is called at the start of a namespace
2622/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002623Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2624 SourceLocation IdentLoc,
2625 IdentifierInfo *II,
2626 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002627 NamespaceDecl *Namespc =
2628 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2629 Namespc->setLBracLoc(LBrace);
2630
2631 Scope *DeclRegionScope = NamespcScope->getParent();
2632
2633 if (II) {
2634 // C++ [namespace.def]p2:
2635 // The identifier in an original-namespace-definition shall not have been
2636 // previously defined in the declarative region in which the
2637 // original-namespace-definition appears. The identifier in an
2638 // original-namespace-definition is the name of the namespace. Subsequently
2639 // in that declarative region, it is treated as an original-namespace-name.
2640
John McCallf36e02d2009-10-09 21:13:30 +00002641 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002642 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002643 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002644
Douglas Gregor44b43212008-12-11 16:49:14 +00002645 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2646 // This is an extended namespace definition.
2647 // Attach this namespace decl to the chain of extended namespace
2648 // definitions.
2649 OrigNS->setNextNamespace(Namespc);
2650 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002651
Mike Stump1eb44332009-09-09 15:08:12 +00002652 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002653 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002654 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002655 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002656 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002657 } else if (PrevDecl) {
2658 // This is an invalid name redefinition.
2659 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2660 << Namespc->getDeclName();
2661 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2662 Namespc->setInvalidDecl();
2663 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002664 } else if (II->isStr("std") &&
2665 CurContext->getLookupContext()->isTranslationUnit()) {
2666 // This is the first "real" definition of the namespace "std", so update
2667 // our cache of the "std" namespace to point at this definition.
2668 if (StdNamespace) {
2669 // We had already defined a dummy namespace "std". Link this new
2670 // namespace definition to the dummy namespace "std".
2671 StdNamespace->setNextNamespace(Namespc);
2672 StdNamespace->setLocation(IdentLoc);
2673 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2674 }
2675
2676 // Make our StdNamespace cache point at the first real definition of the
2677 // "std" namespace.
2678 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002680
2681 PushOnScopeChains(Namespc, DeclRegionScope);
2682 } else {
John McCall9aeed322009-10-01 00:25:31 +00002683 // Anonymous namespaces.
2684
2685 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2686 // behaves as if it were replaced by
2687 // namespace unique { /* empty body */ }
2688 // using namespace unique;
2689 // namespace unique { namespace-body }
2690 // where all occurrences of 'unique' in a translation unit are
2691 // replaced by the same identifier and this identifier differs
2692 // from all other identifiers in the entire program.
2693
2694 // We just create the namespace with an empty name and then add an
2695 // implicit using declaration, just like the standard suggests.
2696 //
2697 // CodeGen enforces the "universally unique" aspect by giving all
2698 // declarations semantically contained within an anonymous
2699 // namespace internal linkage.
2700
2701 assert(Namespc->isAnonymousNamespace());
2702 CurContext->addDecl(Namespc);
2703
2704 UsingDirectiveDecl* UD
2705 = UsingDirectiveDecl::Create(Context, CurContext,
2706 /* 'using' */ LBrace,
2707 /* 'namespace' */ SourceLocation(),
2708 /* qualifier */ SourceRange(),
2709 /* NNS */ NULL,
2710 /* identifier */ SourceLocation(),
2711 Namespc,
2712 /* Ancestor */ CurContext);
2713 UD->setImplicit();
2714 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002715 }
2716
2717 // Although we could have an invalid decl (i.e. the namespace name is a
2718 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002719 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2720 // for the namespace has the declarations that showed up in that particular
2721 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002722 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002723 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002724}
2725
2726/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2727/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002728void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2729 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002730 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2731 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2732 Namespc->setRBracLoc(RBrace);
2733 PopDeclContext();
2734}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002735
Chris Lattnerb28317a2009-03-28 19:18:32 +00002736Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2737 SourceLocation UsingLoc,
2738 SourceLocation NamespcLoc,
2739 const CXXScopeSpec &SS,
2740 SourceLocation IdentLoc,
2741 IdentifierInfo *NamespcName,
2742 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002743 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2744 assert(NamespcName && "Invalid NamespcName.");
2745 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002746 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002747
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002748 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002749
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002750 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002751 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2752 LookupParsedName(R, S, &SS);
2753 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002754 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002755
John McCallf36e02d2009-10-09 21:13:30 +00002756 if (!R.empty()) {
2757 NamedDecl *NS = R.getFoundDecl();
Douglas Gregor19aeac62009-11-14 03:27:21 +00002758 // FIXME: Namespace aliases!
Douglas Gregorf780abc2008-12-30 03:27:21 +00002759 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002760 // C++ [namespace.udir]p1:
2761 // A using-directive specifies that the names in the nominated
2762 // namespace can be used in the scope in which the
2763 // using-directive appears after the using-directive. During
2764 // unqualified name lookup (3.4.1), the names appear as if they
2765 // were declared in the nearest enclosing namespace which
2766 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002767 // namespace. [Note: in this context, "contains" means "contains
2768 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002769
2770 // Find enclosing context containing both using-directive and
2771 // nominated namespace.
2772 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2773 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2774 CommonAncestor = CommonAncestor->getParent();
2775
Mike Stump1eb44332009-09-09 15:08:12 +00002776 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002777 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002778 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002779 SS.getRange(),
2780 (NestedNameSpecifier *)SS.getScopeRep(),
2781 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002782 cast<NamespaceDecl>(NS),
2783 CommonAncestor);
2784 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002785 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002786 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002787 }
2788
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002789 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002790 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002791 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002792}
2793
2794void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2795 // If scope has associated entity, then using directive is at namespace
2796 // or translation unit scope. We add UsingDirectiveDecls, into
2797 // it's lookup structure.
2798 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002799 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002800 else
2801 // Otherwise it is block-sope. using-directives will affect lookup
2802 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002803 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002804}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002805
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002806
2807Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002808 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002809 SourceLocation UsingLoc,
2810 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002811 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002812 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002813 bool IsTypeName,
2814 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002815 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Douglas Gregor12c118a2009-11-04 16:30:06 +00002817 switch (Name.getKind()) {
2818 case UnqualifiedId::IK_Identifier:
2819 case UnqualifiedId::IK_OperatorFunctionId:
2820 case UnqualifiedId::IK_ConversionFunctionId:
2821 break;
2822
2823 case UnqualifiedId::IK_ConstructorName:
2824 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2825 << SS.getRange();
2826 return DeclPtrTy();
2827
2828 case UnqualifiedId::IK_DestructorName:
2829 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2830 << SS.getRange();
2831 return DeclPtrTy();
2832
2833 case UnqualifiedId::IK_TemplateId:
2834 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2835 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2836 return DeclPtrTy();
2837 }
2838
2839 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall9488ea12009-11-17 05:59:44 +00002840 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002841 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002842 TargetName, AttrList,
2843 /* IsInstantiation */ false,
2844 IsTypeName, TypenameLoc);
Anders Carlsson595adc12009-08-29 19:54:19 +00002845 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002846 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002847 UD->setAccess(AS);
2848 }
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Anders Carlssonc72160b2009-08-28 05:40:36 +00002850 return DeclPtrTy::make(UD);
2851}
2852
John McCall9488ea12009-11-17 05:59:44 +00002853/// Builds a shadow declaration corresponding to a 'using' declaration.
2854static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2855 AccessSpecifier AS,
2856 UsingDecl *UD, NamedDecl *Orig) {
2857 // FIXME: diagnose hiding, collisions
2858
2859 // If we resolved to another shadow declaration, just coalesce them.
2860 if (isa<UsingShadowDecl>(Orig)) {
2861 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2862 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2863 }
2864
2865 UsingShadowDecl *Shadow
2866 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2867 UD->getLocation(), UD, Orig);
2868 UD->addShadowDecl(Shadow);
2869
2870 if (S)
2871 SemaRef.PushOnScopeChains(Shadow, S);
2872 else
2873 SemaRef.CurContext->addDecl(Shadow);
2874 Shadow->setAccess(AS);
2875
2876 return Shadow;
2877}
2878
John McCall7ba107a2009-11-18 02:36:19 +00002879/// Builds a using declaration.
2880///
2881/// \param IsInstantiation - Whether this call arises from an
2882/// instantiation of an unresolved using declaration. We treat
2883/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00002884NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2885 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002886 const CXXScopeSpec &SS,
2887 SourceLocation IdentLoc,
2888 DeclarationName Name,
2889 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002890 bool IsInstantiation,
2891 bool IsTypeName,
2892 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002893 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2894 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002895
Anders Carlsson550b14b2009-08-28 05:49:21 +00002896 // FIXME: We ignore attributes for now.
2897 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002899 if (SS.isEmpty()) {
2900 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002901 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002902 }
Mike Stump1eb44332009-09-09 15:08:12 +00002903
2904 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002905 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2906
John McCallaf8e6ed2009-11-12 03:15:40 +00002907 DeclContext *LookupContext = computeDeclContext(SS);
2908 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00002909 if (IsTypeName) {
2910 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2911 UsingLoc, TypenameLoc,
2912 SS.getRange(), NNS,
2913 IdentLoc, Name);
2914 } else {
2915 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2916 UsingLoc, SS.getRange(), NNS,
2917 IdentLoc, Name);
2918 }
Anders Carlsson550b14b2009-08-28 05:49:21 +00002919 }
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002921 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2922 // C++0x N2914 [namespace.udecl]p3:
2923 // A using-declaration used as a member-declaration shall refer to a member
2924 // of a base class of the class being defined, shall refer to a member of an
2925 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002926 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002927 // a member of a base class of the class being defined.
John McCall9488ea12009-11-17 05:59:44 +00002928
John McCallaf8e6ed2009-11-12 03:15:40 +00002929 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2930 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002931 Diag(SS.getRange().getBegin(),
2932 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2933 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002934 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002935 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002936 } else {
2937 // C++0x N2914 [namespace.udecl]p8:
2938 // A using-declaration for a class member shall be a member-declaration.
John McCallaf8e6ed2009-11-12 03:15:40 +00002939 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002940 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002941 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002942 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002943 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002944 }
2945
John McCall9488ea12009-11-17 05:59:44 +00002946 // Look up the target name. Unlike most lookups, we do not want to
2947 // hide tag declarations: tag names are visible through the using
2948 // declaration even if hidden by ordinary names.
John McCalla24dc2e2009-11-17 02:14:36 +00002949 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00002950
2951 // We don't hide tags behind ordinary decls if we're in a
2952 // non-dependent context, but in a dependent context, this is
2953 // important for the stability of two-phase lookup.
2954 if (!IsInstantiation)
2955 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00002956
John McCalla24dc2e2009-11-17 02:14:36 +00002957 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002958
John McCallf36e02d2009-10-09 21:13:30 +00002959 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00002960 Diag(IdentLoc, diag::err_no_member)
2961 << Name << LookupContext << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002962 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002963 }
2964
John McCall9488ea12009-11-17 05:59:44 +00002965 if (R.isAmbiguous())
2966 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002967
John McCall7ba107a2009-11-18 02:36:19 +00002968 if (IsTypeName) {
2969 // If we asked for a typename and got a non-type decl, error out.
2970 if (R.getResultKind() != LookupResult::Found
2971 || !isa<TypeDecl>(R.getFoundDecl())) {
2972 Diag(IdentLoc, diag::err_using_typename_non_type);
2973 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2974 Diag((*I)->getUnderlyingDecl()->getLocation(),
2975 diag::note_using_decl_target);
2976 return 0;
2977 }
2978 } else {
2979 // If we asked for a non-typename and we got a type, error out,
2980 // but only if this is an instantiation of an unresolved using
2981 // decl. Otherwise just silently find the type name.
2982 if (IsInstantiation &&
2983 R.getResultKind() == LookupResult::Found &&
2984 isa<TypeDecl>(R.getFoundDecl())) {
2985 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
2986 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
2987 return 0;
2988 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002989 }
2990
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002991 // C++0x N2914 [namespace.udecl]p6:
2992 // A using-declaration shall not name a namespace.
John McCall9488ea12009-11-17 05:59:44 +00002993 if (R.getResultKind() == LookupResult::Found
2994 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002995 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2996 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002997 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002998 }
Mike Stump1eb44332009-09-09 15:08:12 +00002999
John McCall9488ea12009-11-17 05:59:44 +00003000 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3001 SS.getRange(), UsingLoc, NNS, Name,
3002 IsTypeName);
3003
3004 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3005 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3006
3007 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003008}
3009
Anders Carlsson81c85c42009-03-28 23:53:49 +00003010/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3011/// is a namespace alias, returns the namespace it points to.
3012static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3013 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3014 return AD->getNamespace();
3015 return dyn_cast_or_null<NamespaceDecl>(D);
3016}
3017
Mike Stump1eb44332009-09-09 15:08:12 +00003018Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003019 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003020 SourceLocation AliasLoc,
3021 IdentifierInfo *Alias,
3022 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003023 SourceLocation IdentLoc,
3024 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Anders Carlsson81c85c42009-03-28 23:53:49 +00003026 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003027 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3028 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003029
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003030 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003031 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003032 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003033 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003034 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003035 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003036 if (!R.isAmbiguous() && !R.empty() &&
3037 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003038 return DeclPtrTy();
3039 }
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003041 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3042 diag::err_redefinition_different_kind;
3043 Diag(AliasLoc, DiagID) << Alias;
3044 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003045 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003046 }
3047
John McCalla24dc2e2009-11-17 02:14:36 +00003048 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003049 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003050
John McCallf36e02d2009-10-09 21:13:30 +00003051 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003052 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003053 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003054 }
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003056 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003057 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3058 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003059 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003060 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003061
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003062 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003063 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003064}
3065
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003066void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3067 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003068 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3069 !Constructor->isUsed()) &&
3070 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Eli Friedman80c30da2009-11-09 19:20:36 +00003072 CXXRecordDecl *ClassDecl
3073 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3074 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003075
Eli Friedman80c30da2009-11-09 19:20:36 +00003076 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
3077 Diag(CurrentLocation, diag::note_ctor_synthesized_at)
3078 << Context.getTagDeclType(ClassDecl);
3079 Constructor->setInvalidDecl();
3080 } else {
3081 Constructor->setUsed();
3082 }
Eli Friedman49c16da2009-11-09 01:05:47 +00003083 return;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003084}
3085
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003086void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003087 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003088 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3089 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003090 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003091 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3092 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003093 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003094 // implicitly defined, all the implicitly-declared default destructors
3095 // for its base class and its non-static data members shall have been
3096 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003097 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3098 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003099 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003100 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003101 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003102 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003103 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3104 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3105 else
Mike Stump1eb44332009-09-09 15:08:12 +00003106 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003107 "DefineImplicitDestructor - missing dtor in a base class");
3108 }
3109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003111 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3112 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003113 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3114 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3115 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003116 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003117 CXXRecordDecl *FieldClassDecl
3118 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3119 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003120 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003121 const_cast<CXXDestructorDecl*>(
3122 FieldClassDecl->getDestructor(Context)))
3123 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3124 else
Mike Stump1eb44332009-09-09 15:08:12 +00003125 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003126 "DefineImplicitDestructor - missing dtor in class of a data member");
3127 }
3128 }
3129 }
3130 Destructor->setUsed();
3131}
3132
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003133void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3134 CXXMethodDecl *MethodDecl) {
3135 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3136 MethodDecl->getOverloadedOperator() == OO_Equal &&
3137 !MethodDecl->isUsed()) &&
3138 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003140 CXXRecordDecl *ClassDecl
3141 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003143 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003144 // Before the implicitly-declared copy assignment operator for a class is
3145 // implicitly defined, all implicitly-declared copy assignment operators
3146 // for its direct base classes and its nonstatic data members shall have
3147 // been implicitly defined.
3148 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003149 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3150 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003151 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003152 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003153 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003154 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3155 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3156 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003157 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3158 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003159 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3160 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3161 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003162 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003163 CXXRecordDecl *FieldClassDecl
3164 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003165 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003166 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3167 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003168 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003169 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003170 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3171 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003172 Diag(CurrentLocation, diag::note_first_required_here);
3173 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003174 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003175 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003176 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3177 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003178 Diag(CurrentLocation, diag::note_first_required_here);
3179 err = true;
3180 }
3181 }
3182 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003183 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003184}
3185
3186CXXMethodDecl *
3187Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3188 CXXRecordDecl *ClassDecl) {
3189 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3190 QualType RHSType(LHSType);
3191 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003192 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003193 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003194 RHSType = Context.getCVRQualifiedType(RHSType,
3195 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003196 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3197 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003198 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003199 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3200 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003201 SourceLocation()));
3202 Expr *Args[2] = { &*LHS, &*RHS };
3203 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003204 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003205 CandidateSet);
3206 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00003207 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003208 ClassDecl->getLocation(), Best) == OR_Success)
3209 return cast<CXXMethodDecl>(Best->Function);
3210 assert(false &&
3211 "getAssignOperatorMethod - copy assignment operator method not found");
3212 return 0;
3213}
3214
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003215void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3216 CXXConstructorDecl *CopyConstructor,
3217 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003218 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003219 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3220 !CopyConstructor->isUsed()) &&
3221 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003223 CXXRecordDecl *ClassDecl
3224 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3225 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003226 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003227 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003228 // implicitly defined, all the implicitly-declared copy constructors
3229 // for its base class and its non-static data members shall have been
3230 // implicitly defined.
3231 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3232 Base != ClassDecl->bases_end(); ++Base) {
3233 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003234 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003235 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003236 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003237 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003238 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003239 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3240 FieldEnd = ClassDecl->field_end();
3241 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003242 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3243 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3244 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003245 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003246 CXXRecordDecl *FieldClassDecl
3247 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003248 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003249 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003250 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003251 }
3252 }
3253 CopyConstructor->setUsed();
3254}
3255
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003256Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003257Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003258 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003259 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003260 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Douglas Gregor39da0b82009-09-09 23:08:42 +00003262 // C++ [class.copy]p15:
3263 // Whenever a temporary class object is copied using a copy constructor, and
3264 // this object and the copy have the same cv-unqualified type, an
3265 // implementation is permitted to treat the original and the copy as two
3266 // different ways of referring to the same object and not perform a copy at
3267 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003269 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003270 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003271 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003272 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3273 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003274 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3275 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3276 E = ICE->getSubExpr();
3277
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003278 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3279 Elidable = true;
3280 }
Mike Stump1eb44332009-09-09 15:08:12 +00003281
3282 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003283 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003284}
3285
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003286/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3287/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003288Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003289Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3290 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003291 MultiExprArg ExprArgs) {
3292 unsigned NumExprs = ExprArgs.size();
3293 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Douglas Gregor39da0b82009-09-09 23:08:42 +00003295 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3296 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003297}
3298
Anders Carlssone7624a72009-08-27 05:08:22 +00003299Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003300Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3301 QualType Ty,
3302 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003303 MultiExprArg Args,
3304 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003305 unsigned NumExprs = Args.size();
3306 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Douglas Gregor39da0b82009-09-09 23:08:42 +00003308 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3309 TyBeginLoc, Exprs,
3310 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003311}
3312
3313
Mike Stump1eb44332009-09-09 15:08:12 +00003314bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003315 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003316 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003317 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003318 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003319 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003320 if (TempResult.isInvalid())
3321 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003323 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003324 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003325 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003326 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Anders Carlssonfe2de492009-08-25 05:18:00 +00003328 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003329}
3330
Mike Stump1eb44332009-09-09 15:08:12 +00003331void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003333 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003334 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003335 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003336 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003337 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003338}
3339
Mike Stump1eb44332009-09-09 15:08:12 +00003340/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003341/// ActOnDeclarator, when a C++ direct initializer is present.
3342/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003343void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3344 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003345 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003346 SourceLocation *CommaLocs,
3347 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003348 unsigned NumExprs = Exprs.size();
3349 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003350 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003351
3352 // If there is no declaration, there was an error parsing it. Just ignore
3353 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003354 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003355 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003357 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3358 if (!VDecl) {
3359 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3360 RealDecl->setInvalidDecl();
3361 return;
3362 }
3363
Douglas Gregor83ddad32009-08-26 21:14:46 +00003364 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003365 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003366 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3367 //
3368 // Clients that want to distinguish between the two forms, can check for
3369 // direct initializer using VarDecl::hasCXXDirectInitializer().
3370 // A major benefit is that clients that don't particularly care about which
3371 // exactly form was it (like the CodeGen) can handle both cases without
3372 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003373
Douglas Gregor83ddad32009-08-26 21:14:46 +00003374 // If either the declaration has a dependent type or if any of the expressions
3375 // is type-dependent, we represent the initialization via a ParenListExpr for
3376 // later use during template instantiation.
3377 if (VDecl->getType()->isDependentType() ||
3378 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3379 // Let clients know that initialization was done with a direct initializer.
3380 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Douglas Gregor83ddad32009-08-26 21:14:46 +00003382 // Store the initialization expressions as a ParenListExpr.
3383 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003384 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003385 new (Context) ParenListExpr(Context, LParenLoc,
3386 (Expr **)Exprs.release(),
3387 NumExprs, RParenLoc));
3388 return;
3389 }
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Douglas Gregor83ddad32009-08-26 21:14:46 +00003391
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003392 // C++ 8.5p11:
3393 // The form of initialization (using parentheses or '=') is generally
3394 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003395 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003396 QualType DeclInitType = VDecl->getType();
3397 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003398 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003399
Douglas Gregor615c5d42009-03-24 16:43:20 +00003400 // FIXME: This isn't the right place to complete the type.
3401 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3402 diag::err_typecheck_decl_incomplete_type)) {
3403 VDecl->setInvalidDecl();
3404 return;
3405 }
3406
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003407 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003408 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3409
Douglas Gregor18fe5682008-11-03 20:45:27 +00003410 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003411 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003412 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003413 VDecl->getLocation(),
3414 SourceRange(VDecl->getLocation(),
3415 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003417 IK_Direct,
3418 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003419 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003420 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003421 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003422 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003423 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003424 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003425 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003426 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003427 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003428 return;
3429 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003430
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003431 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003432 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3433 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003434 RealDecl->setInvalidDecl();
3435 return;
3436 }
3437
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003438 // Let clients know that initialization was done with a direct initializer.
3439 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003440
3441 assert(NumExprs == 1 && "Expected 1 expression");
3442 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003443 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3444 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003445}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003446
Douglas Gregor19aeac62009-11-14 03:27:21 +00003447/// \brief Add the applicable constructor candidates for an initialization
3448/// by constructor.
3449static void AddConstructorInitializationCandidates(Sema &SemaRef,
3450 QualType ClassType,
3451 Expr **Args,
3452 unsigned NumArgs,
3453 Sema::InitializationKind Kind,
3454 OverloadCandidateSet &CandidateSet) {
3455 // C++ [dcl.init]p14:
3456 // If the initialization is direct-initialization, or if it is
3457 // copy-initialization where the cv-unqualified version of the
3458 // source type is the same class as, or a derived class of, the
3459 // class of the destination, constructors are considered. The
3460 // applicable constructors are enumerated (13.3.1.3), and the
3461 // best one is chosen through overload resolution (13.3). The
3462 // constructor so selected is called to initialize the object,
3463 // with the initializer expression(s) as its argument(s). If no
3464 // constructor applies, or the overload resolution is ambiguous,
3465 // the initialization is ill-formed.
3466 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3467 assert(ClassRec && "Can only initialize a class type here");
3468
3469 // FIXME: When we decide not to synthesize the implicitly-declared
3470 // constructors, we'll need to make them appear here.
3471
3472 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3473 DeclarationName ConstructorName
3474 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3475 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3476 DeclContext::lookup_const_iterator Con, ConEnd;
3477 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3478 Con != ConEnd; ++Con) {
3479 // Find the constructor (which may be a template).
3480 CXXConstructorDecl *Constructor = 0;
3481 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3482 if (ConstructorTmpl)
3483 Constructor
3484 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3485 else
3486 Constructor = cast<CXXConstructorDecl>(*Con);
3487
3488 if ((Kind == Sema::IK_Direct) ||
3489 (Kind == Sema::IK_Copy &&
3490 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3491 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3492 if (ConstructorTmpl)
3493 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3494 Args, NumArgs, CandidateSet);
3495 else
3496 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3497 }
3498 }
3499}
3500
3501/// \brief Attempt to perform initialization by constructor
3502/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3503/// copy-initialization.
3504///
3505/// This routine determines whether initialization by constructor is possible,
3506/// but it does not emit any diagnostics in the case where the initialization
3507/// is ill-formed.
3508///
3509/// \param ClassType the type of the object being initialized, which must have
3510/// class type.
3511///
3512/// \param Args the arguments provided to initialize the object
3513///
3514/// \param NumArgs the number of arguments provided to initialize the object
3515///
3516/// \param Kind the type of initialization being performed
3517///
3518/// \returns the constructor used to initialize the object, if successful.
3519/// Otherwise, emits a diagnostic and returns NULL.
3520CXXConstructorDecl *
3521Sema::TryInitializationByConstructor(QualType ClassType,
3522 Expr **Args, unsigned NumArgs,
3523 SourceLocation Loc,
3524 InitializationKind Kind) {
3525 // Build the overload candidate set
3526 OverloadCandidateSet CandidateSet;
3527 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3528 CandidateSet);
3529
3530 // Determine whether we found a constructor we can use.
3531 OverloadCandidateSet::iterator Best;
3532 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3533 case OR_Success:
3534 case OR_Deleted:
3535 // We found a constructor. Return it.
3536 return cast<CXXConstructorDecl>(Best->Function);
3537
3538 case OR_No_Viable_Function:
3539 case OR_Ambiguous:
3540 // Overload resolution failed. Return nothing.
3541 return 0;
3542 }
3543
3544 // Silence GCC warning
3545 return 0;
3546}
3547
Douglas Gregor39da0b82009-09-09 23:08:42 +00003548/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3549/// may occur as part of direct-initialization or copy-initialization.
3550///
3551/// \param ClassType the type of the object being initialized, which must have
3552/// class type.
3553///
3554/// \param ArgsPtr the arguments provided to initialize the object
3555///
3556/// \param Loc the source location where the initialization occurs
3557///
3558/// \param Range the source range that covers the entire initialization
3559///
3560/// \param InitEntity the name of the entity being initialized, if known
3561///
3562/// \param Kind the type of initialization being performed
3563///
3564/// \param ConvertedArgs a vector that will be filled in with the
3565/// appropriately-converted arguments to the constructor (if initialization
3566/// succeeded).
3567///
3568/// \returns the constructor used to initialize the object, if successful.
3569/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003570CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003571Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003572 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003573 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003574 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003575 InitializationKind Kind,
3576 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00003577
3578 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00003579 Expr **Args = (Expr **)ArgsPtr.get();
3580 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003581 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00003582 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3583 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003584
Douglas Gregor18fe5682008-11-03 20:45:27 +00003585 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003586 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003587 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003588 // We found a constructor. Break out so that we can convert the arguments
3589 // appropriately.
3590 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Douglas Gregor18fe5682008-11-03 20:45:27 +00003592 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003593 if (InitEntity)
3594 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003595 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003596 else
3597 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003598 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003599 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003600 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Douglas Gregor18fe5682008-11-03 20:45:27 +00003602 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003603 if (InitEntity)
3604 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3605 else
3606 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003607 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3608 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003609
3610 case OR_Deleted:
3611 if (InitEntity)
3612 Diag(Loc, diag::err_ovl_deleted_init)
3613 << Best->Function->isDeleted()
3614 << InitEntity << Range;
3615 else
3616 Diag(Loc, diag::err_ovl_deleted_init)
3617 << Best->Function->isDeleted()
3618 << InitEntity << Range;
3619 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3620 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor39da0b82009-09-09 23:08:42 +00003623 // Convert the arguments, fill in default arguments, etc.
3624 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3625 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3626 return 0;
3627
3628 return Constructor;
3629}
3630
3631/// \brief Given a constructor and the set of arguments provided for the
3632/// constructor, convert the arguments and add any required default arguments
3633/// to form a proper call to this constructor.
3634///
3635/// \returns true if an error occurred, false otherwise.
3636bool
3637Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3638 MultiExprArg ArgsPtr,
3639 SourceLocation Loc,
3640 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3641 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3642 unsigned NumArgs = ArgsPtr.size();
3643 Expr **Args = (Expr **)ArgsPtr.get();
3644
3645 const FunctionProtoType *Proto
3646 = Constructor->getType()->getAs<FunctionProtoType>();
3647 assert(Proto && "Constructor without a prototype?");
3648 unsigned NumArgsInProto = Proto->getNumArgs();
3649 unsigned NumArgsToCheck = NumArgs;
3650
3651 // If too few arguments are available, we'll fill in the rest with defaults.
3652 if (NumArgs < NumArgsInProto) {
3653 NumArgsToCheck = NumArgsInProto;
3654 ConvertedArgs.reserve(NumArgsInProto);
3655 } else {
3656 ConvertedArgs.reserve(NumArgs);
3657 if (NumArgs > NumArgsInProto)
3658 NumArgsToCheck = NumArgsInProto;
3659 }
3660
3661 // Convert arguments
3662 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3663 QualType ProtoArgType = Proto->getArgType(i);
3664
3665 Expr *Arg;
3666 if (i < NumArgs) {
3667 Arg = Args[i];
Anders Carlsson71710112009-09-15 21:14:33 +00003668
3669 // Pass the argument.
3670 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3671 return true;
3672
3673 Args[i] = 0;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003674 } else {
3675 ParmVarDecl *Param = Constructor->getParamDecl(i);
3676
3677 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3678 if (DefArg.isInvalid())
3679 return true;
3680
3681 Arg = DefArg.takeAs<Expr>();
3682 }
3683
3684 ConvertedArgs.push_back(Arg);
3685 }
3686
3687 // If this is a variadic call, handle args passed through "...".
3688 if (Proto->isVariadic()) {
3689 // Promote the arguments (C99 6.5.2.2p7).
3690 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3691 Expr *Arg = Args[i];
3692 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3693 return true;
3694
3695 ConvertedArgs.push_back(Arg);
3696 Args[i] = 0;
3697 }
3698 }
3699
3700 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003701}
3702
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003703/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3704/// determine whether they are reference-related,
3705/// reference-compatible, reference-compatible with added
3706/// qualification, or incompatible, for use in C++ initialization by
3707/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3708/// type, and the first type (T1) is the pointee type of the reference
3709/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003710Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00003711Sema::CompareReferenceRelationship(SourceLocation Loc,
3712 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003713 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003714 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003715 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00003716 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003717
Douglas Gregor393896f2009-11-05 13:06:35 +00003718 QualType T1 = Context.getCanonicalType(OrigT1);
3719 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003720 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3721 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003722
3723 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003724 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003725 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003726 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003727 if (UnqualT1 == UnqualT2)
3728 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00003729 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3730 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3731 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00003732 DerivedToBase = true;
3733 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003734 return Ref_Incompatible;
3735
3736 // At this point, we know that T1 and T2 are reference-related (at
3737 // least).
3738
3739 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003740 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003741 // reference-related to T2 and cv1 is the same cv-qualification
3742 // as, or greater cv-qualification than, cv2. For purposes of
3743 // overload resolution, cases for which cv1 is greater
3744 // cv-qualification than cv2 are identified as
3745 // reference-compatible with added qualification (see 13.3.3.2).
3746 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3747 return Ref_Compatible;
3748 else if (T1.isMoreQualifiedThan(T2))
3749 return Ref_Compatible_With_Added_Qualification;
3750 else
3751 return Ref_Related;
3752}
3753
3754/// CheckReferenceInit - Check the initialization of a reference
3755/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3756/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003757/// list), and DeclType is the type of the declaration. When ICS is
3758/// non-null, this routine will compute the implicit conversion
3759/// sequence according to C++ [over.ics.ref] and will not produce any
3760/// diagnostics; when ICS is null, it will emit diagnostics when any
3761/// errors are found. Either way, a return value of true indicates
3762/// that there was a failure, a return value of false indicates that
3763/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003764///
3765/// When @p SuppressUserConversions, user-defined conversions are
3766/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003767/// When @p AllowExplicit, we also permit explicit user-defined
3768/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003769/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003770/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3771/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003772bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003773Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00003774 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003775 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003776 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003777 ImplicitConversionSequence *ICS,
3778 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003779 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3780
Ted Kremenek6217b802009-07-29 21:53:49 +00003781 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003782 QualType T2 = Init->getType();
3783
Douglas Gregor904eed32008-11-10 20:40:00 +00003784 // If the initializer is the address of an overloaded function, try
3785 // to resolve the overloaded function. If all goes well, T2 is the
3786 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003787 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003788 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003789 ICS != 0);
3790 if (Fn) {
3791 // Since we're performing this reference-initialization for
3792 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003793 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00003794 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003795 return true;
3796
Anders Carlsson96ad5332009-10-21 17:16:23 +00003797 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003798 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003799
3800 T2 = Fn->getType();
3801 }
3802 }
3803
Douglas Gregor15da57e2008-10-29 02:00:59 +00003804 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003805 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003806 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003807 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3808 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003809 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00003810 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003811
3812 // Most paths end in a failed conversion.
3813 if (ICS)
3814 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003815
3816 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003817 // A reference to type "cv1 T1" is initialized by an expression
3818 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003819
3820 // -- If the initializer expression
3821
Sebastian Redla9845802009-03-29 15:27:50 +00003822 // Rvalue references cannot bind to lvalues (N2812).
3823 // There is absolutely no situation where they can. In particular, note that
3824 // this is ill-formed, even if B has a user-defined conversion to A&&:
3825 // B b;
3826 // A&& r = b;
3827 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3828 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00003829 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00003830 << Init->getSourceRange();
3831 return true;
3832 }
3833
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003834 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003835 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3836 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003837 //
3838 // Note that the bit-field check is skipped if we are just computing
3839 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003840 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003841 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003842 BindsDirectly = true;
3843
Douglas Gregor15da57e2008-10-29 02:00:59 +00003844 if (ICS) {
3845 // C++ [over.ics.ref]p1:
3846 // When a parameter of reference type binds directly (8.5.3)
3847 // to an argument expression, the implicit conversion sequence
3848 // is the identity conversion, unless the argument expression
3849 // has a type that is a derived class of the parameter type,
3850 // in which case the implicit conversion sequence is a
3851 // derived-to-base Conversion (13.3.3.1).
3852 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3853 ICS->Standard.First = ICK_Identity;
3854 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3855 ICS->Standard.Third = ICK_Identity;
3856 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3857 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003858 ICS->Standard.ReferenceBinding = true;
3859 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003860 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003861 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003862
3863 // Nothing more to do: the inaccessibility/ambiguity check for
3864 // derived-to-base conversions is suppressed when we're
3865 // computing the implicit conversion sequence (C++
3866 // [over.best.ics]p2).
3867 return false;
3868 } else {
3869 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003870 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3871 if (DerivedToBase)
3872 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003873 else if(CheckExceptionSpecCompatibility(Init, T1))
3874 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00003875 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003876 }
3877 }
3878
3879 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003880 // implicitly converted to an lvalue of type "cv3 T3,"
3881 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003882 // 92) (this conversion is selected by enumerating the
3883 // applicable conversion functions (13.3.1.6) and choosing
3884 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003885 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00003886 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003887 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003888 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003889
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003890 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003891 OverloadedFunctionDecl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003892 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003893 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003894 = Conversions->function_begin();
3895 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003896 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003897 = dyn_cast<FunctionTemplateDecl>(*Func);
3898 CXXConversionDecl *Conv;
3899 if (ConvTemplate)
3900 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3901 else
3902 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00003903
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003904 // If the conversion function doesn't return a reference type,
3905 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003906 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003907 (AllowExplicit || !Conv->isExplicit())) {
3908 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003909 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003910 CandidateSet);
3911 else
3912 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3913 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003914 }
3915
3916 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00003917 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003918 case OR_Success:
3919 // This is a direct binding.
3920 BindsDirectly = true;
3921
3922 if (ICS) {
3923 // C++ [over.ics.ref]p1:
3924 //
3925 // [...] If the parameter binds directly to the result of
3926 // applying a conversion function to the argument
3927 // expression, the implicit conversion sequence is a
3928 // user-defined conversion sequence (13.3.3.1.2), with the
3929 // second standard conversion sequence either an identity
3930 // conversion or, if the conversion function returns an
3931 // entity of a type that is a derived class of the parameter
3932 // type, a derived-to-base Conversion.
3933 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3934 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3935 ICS->UserDefined.After = Best->FinalConversion;
3936 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003937 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003938 assert(ICS->UserDefined.After.ReferenceBinding &&
3939 ICS->UserDefined.After.DirectBinding &&
3940 "Expected a direct reference binding!");
3941 return false;
3942 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003943 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00003944 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003945 CastExpr::CK_UserDefinedConversion,
3946 cast<CXXMethodDecl>(Best->Function),
3947 Owned(Init));
3948 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00003949
3950 if (CheckExceptionSpecCompatibility(Init, T1))
3951 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00003952 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3953 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003954 }
3955 break;
3956
3957 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00003958 if (ICS) {
3959 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3960 Cand != CandidateSet.end(); ++Cand)
3961 if (Cand->Viable)
3962 ICS->ConversionFunctionSet.push_back(Cand->Function);
3963 break;
3964 }
3965 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3966 << Init->getSourceRange();
3967 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003968 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003970 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003971 case OR_Deleted:
3972 // There was no suitable conversion, or we found a deleted
3973 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003974 break;
3975 }
3976 }
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003978 if (BindsDirectly) {
3979 // C++ [dcl.init.ref]p4:
3980 // [...] In all cases where the reference-related or
3981 // reference-compatible relationship of two types is used to
3982 // establish the validity of a reference binding, and T1 is a
3983 // base class of T2, a program that necessitates such a binding
3984 // is ill-formed if T1 is an inaccessible (clause 11) or
3985 // ambiguous (10.2) base class of T2.
3986 //
3987 // Note that we only check this condition when we're allowed to
3988 // complain about errors, because we should not be checking for
3989 // ambiguity (or inaccessibility) unless the reference binding
3990 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003991 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00003992 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00003993 Init->getSourceRange(),
3994 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00003995 else
3996 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003997 }
3998
3999 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004000 // type (i.e., cv1 shall be const), or the reference shall be an
4001 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004002 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004003 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004004 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00004005 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4006 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004007 return true;
4008 }
4009
4010 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004011 // class type, and "cv1 T1" is reference-compatible with
4012 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004013 // following ways (the choice is implementation-defined):
4014 //
4015 // -- The reference is bound to the object represented by
4016 // the rvalue (see 3.10) or to a sub-object within that
4017 // object.
4018 //
Eli Friedman33a31382009-08-05 19:21:58 +00004019 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004020 // a constructor is called to copy the entire rvalue
4021 // object into the temporary. The reference is bound to
4022 // the temporary or to a sub-object within the
4023 // temporary.
4024 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004025 // The constructor that would be used to make the copy
4026 // shall be callable whether or not the copy is actually
4027 // done.
4028 //
Sebastian Redla9845802009-03-29 15:27:50 +00004029 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004030 // freedom, so we will always take the first option and never build
4031 // a temporary in this case. FIXME: We will, however, have to check
4032 // for the presence of a copy constructor in C++98/03 mode.
4033 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004034 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4035 if (ICS) {
4036 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4037 ICS->Standard.First = ICK_Identity;
4038 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4039 ICS->Standard.Third = ICK_Identity;
4040 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4041 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004042 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004043 ICS->Standard.DirectBinding = false;
4044 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004045 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004046 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004047 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4048 if (DerivedToBase)
4049 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004050 else if(CheckExceptionSpecCompatibility(Init, T1))
4051 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004052 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004053 }
4054 return false;
4055 }
4056
Eli Friedman33a31382009-08-05 19:21:58 +00004057 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004058 // initialized from the initializer expression using the
4059 // rules for a non-reference copy initialization (8.5). The
4060 // reference is then bound to the temporary. If T1 is
4061 // reference-related to T2, cv1 must be the same
4062 // cv-qualification as, or greater cv-qualification than,
4063 // cv2; otherwise, the program is ill-formed.
4064 if (RefRelationship == Ref_Related) {
4065 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4066 // we would be reference-compatible or reference-compatible with
4067 // added qualification. But that wasn't the case, so the reference
4068 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004069 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004070 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00004071 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4072 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004073 return true;
4074 }
4075
Douglas Gregor734d9862009-01-30 23:27:23 +00004076 // If at least one of the types is a class type, the types are not
4077 // related, and we aren't allowed any user conversions, the
4078 // reference binding fails. This case is important for breaking
4079 // recursion, since TryImplicitConversion below will attempt to
4080 // create a temporary through the use of a copy constructor.
4081 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4082 (T1->isRecordType() || T2->isRecordType())) {
4083 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004084 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00004085 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4086 return true;
4087 }
4088
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004089 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004090 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004091 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004092 //
Sebastian Redla9845802009-03-29 15:27:50 +00004093 // When a parameter of reference type is not bound directly to
4094 // an argument expression, the conversion sequence is the one
4095 // required to convert the argument expression to the
4096 // underlying type of the reference according to
4097 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4098 // to copy-initializing a temporary of the underlying type with
4099 // the argument expression. Any difference in top-level
4100 // cv-qualification is subsumed by the initialization itself
4101 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004102 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4103 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004104 /*ForceRValue=*/false,
4105 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Sebastian Redla9845802009-03-29 15:27:50 +00004107 // Of course, that's still a reference binding.
4108 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4109 ICS->Standard.ReferenceBinding = true;
4110 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004111 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004112 ImplicitConversionSequence::UserDefinedConversion) {
4113 ICS->UserDefined.After.ReferenceBinding = true;
4114 ICS->UserDefined.After.RRefBinding = isRValRef;
4115 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004116 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4117 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004118 ImplicitConversionSequence Conversions;
4119 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4120 false, false,
4121 Conversions);
4122 if (badConversion) {
4123 if ((Conversions.ConversionKind ==
4124 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004125 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004126 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004127 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4128 for (int j = Conversions.ConversionFunctionSet.size()-1;
4129 j >= 0; j--) {
4130 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4131 Diag(Func->getLocation(), diag::err_ovl_candidate);
4132 }
4133 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004134 else {
4135 if (isRValRef)
4136 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4137 << Init->getSourceRange();
4138 else
4139 Diag(DeclLoc, diag::err_invalid_initialization)
4140 << DeclType << Init->getType() << Init->getSourceRange();
4141 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004142 }
4143 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004144 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004145}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004146
4147/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4148/// of this overloaded operator is well-formed. If so, returns false;
4149/// otherwise, emits appropriate diagnostics and returns true.
4150bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004151 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004152 "Expected an overloaded operator declaration");
4153
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004154 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4155
Mike Stump1eb44332009-09-09 15:08:12 +00004156 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004157 // The allocation and deallocation functions, operator new,
4158 // operator new[], operator delete and operator delete[], are
4159 // described completely in 3.7.3. The attributes and restrictions
4160 // found in the rest of this subclause do not apply to them unless
4161 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00004162 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004163 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004164 return false;
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004165
4166 if (Op == OO_New || Op == OO_Array_New) {
4167 bool ret = false;
4168 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4169 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4170 QualType T = Context.getCanonicalType((*Param)->getType());
4171 if (!T->isDependentType() && SizeTy != T) {
4172 Diag(FnDecl->getLocation(),
4173 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4174 << SizeTy;
4175 ret = true;
4176 }
4177 }
4178 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4179 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4180 return Diag(FnDecl->getLocation(),
4181 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregorcffecd02009-11-12 16:49:45 +00004182 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004183 return ret;
4184 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004185
4186 // C++ [over.oper]p6:
4187 // An operator function shall either be a non-static member
4188 // function or be a non-member function and have at least one
4189 // parameter whose type is a class, a reference to a class, an
4190 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004191 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4192 if (MethodDecl->isStatic())
4193 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004194 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004195 } else {
4196 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004197 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4198 ParamEnd = FnDecl->param_end();
4199 Param != ParamEnd; ++Param) {
4200 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004201 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4202 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004203 ClassOrEnumParam = true;
4204 break;
4205 }
4206 }
4207
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004208 if (!ClassOrEnumParam)
4209 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004210 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004211 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004212 }
4213
4214 // C++ [over.oper]p8:
4215 // An operator function cannot have default arguments (8.3.6),
4216 // except where explicitly stated below.
4217 //
Mike Stump1eb44332009-09-09 15:08:12 +00004218 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004219 // (C++ [over.call]p1).
4220 if (Op != OO_Call) {
4221 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4222 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004223 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004224 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004225 diag::err_operator_overload_default_arg)
4226 << FnDecl->getDeclName();
4227 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004228 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004229 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004230 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004231 }
4232 }
4233
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004234 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4235 { false, false, false }
4236#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4237 , { Unary, Binary, MemberOnly }
4238#include "clang/Basic/OperatorKinds.def"
4239 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004240
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004241 bool CanBeUnaryOperator = OperatorUses[Op][0];
4242 bool CanBeBinaryOperator = OperatorUses[Op][1];
4243 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004244
4245 // C++ [over.oper]p8:
4246 // [...] Operator functions cannot have more or fewer parameters
4247 // than the number required for the corresponding operator, as
4248 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004249 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004250 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004251 if (Op != OO_Call &&
4252 ((NumParams == 1 && !CanBeUnaryOperator) ||
4253 (NumParams == 2 && !CanBeBinaryOperator) ||
4254 (NumParams < 1) || (NumParams > 2))) {
4255 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004256 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004257 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004258 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004259 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004260 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004261 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004262 assert(CanBeBinaryOperator &&
4263 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004264 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004265 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004266
Chris Lattner416e46f2008-11-21 07:57:12 +00004267 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004268 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004269 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004270
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004271 // Overloaded operators other than operator() cannot be variadic.
4272 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004273 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004274 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004275 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004276 }
4277
4278 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004279 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4280 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004281 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004282 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004283 }
4284
4285 // C++ [over.inc]p1:
4286 // The user-defined function called operator++ implements the
4287 // prefix and postfix ++ operator. If this function is a member
4288 // function with no parameters, or a non-member function with one
4289 // parameter of class or enumeration type, it defines the prefix
4290 // increment operator ++ for objects of that type. If the function
4291 // is a member function with one parameter (which shall be of type
4292 // int) or a non-member function with two parameters (the second
4293 // of which shall be of type int), it defines the postfix
4294 // increment operator ++ for objects of that type.
4295 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4296 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4297 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004298 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004299 ParamIsInt = BT->getKind() == BuiltinType::Int;
4300
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004301 if (!ParamIsInt)
4302 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004303 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004304 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004305 }
4306
Sebastian Redl64b45f72009-01-05 20:52:13 +00004307 // Notify the class if it got an assignment operator.
4308 if (Op == OO_Equal) {
4309 // Would have returned earlier otherwise.
4310 assert(isa<CXXMethodDecl>(FnDecl) &&
4311 "Overloaded = not member, but not filtered.");
4312 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4313 Method->getParent()->addedAssignmentOperator(Context, Method);
4314 }
4315
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004316 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004317}
Chris Lattner5a003a42008-12-17 07:09:26 +00004318
Douglas Gregor074149e2009-01-05 19:45:36 +00004319/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4320/// linkage specification, including the language and (if present)
4321/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4322/// the location of the language string literal, which is provided
4323/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4324/// the '{' brace. Otherwise, this linkage specification does not
4325/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004326Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4327 SourceLocation ExternLoc,
4328 SourceLocation LangLoc,
4329 const char *Lang,
4330 unsigned StrSize,
4331 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004332 LinkageSpecDecl::LanguageIDs Language;
4333 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4334 Language = LinkageSpecDecl::lang_c;
4335 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4336 Language = LinkageSpecDecl::lang_cxx;
4337 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004338 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004339 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004340 }
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Chris Lattnercc98eac2008-12-17 07:13:27 +00004342 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004343
Douglas Gregor074149e2009-01-05 19:45:36 +00004344 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004345 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004346 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004347 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004348 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004349 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004350}
4351
Douglas Gregor074149e2009-01-05 19:45:36 +00004352/// ActOnFinishLinkageSpecification - Completely the definition of
4353/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4354/// valid, it's the position of the closing '}' brace in a linkage
4355/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004356Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4357 DeclPtrTy LinkageSpec,
4358 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004359 if (LinkageSpec)
4360 PopDeclContext();
4361 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004362}
4363
Douglas Gregord308e622009-05-18 20:51:54 +00004364/// \brief Perform semantic analysis for the variable declaration that
4365/// occurs within a C++ catch clause, returning the newly-created
4366/// variable.
4367VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004368 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004369 IdentifierInfo *Name,
4370 SourceLocation Loc,
4371 SourceRange Range) {
4372 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004373
4374 // Arrays and functions decay.
4375 if (ExDeclType->isArrayType())
4376 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4377 else if (ExDeclType->isFunctionType())
4378 ExDeclType = Context.getPointerType(ExDeclType);
4379
4380 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4381 // The exception-declaration shall not denote a pointer or reference to an
4382 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004383 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004384 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004385 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004386 Invalid = true;
4387 }
Douglas Gregord308e622009-05-18 20:51:54 +00004388
Sebastian Redl4b07b292008-12-22 19:15:10 +00004389 QualType BaseType = ExDeclType;
4390 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004391 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004392 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004393 BaseType = Ptr->getPointeeType();
4394 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004395 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004396 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004397 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004398 BaseType = Ref->getPointeeType();
4399 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004400 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004401 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004402 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004403 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004404 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004405
Mike Stump1eb44332009-09-09 15:08:12 +00004406 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004407 RequireNonAbstractType(Loc, ExDeclType,
4408 diag::err_abstract_type_in_decl,
4409 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004410 Invalid = true;
4411
Douglas Gregord308e622009-05-18 20:51:54 +00004412 // FIXME: Need to test for ability to copy-construct and destroy the
4413 // exception variable.
4414
Sebastian Redl8351da02008-12-22 21:35:02 +00004415 // FIXME: Need to check for abstract classes.
4416
Mike Stump1eb44332009-09-09 15:08:12 +00004417 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00004418 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004419
4420 if (Invalid)
4421 ExDecl->setInvalidDecl();
4422
4423 return ExDecl;
4424}
4425
4426/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4427/// handler.
4428Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004429 DeclaratorInfo *DInfo = 0;
4430 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004431
4432 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004433 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004434 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004435 // The scope should be freshly made just for us. There is just no way
4436 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004437 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004438 if (PrevDecl->isTemplateParameter()) {
4439 // Maybe we will complain about the shadowed template parameter.
4440 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004441 }
4442 }
4443
Chris Lattnereaaebc72009-04-25 08:06:05 +00004444 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004445 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4446 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004447 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004448 }
4449
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004450 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004451 D.getIdentifier(),
4452 D.getIdentifierLoc(),
4453 D.getDeclSpec().getSourceRange());
4454
Chris Lattnereaaebc72009-04-25 08:06:05 +00004455 if (Invalid)
4456 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Sebastian Redl4b07b292008-12-22 19:15:10 +00004458 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004459 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004460 PushOnScopeChains(ExDecl, S);
4461 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004462 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004463
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004464 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004465 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004466}
Anders Carlssonfb311762009-03-14 00:25:26 +00004467
Mike Stump1eb44332009-09-09 15:08:12 +00004468Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004469 ExprArg assertexpr,
4470 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004471 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004472 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004473 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4474
Anders Carlssonc3082412009-03-14 00:33:21 +00004475 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4476 llvm::APSInt Value(32);
4477 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4478 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4479 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004480 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00004481 }
Anders Carlssonfb311762009-03-14 00:25:26 +00004482
Anders Carlssonc3082412009-03-14 00:33:21 +00004483 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00004484 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00004485 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00004486 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00004487 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00004488 }
4489 }
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Anders Carlsson77d81422009-03-15 17:35:16 +00004491 assertexpr.release();
4492 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004493 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004494 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004496 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004497 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004498}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004499
John McCalldd4a3b02009-09-16 22:47:08 +00004500/// Handle a friend type declaration. This works in tandem with
4501/// ActOnTag.
4502///
4503/// Notes on friend class templates:
4504///
4505/// We generally treat friend class declarations as if they were
4506/// declaring a class. So, for example, the elaborated type specifier
4507/// in a friend declaration is required to obey the restrictions of a
4508/// class-head (i.e. no typedefs in the scope chain), template
4509/// parameters are required to match up with simple template-ids, &c.
4510/// However, unlike when declaring a template specialization, it's
4511/// okay to refer to a template specialization without an empty
4512/// template parameter declaration, e.g.
4513/// friend class A<T>::B<unsigned>;
4514/// We permit this as a special case; if there are any template
4515/// parameters present at all, require proper matching, i.e.
4516/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00004517Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00004518 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00004519 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004520
4521 assert(DS.isFriendSpecified());
4522 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4523
John McCalldd4a3b02009-09-16 22:47:08 +00004524 // Try to convert the decl specifier to a type. This works for
4525 // friend templates because ActOnTag never produces a ClassTemplateDecl
4526 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00004527 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00004528 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4529 if (TheDeclarator.isInvalidType())
4530 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004531
John McCalldd4a3b02009-09-16 22:47:08 +00004532 // This is definitely an error in C++98. It's probably meant to
4533 // be forbidden in C++0x, too, but the specification is just
4534 // poorly written.
4535 //
4536 // The problem is with declarations like the following:
4537 // template <T> friend A<T>::foo;
4538 // where deciding whether a class C is a friend or not now hinges
4539 // on whether there exists an instantiation of A that causes
4540 // 'foo' to equal C. There are restrictions on class-heads
4541 // (which we declare (by fiat) elaborated friend declarations to
4542 // be) that makes this tractable.
4543 //
4544 // FIXME: handle "template <> friend class A<T>;", which
4545 // is possibly well-formed? Who even knows?
4546 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4547 Diag(Loc, diag::err_tagless_friend_type_template)
4548 << DS.getSourceRange();
4549 return DeclPtrTy();
4550 }
4551
John McCall02cace72009-08-28 07:59:38 +00004552 // C++ [class.friend]p2:
4553 // An elaborated-type-specifier shall be used in a friend declaration
4554 // for a class.*
4555 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004556 // This is one of the rare places in Clang where it's legitimate to
4557 // ask about the "spelling" of the type.
4558 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4559 // If we evaluated the type to a record type, suggest putting
4560 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004561 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004562 RecordDecl *RD = RT->getDecl();
4563
4564 std::string InsertionText = std::string(" ") + RD->getKindName();
4565
John McCalle3af0232009-10-07 23:34:25 +00004566 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4567 << (unsigned) RD->getTagKind()
4568 << T
4569 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00004570 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4571 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004572 return DeclPtrTy();
4573 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004574 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4575 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004576 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004577 }
4578 }
4579
John McCalle3af0232009-10-07 23:34:25 +00004580 // Enum types cannot be friends.
4581 if (T->getAs<EnumType>()) {
4582 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4583 << SourceRange(DS.getFriendSpecLoc());
4584 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00004585 }
John McCall02cace72009-08-28 07:59:38 +00004586
John McCall02cace72009-08-28 07:59:38 +00004587 // C++98 [class.friend]p1: A friend of a class is a function
4588 // or class that is not a member of the class . . .
4589 // But that's a silly restriction which nobody implements for
4590 // inner classes, and C++0x removes it anyway, so we only report
4591 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004592 if (!getLangOptions().CPlusPlus0x)
4593 if (const RecordType *RT = T->getAs<RecordType>())
4594 if (RT->getDecl()->getDeclContext() == CurContext)
4595 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004596
John McCalldd4a3b02009-09-16 22:47:08 +00004597 Decl *D;
4598 if (TempParams.size())
4599 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4600 TempParams.size(),
4601 (TemplateParameterList**) TempParams.release(),
4602 T.getTypePtr(),
4603 DS.getFriendSpecLoc());
4604 else
4605 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4606 DS.getFriendSpecLoc());
4607 D->setAccess(AS_public);
4608 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00004609
John McCalldd4a3b02009-09-16 22:47:08 +00004610 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00004611}
4612
John McCallbbbcdd92009-09-11 21:02:39 +00004613Sema::DeclPtrTy
4614Sema::ActOnFriendFunctionDecl(Scope *S,
4615 Declarator &D,
4616 bool IsDefinition,
4617 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00004618 const DeclSpec &DS = D.getDeclSpec();
4619
4620 assert(DS.isFriendSpecified());
4621 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4622
4623 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004624 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004625 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004626
4627 // C++ [class.friend]p1
4628 // A friend of a class is a function or class....
4629 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004630 // It *doesn't* see through dependent types, which is correct
4631 // according to [temp.arg.type]p3:
4632 // If a declaration acquires a function type through a
4633 // type dependent on a template-parameter and this causes
4634 // a declaration that does not use the syntactic form of a
4635 // function declarator to have a function type, the program
4636 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004637 if (!T->isFunctionType()) {
4638 Diag(Loc, diag::err_unexpected_friend);
4639
4640 // It might be worthwhile to try to recover by creating an
4641 // appropriate declaration.
4642 return DeclPtrTy();
4643 }
4644
4645 // C++ [namespace.memdef]p3
4646 // - If a friend declaration in a non-local class first declares a
4647 // class or function, the friend class or function is a member
4648 // of the innermost enclosing namespace.
4649 // - The name of the friend is not found by simple name lookup
4650 // until a matching declaration is provided in that namespace
4651 // scope (either before or after the class declaration granting
4652 // friendship).
4653 // - If a friend function is called, its name may be found by the
4654 // name lookup that considers functions from namespaces and
4655 // classes associated with the types of the function arguments.
4656 // - When looking for a prior declaration of a class or a function
4657 // declared as a friend, scopes outside the innermost enclosing
4658 // namespace scope are not considered.
4659
John McCall02cace72009-08-28 07:59:38 +00004660 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4661 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004662 assert(Name);
4663
John McCall67d1a672009-08-06 02:15:43 +00004664 // The context we found the declaration in, or in which we should
4665 // create the declaration.
4666 DeclContext *DC;
4667
4668 // FIXME: handle local classes
4669
4670 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004671 NamedDecl *PrevDecl = 0;
John McCall67d1a672009-08-06 02:15:43 +00004672 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00004673 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00004674 DC = computeDeclContext(ScopeQual);
4675
4676 // FIXME: handle dependent contexts
4677 if (!DC) return DeclPtrTy();
4678
John McCall7d384dd2009-11-18 07:57:50 +00004679 LookupResult R(*this, Name, Loc, LookupOrdinaryName, ForRedeclaration);
John McCalla24dc2e2009-11-17 02:14:36 +00004680 LookupQualifiedName(R, DC);
John McCallf36e02d2009-10-09 21:13:30 +00004681 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004682
4683 // If searching in that context implicitly found a declaration in
4684 // a different context, treat it like it wasn't found at all.
4685 // TODO: better diagnostics for this case. Suggesting the right
4686 // qualified scope would be nice...
Douglas Gregor182ddf02009-09-28 00:08:27 +00004687 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00004688 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004689 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4690 return DeclPtrTy();
4691 }
4692
4693 // C++ [class.friend]p1: A friend of a class is a function or
4694 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00004695 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00004696 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4697
John McCall67d1a672009-08-06 02:15:43 +00004698 // Otherwise walk out to the nearest namespace scope looking for matches.
4699 } else {
4700 // TODO: handle local class contexts.
4701
4702 DC = CurContext;
4703 while (true) {
4704 // Skip class contexts. If someone can cite chapter and verse
4705 // for this behavior, that would be nice --- it's what GCC and
4706 // EDG do, and it seems like a reasonable intent, but the spec
4707 // really only says that checks for unqualified existing
4708 // declarations should stop at the nearest enclosing namespace,
4709 // not that they should only consider the nearest enclosing
4710 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004711 while (DC->isRecord())
4712 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00004713
John McCall7d384dd2009-11-18 07:57:50 +00004714 LookupResult R(*this, Name, Loc, LookupOrdinaryName, ForRedeclaration);
John McCalla24dc2e2009-11-17 02:14:36 +00004715 LookupQualifiedName(R, DC);
John McCallf36e02d2009-10-09 21:13:30 +00004716 PrevDecl = R.getAsSingleDecl(Context);
John McCall67d1a672009-08-06 02:15:43 +00004717
4718 // TODO: decide what we think about using declarations.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004719 if (PrevDecl)
John McCall67d1a672009-08-06 02:15:43 +00004720 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00004721
John McCall67d1a672009-08-06 02:15:43 +00004722 if (DC->isFileContext()) break;
4723 DC = DC->getParent();
4724 }
4725
4726 // C++ [class.friend]p1: A friend of a class is a function or
4727 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004728 // C++0x changes this for both friend types and functions.
4729 // Most C++ 98 compilers do seem to give an error here, so
4730 // we do, too.
Douglas Gregor182ddf02009-09-28 00:08:27 +00004731 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004732 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4733 }
4734
Douglas Gregor182ddf02009-09-28 00:08:27 +00004735 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00004736 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004737 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4738 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4739 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00004740 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00004741 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4742 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004743 return DeclPtrTy();
4744 }
John McCall67d1a672009-08-06 02:15:43 +00004745 }
4746
Douglas Gregor182ddf02009-09-28 00:08:27 +00004747 bool Redeclaration = false;
4748 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregora735b202009-10-13 14:39:41 +00004749 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00004750 IsDefinition,
4751 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004752 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004753
Douglas Gregor182ddf02009-09-28 00:08:27 +00004754 assert(ND->getDeclContext() == DC);
4755 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00004756
John McCallab88d972009-08-31 22:39:49 +00004757 // Add the function declaration to the appropriate lookup tables,
4758 // adjusting the redeclarations list as necessary. We don't
4759 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004760 //
John McCallab88d972009-08-31 22:39:49 +00004761 // Also update the scope-based lookup if the target context's
4762 // lookup context is in lexical scope.
4763 if (!CurContext->isDependentContext()) {
4764 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00004765 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004766 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00004767 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00004768 }
John McCall02cace72009-08-28 07:59:38 +00004769
4770 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00004771 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00004772 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004773 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004774 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004775
Douglas Gregor182ddf02009-09-28 00:08:27 +00004776 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00004777}
4778
Chris Lattnerb28317a2009-03-28 19:18:32 +00004779void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004780 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Chris Lattnerb28317a2009-03-28 19:18:32 +00004782 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004783 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4784 if (!Fn) {
4785 Diag(DelLoc, diag::err_deleted_non_function);
4786 return;
4787 }
4788 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4789 Diag(DelLoc, diag::err_deleted_decl_not_first);
4790 Diag(Prev->getLocation(), diag::note_previous_declaration);
4791 // If the declaration wasn't the first, we delete the function anyway for
4792 // recovery.
4793 }
4794 Fn->setDeleted();
4795}
Sebastian Redl13e88542009-04-27 21:33:24 +00004796
4797static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4798 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4799 ++CI) {
4800 Stmt *SubStmt = *CI;
4801 if (!SubStmt)
4802 continue;
4803 if (isa<ReturnStmt>(SubStmt))
4804 Self.Diag(SubStmt->getSourceRange().getBegin(),
4805 diag::err_return_in_constructor_handler);
4806 if (!isa<Expr>(SubStmt))
4807 SearchForReturnInStmt(Self, SubStmt);
4808 }
4809}
4810
4811void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4812 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4813 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4814 SearchForReturnInStmt(*this, Handler);
4815 }
4816}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004817
Mike Stump1eb44332009-09-09 15:08:12 +00004818bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004819 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00004820 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4821 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004822
4823 QualType CNewTy = Context.getCanonicalType(NewTy);
4824 QualType COldTy = Context.getCanonicalType(OldTy);
4825
Mike Stump1eb44332009-09-09 15:08:12 +00004826 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00004827 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004828 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004829
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004830 // Check if the return types are covariant
4831 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004832
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004833 /// Both types must be pointers or references to classes.
4834 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4835 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4836 NewClassTy = NewPT->getPointeeType();
4837 OldClassTy = OldPT->getPointeeType();
4838 }
4839 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4840 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4841 NewClassTy = NewRT->getPointeeType();
4842 OldClassTy = OldRT->getPointeeType();
4843 }
4844 }
Mike Stump1eb44332009-09-09 15:08:12 +00004845
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004846 // The return types aren't either both pointers or references to a class type.
4847 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004848 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004849 diag::err_different_return_type_for_overriding_virtual_function)
4850 << New->getDeclName() << NewTy << OldTy;
4851 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004853 return true;
4854 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004855
Douglas Gregora4923eb2009-11-16 21:35:15 +00004856 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004857 // Check if the new class derives from the old class.
4858 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4859 Diag(New->getLocation(),
4860 diag::err_covariant_return_not_derived)
4861 << New->getDeclName() << NewTy << OldTy;
4862 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4863 return true;
4864 }
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004866 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004867 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004868 diag::err_covariant_return_inaccessible_base,
4869 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4870 // FIXME: Should this point to the return type?
4871 New->getLocation(), SourceRange(), New->getDeclName())) {
4872 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4873 return true;
4874 }
4875 }
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004877 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004878 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004879 Diag(New->getLocation(),
4880 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004881 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004882 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4883 return true;
4884 };
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004886
4887 // The new class type must have the same or less qualifiers as the old type.
4888 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4889 Diag(New->getLocation(),
4890 diag::err_covariant_return_type_class_type_more_qualified)
4891 << New->getDeclName() << NewTy << OldTy;
4892 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4893 return true;
4894 };
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004896 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004897}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004898
4899/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4900/// initializer for the declaration 'Dcl'.
4901/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4902/// static data member of class X, names should be looked up in the scope of
4903/// class X.
4904void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004905 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004906
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004907 Decl *D = Dcl.getAs<Decl>();
4908 // If there is no declaration, there was an error parsing it.
4909 if (D == 0)
4910 return;
4911
4912 // Check whether it is a declaration with a nested name specifier like
4913 // int foo::bar;
4914 if (!D->isOutOfLine())
4915 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004916
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004917 // C++ [basic.lookup.unqual]p13
4918 //
4919 // A name used in the definition of a static data member of class X
4920 // (after the qualified-id of the static member) is looked up as if the name
4921 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004923 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004924 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004925}
4926
4927/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4928/// initializer for the declaration 'Dcl'.
4929void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004930 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004931
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004932 Decl *D = Dcl.getAs<Decl>();
4933 // If there is no declaration, there was an error parsing it.
4934 if (D == 0)
4935 return;
4936
4937 // Check whether it is a declaration with a nested name specifier like
4938 // int foo::bar;
4939 if (!D->isOutOfLine())
4940 return;
4941
4942 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004943 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004944}