blob: b00b1886f14b0e26dbba3185cbaf6cdbb6b84a8e [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"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000112 QualType ParamType = Param->getType();
113
Anders Carlsson5653ca52009-08-25 13:46:13 +0000114 if (RequireCompleteType(Param->getLocation(), Param->getType(),
115 diag::err_typecheck_decl_incomplete_type)) {
116 Param->setInvalidDecl();
117 return true;
118 }
119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000128 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000129 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000130 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000131
132 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Anders Carlssoned961f92009-08-25 02:29:20 +0000134 // Okay: add the default argument to the parameter
135 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Anders Carlssoned961f92009-08-25 02:29:20 +0000137 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlsson9351c172009-08-25 03:18:48 +0000139 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000140}
141
Chris Lattner8123a952008-04-10 02:22:51 +0000142/// ActOnParamDefaultArgument - Check whether the default argument
143/// provided for a function parameter is well-formed. If so, attach it
144/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000145void
Mike Stump1eb44332009-09-09 15:08:12 +0000146Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000147 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000148 if (!param || !defarg.get())
149 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattnerb28317a2009-03-28 19:18:32 +0000151 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000152 UnparsedDefaultArgLocs.erase(Param);
153
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000154 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000155 QualType ParamType = Param->getType();
156
157 // Default arguments are only permitted in C++
158 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000159 Diag(EqualLoc, diag::err_param_default_argument)
160 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000161 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000162 return;
163 }
164
Anders Carlsson66e30672009-08-25 01:02:06 +0000165 // Check that the default argument is well-formed
166 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
167 if (DefaultArgChecker.Visit(DefaultArg.get())) {
168 Param->setInvalidDecl();
169 return;
170 }
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Anders Carlssoned961f92009-08-25 02:29:20 +0000172 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000173}
174
Douglas Gregor61366e92008-12-24 00:01:03 +0000175/// ActOnParamUnparsedDefaultArgument - We've seen a default
176/// argument for a function parameter, but we can't parse it yet
177/// because we're inside a class definition. Note that this default
178/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000179void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000180 SourceLocation EqualLoc,
181 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000182 if (!param)
183 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000186 if (Param)
187 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Anders Carlsson5e300d12009-06-12 16:51:40 +0000189 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000190}
191
Douglas Gregor72b505b2008-12-16 21:30:33 +0000192/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
193/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000194void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000195 if (!param)
196 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlsson5e300d12009-06-12 16:51:40 +0000198 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Anders Carlsson5e300d12009-06-12 16:51:40 +0000200 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000203}
204
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000205/// CheckExtraCXXDefaultArguments - Check for any extra default
206/// arguments in the declarator, which is not a function declaration
207/// or definition and therefore is not permitted to have default
208/// arguments. This routine should be invoked for every declarator
209/// that is not a function declaration or definition.
210void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
211 // C++ [dcl.fct.default]p3
212 // A default argument expression shall be specified only in the
213 // parameter-declaration-clause of a function declaration or in a
214 // template-parameter (14.1). It shall not be specified for a
215 // parameter pack. If it is specified in a
216 // parameter-declaration-clause, it shall not occur within a
217 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000219 DeclaratorChunk &chunk = D.getTypeObject(i);
220 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
222 ParmVarDecl *Param =
223 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000224 if (Param->hasUnparsedDefaultArg()) {
225 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000226 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
227 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
228 delete Toks;
229 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000230 } else if (Param->getDefaultArg()) {
231 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
232 << Param->getDefaultArg()->getSourceRange();
233 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000234 }
235 }
236 }
237 }
238}
239
Chris Lattner3d1cee32008-04-08 05:04:30 +0000240// MergeCXXFunctionDecl - Merge two declarations of the same C++
241// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000242// type. Subroutine of MergeFunctionDecl. Returns true if there was an
243// error, false otherwise.
244bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
245 bool Invalid = false;
246
Chris Lattner3d1cee32008-04-08 05:04:30 +0000247 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000248 // For non-template functions, default arguments can be added in
249 // later declarations of a function in the same
250 // scope. Declarations in different scopes have completely
251 // distinct sets of default arguments. That is, declarations in
252 // inner scopes do not acquire default arguments from
253 // declarations in outer scopes, and vice versa. In a given
254 // function declaration, all parameters subsequent to a
255 // parameter with a default argument shall have default
256 // arguments supplied in this or previous declarations. A
257 // default argument shall not be redefined by a later
258 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000259 //
260 // C++ [dcl.fct.default]p6:
261 // Except for member functions of class templates, the default arguments
262 // in a member function definition that appears outside of the class
263 // definition are added to the set of default arguments provided by the
264 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000265 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
266 ParmVarDecl *OldParam = Old->getParamDecl(p);
267 ParmVarDecl *NewParam = New->getParamDecl(p);
268
Douglas Gregor6cc15182009-09-11 18:44:32 +0000269 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlssonad26b732009-11-10 03:24:44 +0000270 // FIXME: If the parameter doesn't have an identifier then the location
271 // points to the '=' which means that the fixit hint won't remove any
272 // extra spaces between the type and the '='.
273 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson4881b992009-11-10 03:32:44 +0000274 if (NewParam->getIdentifier())
275 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlssonad26b732009-11-10 03:24:44 +0000276
Mike Stump1eb44332009-09-09 15:08:12 +0000277 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000278 diag::err_param_default_argument_redefinition)
Anders Carlssonad26b732009-11-10 03:24:44 +0000279 << NewParam->getDefaultArgRange()
280 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
281 NewParam->getLocEnd()));
Douglas Gregor6cc15182009-09-11 18:44:32 +0000282
283 // Look for the function declaration where the default argument was
284 // actually written, which may be a declaration prior to Old.
285 for (FunctionDecl *Older = Old->getPreviousDeclaration();
286 Older; Older = Older->getPreviousDeclaration()) {
287 if (!Older->getParamDecl(p)->hasDefaultArg())
288 break;
289
290 OldParam = Older->getParamDecl(p);
291 }
292
293 Diag(OldParam->getLocation(), diag::note_previous_definition)
294 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000295 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000296 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000297 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000298 if (OldParam->hasUninstantiatedDefaultArg())
299 NewParam->setUninstantiatedDefaultArg(
300 OldParam->getUninstantiatedDefaultArg());
301 else
302 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000303 } else if (NewParam->hasDefaultArg()) {
304 if (New->getDescribedFunctionTemplate()) {
305 // Paragraph 4, quoted above, only applies to non-template functions.
306 Diag(NewParam->getLocation(),
307 diag::err_param_default_argument_template_redecl)
308 << NewParam->getDefaultArgRange();
309 Diag(Old->getLocation(), diag::note_template_prev_declaration)
310 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000311 } else if (New->getTemplateSpecializationKind()
312 != TSK_ImplicitInstantiation &&
313 New->getTemplateSpecializationKind() != TSK_Undeclared) {
314 // C++ [temp.expr.spec]p21:
315 // Default function arguments shall not be specified in a declaration
316 // or a definition for one of the following explicit specializations:
317 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000318 // - the explicit specialization of a member function template;
319 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000320 // template where the class template specialization to which the
321 // member function specialization belongs is implicitly
322 // instantiated.
323 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
324 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
325 << New->getDeclName()
326 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000327 } else if (New->getDeclContext()->isDependentContext()) {
328 // C++ [dcl.fct.default]p6 (DR217):
329 // Default arguments for a member function of a class template shall
330 // be specified on the initial declaration of the member function
331 // within the class template.
332 //
333 // Reading the tea leaves a bit in DR217 and its reference to DR205
334 // leads me to the conclusion that one cannot add default function
335 // arguments for an out-of-line definition of a member function of a
336 // dependent type.
337 int WhichKind = 2;
338 if (CXXRecordDecl *Record
339 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
340 if (Record->getDescribedClassTemplate())
341 WhichKind = 0;
342 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
343 WhichKind = 1;
344 else
345 WhichKind = 2;
346 }
347
348 Diag(NewParam->getLocation(),
349 diag::err_param_default_argument_member_template_redecl)
350 << WhichKind
351 << NewParam->getDefaultArgRange();
352 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000353 }
354 }
355
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000356 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000357 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000358 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000360
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");
Eli Friedmand0137332009-12-05 23:03:49 +0000488
Sean Huntbbd37c62009-11-21 08:43:09 +0000489 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
490 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
491 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000492 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
493 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000494 return 0;
495 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000496
Eli Friedmand0137332009-12-05 23:03:49 +0000497 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000498
499 // Create the base specifier.
500 // FIXME: Allocate via ASTContext?
501 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
502 Class->getTagKind() == RecordDecl::TK_class,
503 Access, BaseType);
504}
505
506void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
507 const CXXRecordDecl *BaseClass,
508 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000509 // A class with a non-empty base class is not empty.
510 // FIXME: Standard ref?
511 if (!BaseClass->isEmpty())
512 Class->setEmpty(false);
513
514 // C++ [class.virtual]p1:
515 // A class that [...] inherits a virtual function is called a polymorphic
516 // class.
517 if (BaseClass->isPolymorphic())
518 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000519
Douglas Gregor2943aed2009-03-03 04:44:36 +0000520 // C++ [dcl.init.aggr]p1:
521 // An aggregate is [...] a class with [...] no base classes [...].
522 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000523
524 // C++ [class]p4:
525 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000526 Class->setPOD(false);
527
Anders Carlsson51f94042009-12-03 17:49:57 +0000528 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000529 // C++ [class.ctor]p5:
530 // A constructor is trivial if its class has no virtual base classes.
531 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000532
533 // C++ [class.copy]p6:
534 // A copy constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialCopyConstructor(false);
536
537 // C++ [class.copy]p11:
538 // A copy assignment operator is trivial if its class has no virtual
539 // base classes.
540 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000541
542 // C++0x [meta.unary.prop] is_empty:
543 // T is a class type, but not a union type, with ... no virtual base
544 // classes
545 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000546 } else {
547 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000548 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000550 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000551 Class->setHasTrivialConstructor(false);
552
553 // C++ [class.copy]p6:
554 // A copy constructor is trivial if all the direct base classes of its
555 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000557 Class->setHasTrivialCopyConstructor(false);
558
559 // C++ [class.copy]p11:
560 // A copy assignment operator is trivial if all the direct base classes
561 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000564 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000565
566 // C++ [class.ctor]p3:
567 // A destructor is trivial if all the direct base classes of its class
568 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000569 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000570 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000571}
572
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000573/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
574/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000575/// example:
576/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000578Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000579Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000580 bool Virtual, AccessSpecifier Access,
581 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000582 if (!classdecl)
583 return true;
584
Douglas Gregor40808ce2009-03-09 23:48:35 +0000585 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000586 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000587 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000588 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
589 Virtual, Access,
590 BaseType, BaseLoc))
591 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000594}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596/// \brief Performs the actual work of attaching the given base class
597/// specifiers to a C++ class.
598bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
599 unsigned NumBases) {
600 if (NumBases == 0)
601 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000602
603 // Used to keep track of which base types we have already seen, so
604 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000605 // that the key is always the unqualified canonical type of the base
606 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000607 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
608
609 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000610 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000611 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000612 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000613 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000615 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000616
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000617 if (KnownBaseTypes[NewBaseType]) {
618 // C++ [class.mi]p3:
619 // A class shall not be specified as a direct base class of a
620 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000622 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000623 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000625
626 // Delete the duplicate base class specifier; we're going to
627 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000628 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629
630 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000631 } else {
632 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000633 KnownBaseTypes[NewBaseType] = Bases[idx];
634 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000635 }
636 }
637
638 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000639 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000640
641 // Delete the remaining (good) base class specifiers, since their
642 // data has been copied into the CXXRecordDecl.
643 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000644 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000645
646 return Invalid;
647}
648
649/// ActOnBaseSpecifiers - Attach the given base specifiers to the
650/// class, after checking whether there are any duplicate base
651/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000652void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653 unsigned NumBases) {
654 if (!ClassDecl || !Bases || !NumBases)
655 return;
656
657 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000658 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000660}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000661
Douglas Gregora8f32e02009-10-06 17:59:45 +0000662/// \brief Determine whether the type \p Derived is a C++ class that is
663/// derived from the type \p Base.
664bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
665 if (!getLangOptions().CPlusPlus)
666 return false;
667
668 const RecordType *DerivedRT = Derived->getAs<RecordType>();
669 if (!DerivedRT)
670 return false;
671
672 const RecordType *BaseRT = Base->getAs<RecordType>();
673 if (!BaseRT)
674 return false;
675
676 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
677 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
678 return DerivedRD->isDerivedFrom(BaseRD);
679}
680
681/// \brief Determine whether the type \p Derived is a C++ class that is
682/// derived from the type \p Base.
683bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
684 if (!getLangOptions().CPlusPlus)
685 return false;
686
687 const RecordType *DerivedRT = Derived->getAs<RecordType>();
688 if (!DerivedRT)
689 return false;
690
691 const RecordType *BaseRT = Base->getAs<RecordType>();
692 if (!BaseRT)
693 return false;
694
695 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
696 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
697 return DerivedRD->isDerivedFrom(BaseRD, Paths);
698}
699
700/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
701/// conversion (where Derived and Base are class types) is
702/// well-formed, meaning that the conversion is unambiguous (and
703/// that all of the base classes are accessible). Returns true
704/// and emits a diagnostic if the code is ill-formed, returns false
705/// otherwise. Loc is the location where this routine should point to
706/// if there is an error, and Range is the source range to highlight
707/// if there is an error.
708bool
709Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
710 unsigned InaccessibleBaseID,
711 unsigned AmbigiousBaseConvID,
712 SourceLocation Loc, SourceRange Range,
713 DeclarationName Name) {
714 // First, determine whether the path from Derived to Base is
715 // ambiguous. This is slightly more expensive than checking whether
716 // the Derived to Base conversion exists, because here we need to
717 // explore multiple paths to determine if there is an ambiguity.
718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
719 /*DetectVirtual=*/false);
720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
721 assert(DerivationOkay &&
722 "Can only be used with a derived-to-base conversion");
723 (void)DerivationOkay;
724
725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000726 if (InaccessibleBaseID == 0)
727 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000728 // Check that the base class can be accessed.
729 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
730 Name);
731 }
732
733 // We know that the derived-to-base conversion is ambiguous, and
734 // we're going to produce a diagnostic. Perform the derived-to-base
735 // search just one more time to compute all of the possible paths so
736 // that we can print them out. This is more expensive than any of
737 // the previous derived-to-base checks we've done, but at this point
738 // performance isn't as much of an issue.
739 Paths.clear();
740 Paths.setRecordingPaths(true);
741 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
742 assert(StillOkay && "Can only be used with a derived-to-base conversion");
743 (void)StillOkay;
744
745 // Build up a textual representation of the ambiguous paths, e.g.,
746 // D -> B -> A, that will be used to illustrate the ambiguous
747 // conversions in the diagnostic. We only print one of the paths
748 // to each base class subobject.
749 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
750
751 Diag(Loc, AmbigiousBaseConvID)
752 << Derived << Base << PathDisplayStr << Range << Name;
753 return true;
754}
755
756bool
757Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000758 SourceLocation Loc, SourceRange Range,
759 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000760 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000761 IgnoreAccess ? 0 :
762 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000763 diag::err_ambiguous_derived_to_base_conv,
764 Loc, Range, DeclarationName());
765}
766
767
768/// @brief Builds a string representing ambiguous paths from a
769/// specific derived class to different subobjects of the same base
770/// class.
771///
772/// This function builds a string that can be used in error messages
773/// to show the different paths that one can take through the
774/// inheritance hierarchy to go from the derived class to different
775/// subobjects of a base class. The result looks something like this:
776/// @code
777/// struct D -> struct B -> struct A
778/// struct D -> struct C -> struct A
779/// @endcode
780std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
781 std::string PathDisplayStr;
782 std::set<unsigned> DisplayedPaths;
783 for (CXXBasePaths::paths_iterator Path = Paths.begin();
784 Path != Paths.end(); ++Path) {
785 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
786 // We haven't displayed a path to this particular base
787 // class subobject yet.
788 PathDisplayStr += "\n ";
789 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
790 for (CXXBasePath::const_iterator Element = Path->begin();
791 Element != Path->end(); ++Element)
792 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
793 }
794 }
795
796 return PathDisplayStr;
797}
798
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000799//===----------------------------------------------------------------------===//
800// C++ class member Handling
801//===----------------------------------------------------------------------===//
802
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000803/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
804/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
805/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000806/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000807Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000808Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000809 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000810 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
811 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000812 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000813 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000814 Expr *BitWidth = static_cast<Expr*>(BW);
815 Expr *Init = static_cast<Expr*>(InitExpr);
816 SourceLocation Loc = D.getIdentifierLoc();
817
Sebastian Redl669d5d72008-11-14 23:42:31 +0000818 bool isFunc = D.isFunctionDeclarator();
819
John McCall67d1a672009-08-06 02:15:43 +0000820 assert(!DS.isFriendSpecified());
821
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000822 // C++ 9.2p6: A member shall not be declared to have automatic storage
823 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
825 // data members and cannot be applied to names declared const or static,
826 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000827 switch (DS.getStorageClassSpec()) {
828 case DeclSpec::SCS_unspecified:
829 case DeclSpec::SCS_typedef:
830 case DeclSpec::SCS_static:
831 // FALL THROUGH.
832 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000833 case DeclSpec::SCS_mutable:
834 if (isFunc) {
835 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000836 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000837 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000838 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Sebastian Redla11f42f2008-11-17 23:24:37 +0000840 // FIXME: It would be nicer if the keyword was ignored only for this
841 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000842 D.getMutableDeclSpec().ClearStorageClassSpecs();
843 } else {
844 QualType T = GetTypeForDeclarator(D, S);
845 diag::kind err = static_cast<diag::kind>(0);
846 if (T->isReferenceType())
847 err = diag::err_mutable_reference;
848 else if (T.isConstQualified())
849 err = diag::err_mutable_const;
850 if (err != 0) {
851 if (DS.getStorageClassSpecLoc().isValid())
852 Diag(DS.getStorageClassSpecLoc(), err);
853 else
854 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000855 // FIXME: It would be nicer if the keyword was ignored only for this
856 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 D.getMutableDeclSpec().ClearStorageClassSpecs();
858 }
859 }
860 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000861 default:
862 if (DS.getStorageClassSpecLoc().isValid())
863 Diag(DS.getStorageClassSpecLoc(),
864 diag::err_storageclass_invalid_for_member);
865 else
866 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
867 D.getMutableDeclSpec().ClearStorageClassSpecs();
868 }
869
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000870 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000871 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000872 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000873 // Check also for this case:
874 //
875 // typedef int f();
876 // f a;
877 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000878 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000879 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000880 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000881
Sebastian Redl669d5d72008-11-14 23:42:31 +0000882 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
883 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000884 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885
886 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000887 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000888 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000889 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
890 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000891 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000892 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000893 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000894 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000895 if (!Member) {
896 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000897 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000898 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000899
900 // Non-instance-fields can't have a bitfield.
901 if (BitWidth) {
902 if (Member->isInvalidDecl()) {
903 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000904 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000905 // C++ 9.6p3: A bit-field shall not be a static member.
906 // "static member 'A' cannot be a bit-field"
907 Diag(Loc, diag::err_static_not_bitfield)
908 << Name << BitWidth->getSourceRange();
909 } else if (isa<TypedefDecl>(Member)) {
910 // "typedef member 'x' cannot be a bit-field"
911 Diag(Loc, diag::err_typedef_not_bitfield)
912 << Name << BitWidth->getSourceRange();
913 } else {
914 // A function typedef ("typedef int f(); f a;").
915 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
916 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000917 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000918 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Chris Lattner8b963ef2009-03-05 23:01:03 +0000921 DeleteExpr(BitWidth);
922 BitWidth = 0;
923 Member->setInvalidDecl();
924 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000925
926 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregor37b372b2009-08-20 22:52:58 +0000928 // If we have declared a member function template, set the access of the
929 // templated declaration as well.
930 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
931 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000932 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000933
Douglas Gregor10bd3682008-11-17 22:58:34 +0000934 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000935
Douglas Gregor021c3b32009-03-11 23:00:04 +0000936 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000937 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000938 if (Deleted) // FIXME: Source location is not very good.
939 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000940
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000941 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000942 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000943 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000944 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000945 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000946}
947
Douglas Gregor7ad83902008-11-05 04:29:56 +0000948/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000949Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000950Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000951 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000952 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000953 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000954 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000955 SourceLocation IdLoc,
956 SourceLocation LParenLoc,
957 ExprTy **Args, unsigned NumArgs,
958 SourceLocation *CommaLocs,
959 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000960 if (!ConstructorD)
961 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000963 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000964
965 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000966 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000967 if (!Constructor) {
968 // The user wrote a constructor initializer on a function that is
969 // not a C++ constructor. Ignore the error for now, because we may
970 // have more member initializers coming; we'll diagnose it just
971 // once in ActOnMemInitializers.
972 return true;
973 }
974
975 CXXRecordDecl *ClassDecl = Constructor->getParent();
976
977 // C++ [class.base.init]p2:
978 // Names in a mem-initializer-id are looked up in the scope of the
979 // constructor’s class and, if not found in that scope, are looked
980 // up in the scope containing the constructor’s
981 // definition. [Note: if the constructor’s class contains a member
982 // with the same name as a direct or virtual base class of the
983 // class, a mem-initializer-id naming the member or base class and
984 // composed of a single identifier refers to the class member. A
985 // mem-initializer-id for the hidden base class may be specified
986 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000987 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000988 // Look for a member, first.
989 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000990 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000991 = ClassDecl->lookup(MemberOrBase);
992 if (Result.first != Result.second)
993 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000994
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000995 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000996
Eli Friedman59c04372009-07-29 19:44:27 +0000997 if (Member)
998 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +0000999 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001000 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001001 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001002 QualType BaseType;
1003
John McCalla93c9342009-12-07 02:54:59 +00001004 TypeSourceInfo *TInfo = 0;
Douglas Gregor802ab452009-12-02 22:36:29 +00001005 if (TemplateTypeTy)
John McCalla93c9342009-12-07 02:54:59 +00001006 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
Douglas Gregor802ab452009-12-02 22:36:29 +00001007 else
1008 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
1009 S, &SS));
1010 if (BaseType.isNull())
Chris Lattner3c73c412008-11-19 08:23:25 +00001011 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1012 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001013
John McCalla93c9342009-12-07 02:54:59 +00001014 if (!TInfo)
1015 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001016
John McCalla93c9342009-12-07 02:54:59 +00001017 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001018 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001019}
1020
John McCallb4190042009-11-04 23:02:40 +00001021/// Checks an initializer expression for use of uninitialized fields, such as
1022/// containing the field that is being initialized. Returns true if there is an
1023/// uninitialized field was used an updates the SourceLocation parameter; false
1024/// otherwise.
1025static bool InitExprContainsUninitializedFields(const Stmt* S,
1026 const FieldDecl* LhsField,
1027 SourceLocation* L) {
1028 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1029 if (ME) {
1030 const NamedDecl* RhsField = ME->getMemberDecl();
1031 if (RhsField == LhsField) {
1032 // Initializing a field with itself. Throw a warning.
1033 // But wait; there are exceptions!
1034 // Exception #1: The field may not belong to this record.
1035 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1036 const Expr* base = ME->getBase();
1037 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1038 // Even though the field matches, it does not belong to this record.
1039 return false;
1040 }
1041 // None of the exceptions triggered; return true to indicate an
1042 // uninitialized field was used.
1043 *L = ME->getMemberLoc();
1044 return true;
1045 }
1046 }
1047 bool found = false;
1048 for (Stmt::const_child_iterator it = S->child_begin();
1049 it != S->child_end() && found == false;
1050 ++it) {
1051 if (isa<CallExpr>(S)) {
1052 // Do not descend into function calls or constructors, as the use
1053 // of an uninitialized field may be valid. One would have to inspect
1054 // the contents of the function/ctor to determine if it is safe or not.
1055 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1056 // may be safe, depending on what the function/ctor does.
1057 continue;
1058 }
1059 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1060 }
1061 return found;
1062}
1063
Eli Friedman59c04372009-07-29 19:44:27 +00001064Sema::MemInitResult
1065Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1066 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001067 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001068 SourceLocation RParenLoc) {
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001069 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1070 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1071 ExprTemporaries.clear();
1072
John McCallb4190042009-11-04 23:02:40 +00001073 // Diagnose value-uses of fields to initialize themselves, e.g.
1074 // foo(foo)
1075 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001076 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001077 for (unsigned i = 0; i < NumArgs; ++i) {
1078 SourceLocation L;
1079 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1080 // FIXME: Return true in the case when other fields are used before being
1081 // uninitialized. For example, let this field be the i'th field. When
1082 // initializing the i'th field, throw a warning if any of the >= i'th
1083 // fields are used, as they are not yet initialized.
1084 // Right now we are only handling the case where the i'th field uses
1085 // itself in its initializer.
1086 Diag(L, diag::warn_field_is_uninit);
1087 }
1088 }
1089
Eli Friedman59c04372009-07-29 19:44:27 +00001090 bool HasDependentArg = false;
1091 for (unsigned i = 0; i < NumArgs; i++)
1092 HasDependentArg |= Args[i]->isTypeDependent();
1093
1094 CXXConstructorDecl *C = 0;
1095 QualType FieldType = Member->getType();
1096 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1097 FieldType = Array->getElementType();
1098 if (FieldType->isDependentType()) {
1099 // Can't check init for dependent type.
John McCall6aee6212009-11-04 23:13:52 +00001100 } else if (FieldType->isRecordType()) {
1101 // Member is a record (struct/union/class), so pass the initializer
1102 // arguments down to the record's constructor.
Douglas Gregor39da0b82009-09-09 23:08:42 +00001103 if (!HasDependentArg) {
1104 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1105
1106 C = PerformInitializationByConstructor(FieldType,
1107 MultiExprArg(*this,
1108 (void**)Args,
1109 NumArgs),
1110 IdLoc,
1111 SourceRange(IdLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001112 Member->getDeclName(),
1113 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001114 ConstructorArgs);
1115
1116 if (C) {
1117 // Take over the constructor arguments as our own.
1118 NumArgs = ConstructorArgs.size();
1119 Args = (Expr **)ConstructorArgs.take();
1120 }
1121 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001122 } else if (NumArgs != 1 && NumArgs != 0) {
John McCall6aee6212009-11-04 23:13:52 +00001123 // The member type is not a record type (or an array of record
1124 // types), so it can be only be default- or copy-initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00001125 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +00001126 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1127 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001128 Expr *NewExp;
1129 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001130 if (FieldType->isReferenceType()) {
1131 Diag(IdLoc, diag::err_null_intialized_reference_member)
1132 << Member->getDeclName();
1133 return Diag(Member->getLocation(), diag::note_declared_at);
1134 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +00001135 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1136 NumArgs = 1;
1137 }
1138 else
1139 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +00001140 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1141 return true;
1142 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +00001143 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001144
1145 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1146 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1147 ExprTemporaries.clear();
1148
Eli Friedman59c04372009-07-29 19:44:27 +00001149 // FIXME: Perform direct initialization of the member.
Douglas Gregor802ab452009-12-02 22:36:29 +00001150 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1151 C, LParenLoc, (Expr **)Args,
1152 NumArgs, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001153}
1154
1155Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001156Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001157 Expr **Args, unsigned NumArgs,
1158 SourceLocation LParenLoc, SourceLocation RParenLoc,
1159 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001160 bool HasDependentArg = false;
1161 for (unsigned i = 0; i < NumArgs; i++)
1162 HasDependentArg |= Args[i]->isTypeDependent();
1163
John McCalla93c9342009-12-07 02:54:59 +00001164 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman59c04372009-07-29 19:44:27 +00001165 if (!BaseType->isDependentType()) {
1166 if (!BaseType->isRecordType())
Douglas Gregor802ab452009-12-02 22:36:29 +00001167 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
John McCalla93c9342009-12-07 02:54:59 +00001168 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001169
1170 // C++ [class.base.init]p2:
1171 // [...] Unless the mem-initializer-id names a nonstatic data
1172 // member of the constructor’s class or a direct or virtual base
1173 // of that class, the mem-initializer is ill-formed. A
1174 // mem-initializer-list can initialize a base class using any
1175 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Eli Friedman59c04372009-07-29 19:44:27 +00001177 // First, check for a direct base class.
1178 const CXXBaseSpecifier *DirectBaseSpec = 0;
1179 for (CXXRecordDecl::base_class_const_iterator Base =
1180 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00001181 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman59c04372009-07-29 19:44:27 +00001182 // We found a direct base of this type. That's what we're
1183 // initializing.
1184 DirectBaseSpec = &*Base;
1185 break;
1186 }
1187 }
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Eli Friedman59c04372009-07-29 19:44:27 +00001189 // Check for a virtual base class.
1190 // FIXME: We might be able to short-circuit this if we know in advance that
1191 // there are no virtual bases.
1192 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1193 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1194 // We haven't found a base yet; search the class hierarchy for a
1195 // virtual base class.
Douglas Gregora8f32e02009-10-06 17:59:45 +00001196 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1197 /*DetectVirtual=*/false);
Eli Friedman59c04372009-07-29 19:44:27 +00001198 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001199 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +00001200 Path != Paths.end(); ++Path) {
1201 if (Path->back().Base->isVirtual()) {
1202 VirtualBaseSpec = Path->back().Base;
1203 break;
1204 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001205 }
1206 }
1207 }
Eli Friedman59c04372009-07-29 19:44:27 +00001208
1209 // C++ [base.class.init]p2:
1210 // If a mem-initializer-id is ambiguous because it designates both
1211 // a direct non-virtual base class and an inherited virtual base
1212 // class, the mem-initializer is ill-formed.
1213 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001214 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
John McCalla93c9342009-12-07 02:54:59 +00001215 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00001216 // C++ [base.class.init]p2:
1217 // Unless the mem-initializer-id names a nonstatic data membeer of the
1218 // constructor's class ot a direst or virtual base of that class, the
1219 // mem-initializer is ill-formed.
1220 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregor802ab452009-12-02 22:36:29 +00001221 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1222 << BaseType << ClassDecl->getNameAsCString()
John McCalla93c9342009-12-07 02:54:59 +00001223 << BaseTInfo->getTypeLoc().getSourceRange();
Douglas Gregor7ad83902008-11-05 04:29:56 +00001224 }
1225
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +00001226 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +00001227 if (!BaseType->isDependentType() && !HasDependentArg) {
1228 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3eaa9ff2009-11-08 07:12:55 +00001229 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor39da0b82009-09-09 23:08:42 +00001230 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1231
1232 C = PerformInitializationByConstructor(BaseType,
1233 MultiExprArg(*this,
1234 (void**)Args, NumArgs),
Douglas Gregor802ab452009-12-02 22:36:29 +00001235 BaseLoc,
1236 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor20093b42009-12-09 23:02:17 +00001237 Name,
1238 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00001239 ConstructorArgs);
1240 if (C) {
1241 // Take over the constructor arguments as our own.
1242 NumArgs = ConstructorArgs.size();
1243 Args = (Expr **)ConstructorArgs.take();
1244 }
Eli Friedman59c04372009-07-29 19:44:27 +00001245 }
1246
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001247 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1248 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1249 ExprTemporaries.clear();
1250
John McCalla93c9342009-12-07 02:54:59 +00001251 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, C,
Douglas Gregor802ab452009-12-02 22:36:29 +00001252 LParenLoc, (Expr **)Args,
1253 NumArgs, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001254}
1255
Eli Friedman80c30da2009-11-09 19:20:36 +00001256bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001257Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001258 CXXBaseOrMemberInitializer **Initializers,
1259 unsigned NumInitializers,
Eli Friedman49c16da2009-11-09 01:05:47 +00001260 bool IsImplicitConstructor) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001261 // We need to build the initializer AST according to order of construction
1262 // and not what user specified in the Initializers list.
1263 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1264 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1265 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1266 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001267 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001269 for (unsigned i = 0; i < NumInitializers; i++) {
1270 CXXBaseOrMemberInitializer *Member = Initializers[i];
1271 if (Member->isBaseInitializer()) {
1272 if (Member->getBaseClass()->isDependentType())
1273 HasDependentBaseInit = true;
1274 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1275 } else {
1276 AllBaseFields[Member->getMember()] = Member;
1277 }
1278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001280 if (HasDependentBaseInit) {
1281 // FIXME. This does not preserve the ordering of the initializers.
1282 // Try (with -Wreorder)
1283 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001284 // template<class X> struct B : A<X> {
1285 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001286 // int x1;
1287 // };
1288 // B<int> x;
1289 // On seeing one dependent type, we should essentially exit this routine
1290 // while preserving user-declared initializer list. When this routine is
1291 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001292 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001294 // If we have a dependent base initialization, we can't determine the
1295 // association between initializers and bases; just dump the known
1296 // initializers into the list, and don't try to deal with other bases.
1297 for (unsigned i = 0; i < NumInitializers; i++) {
1298 CXXBaseOrMemberInitializer *Member = Initializers[i];
1299 if (Member->isBaseInitializer())
1300 AllToInit.push_back(Member);
1301 }
1302 } else {
1303 // Push virtual bases before others.
1304 for (CXXRecordDecl::base_class_iterator VBase =
1305 ClassDecl->vbases_begin(),
1306 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1307 if (VBase->getType()->isDependentType())
1308 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001309 if (CXXBaseOrMemberInitializer *Value
1310 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001311 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001312 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001313 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001314 CXXRecordDecl *VBaseDecl =
Douglas Gregor802ab452009-12-02 22:36:29 +00001315 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001316 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001317 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001318 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001319 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1320 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1321 << 0 << VBase->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001322 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001323 << Context.getTagDeclType(VBaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001324 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001325 continue;
1326 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001327
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001328 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1329 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1330 Constructor->getLocation(), CtorArgs))
1331 continue;
1332
1333 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1334
Anders Carlsson8db68da2009-11-13 20:11:49 +00001335 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001336 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1337 // necessary.
1338 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001339 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001340 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001341 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001342 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001343 SourceLocation()),
1344 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001345 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001346 CtorArgs.takeAs<Expr>(),
1347 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001348 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001349 AllToInit.push_back(Member);
1350 }
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001353 for (CXXRecordDecl::base_class_iterator Base =
1354 ClassDecl->bases_begin(),
1355 E = ClassDecl->bases_end(); Base != E; ++Base) {
1356 // Virtuals are in the virtual base list and already constructed.
1357 if (Base->isVirtual())
1358 continue;
1359 // Skip dependent types.
1360 if (Base->getType()->isDependentType())
1361 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001362 if (CXXBaseOrMemberInitializer *Value
1363 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001364 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001365 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001366 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001367 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001368 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001369 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001370 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001371 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001372 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1373 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1374 << 0 << Base->getType();
Douglas Gregor9af2f522009-12-01 16:58:18 +00001375 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001376 << Context.getTagDeclType(BaseDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00001377 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001378 continue;
1379 }
1380
1381 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1382 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1383 Constructor->getLocation(), CtorArgs))
1384 continue;
1385
1386 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001387
Anders Carlsson8db68da2009-11-13 20:11:49 +00001388 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregor802ab452009-12-02 22:36:29 +00001389 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1390 // necessary.
1391 // FIXME: Is there any better source-location information we can give?
Anders Carlsson8db68da2009-11-13 20:11:49 +00001392 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001393 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001394 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001395 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001396 SourceLocation()),
1397 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001398 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001399 CtorArgs.takeAs<Expr>(),
1400 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001401 SourceLocation());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001402 AllToInit.push_back(Member);
1403 }
1404 }
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001407 // non-static data members.
1408 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1409 E = ClassDecl->field_end(); Field != E; ++Field) {
1410 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001411 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001412 Field->getType()->getAs<RecordType>()) {
1413 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001414 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001415 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001416 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1417 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1418 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1419 // set to the anonymous union data member used in the initializer
1420 // list.
1421 Value->setMember(*Field);
1422 Value->setAnonUnionMember(*FA);
1423 AllToInit.push_back(Value);
1424 break;
1425 }
1426 }
1427 }
1428 continue;
1429 }
1430 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1431 AllToInit.push_back(Value);
1432 continue;
1433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Eli Friedman49c16da2009-11-09 01:05:47 +00001435 if ((*Field)->getType()->isDependentType())
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001436 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001437
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001438 QualType FT = Context.getBaseElementType((*Field)->getType());
1439 if (const RecordType* RT = FT->getAs<RecordType>()) {
1440 CXXConstructorDecl *Ctor =
1441 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001442 if (!Ctor) {
Eli Friedman49c16da2009-11-09 01:05:47 +00001443 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1444 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1445 << 1 << (*Field)->getDeclName();
1446 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001447 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedman49c16da2009-11-09 01:05:47 +00001448 << Context.getTagDeclType(RT->getDecl());
Eli Friedman80c30da2009-11-09 19:20:36 +00001449 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001450 continue;
1451 }
Eli Friedmane73d3bc2009-11-16 23:07:59 +00001452
1453 if (FT.isConstQualified() && Ctor->isTrivial()) {
1454 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1455 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1456 << 1 << (*Field)->getDeclName();
1457 Diag((*Field)->getLocation(), diag::note_declared_at);
1458 HadError = true;
1459 }
1460
1461 // Don't create initializers for trivial constructors, since they don't
1462 // actually need to be run.
1463 if (Ctor->isTrivial())
1464 continue;
1465
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001466 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1467 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1468 Constructor->getLocation(), CtorArgs))
1469 continue;
1470
Anders Carlsson8db68da2009-11-13 20:11:49 +00001471 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1472 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1473 ExprTemporaries.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001474 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001475 new (Context) CXXBaseOrMemberInitializer(Context,
1476 *Field, SourceLocation(),
1477 Ctor,
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001478 SourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001479 CtorArgs.takeAs<Expr>(),
1480 CtorArgs.size(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001481 SourceLocation());
1482
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001483 AllToInit.push_back(Member);
Eli Friedman49c16da2009-11-09 01:05:47 +00001484 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001485 }
1486 else if (FT->isReferenceType()) {
1487 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001488 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1489 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001490 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001491 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001492 }
1493 else if (FT.isConstQualified()) {
1494 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001495 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1496 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001497 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001498 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001499 }
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001502 NumInitializers = AllToInit.size();
1503 if (NumInitializers > 0) {
1504 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1505 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1506 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1509 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1510 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1511 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001512
1513 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001514}
1515
Eli Friedman6347f422009-07-21 19:28:10 +00001516static void *GetKeyForTopLevelField(FieldDecl *Field) {
1517 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001518 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001519 if (RT->getDecl()->isAnonymousStructOrUnion())
1520 return static_cast<void *>(RT->getDecl());
1521 }
1522 return static_cast<void *>(Field);
1523}
1524
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001525static void *GetKeyForBase(QualType BaseType) {
1526 if (const RecordType *RT = BaseType->getAs<RecordType>())
1527 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001529 assert(0 && "Unexpected base type!");
1530 return 0;
1531}
1532
Mike Stump1eb44332009-09-09 15:08:12 +00001533static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001534 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001535 // For fields injected into the class via declaration of an anonymous union,
1536 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001537 if (Member->isMemberInitializer()) {
1538 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Eli Friedman49c16da2009-11-09 01:05:47 +00001540 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001541 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001542 // in AnonUnionMember field.
1543 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1544 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001545 if (Field->getDeclContext()->isRecord()) {
1546 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1547 if (RD->isAnonymousStructOrUnion())
1548 return static_cast<void *>(RD);
1549 }
1550 return static_cast<void *>(Field);
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001553 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001554}
1555
John McCall6aee6212009-11-04 23:13:52 +00001556/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001557void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001558 SourceLocation ColonLoc,
1559 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001560 if (!ConstructorDecl)
1561 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001562
1563 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
1565 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001566 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Anders Carlssona7b35212009-03-25 02:58:17 +00001568 if (!Constructor) {
1569 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1570 return;
1571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001573 if (!Constructor->isDependentContext()) {
1574 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1575 bool err = false;
1576 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001577 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001578 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1579 void *KeyToMember = GetKeyForMember(Member);
1580 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1581 if (!PrevMember) {
1582 PrevMember = Member;
1583 continue;
1584 }
1585 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001586 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001587 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001588 << Field->getNameAsString()
1589 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001590 else {
1591 Type *BaseClass = Member->getBaseClass();
1592 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001593 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001594 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001595 << QualType(BaseClass, 0)
1596 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001597 }
1598 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1599 << 0;
1600 err = true;
1601 }
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001603 if (err)
1604 return;
1605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Eli Friedman49c16da2009-11-09 01:05:47 +00001607 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001608 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedman49c16da2009-11-09 01:05:47 +00001609 NumMemInits, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001611 if (Constructor->isDependentContext())
1612 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
1614 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001615 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001616 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001617 Diagnostic::Ignored)
1618 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001620 // Also issue warning if order of ctor-initializer list does not match order
1621 // of 1) base class declarations and 2) order of non-static data members.
1622 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001624 CXXRecordDecl *ClassDecl
1625 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1626 // Push virtual bases before others.
1627 for (CXXRecordDecl::base_class_iterator VBase =
1628 ClassDecl->vbases_begin(),
1629 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001630 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001632 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1633 E = ClassDecl->bases_end(); Base != E; ++Base) {
1634 // Virtuals are alread in the virtual base list and are constructed
1635 // first.
1636 if (Base->isVirtual())
1637 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001638 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001641 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1642 E = ClassDecl->field_end(); Field != E; ++Field)
1643 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001645 int Last = AllBaseOrMembers.size();
1646 int curIndex = 0;
1647 CXXBaseOrMemberInitializer *PrevMember = 0;
1648 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001649 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001650 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1651 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001652
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001653 for (; curIndex < Last; curIndex++)
1654 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1655 break;
1656 if (curIndex == Last) {
1657 assert(PrevMember && "Member not in member list?!");
1658 // Initializer as specified in ctor-initializer list is out of order.
1659 // Issue a warning diagnostic.
1660 if (PrevMember->isBaseInitializer()) {
1661 // Diagnostics is for an initialized base class.
1662 Type *BaseClass = PrevMember->getBaseClass();
1663 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001664 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001665 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001666 } else {
1667 FieldDecl *Field = PrevMember->getMember();
1668 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001669 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001670 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001671 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001672 // Also the note!
1673 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001674 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001675 diag::note_fieldorbase_initialized_here) << 0
1676 << Field->getNameAsString();
1677 else {
1678 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001679 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001680 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001681 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001682 }
1683 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001684 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001685 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001686 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001687 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001688 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001689}
1690
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001691void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001692Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1693 // Ignore dependent destructors.
1694 if (Destructor->isDependentContext())
1695 return;
1696
1697 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Anders Carlsson9f853df2009-11-17 04:44:12 +00001699 // Non-static data members.
1700 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1701 E = ClassDecl->field_end(); I != E; ++I) {
1702 FieldDecl *Field = *I;
1703
1704 QualType FieldType = Context.getBaseElementType(Field->getType());
1705
1706 const RecordType* RT = FieldType->getAs<RecordType>();
1707 if (!RT)
1708 continue;
1709
1710 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1711 if (FieldClassDecl->hasTrivialDestructor())
1712 continue;
1713
1714 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1715 MarkDeclarationReferenced(Destructor->getLocation(),
1716 const_cast<CXXDestructorDecl*>(Dtor));
1717 }
1718
1719 // Bases.
1720 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1721 E = ClassDecl->bases_end(); Base != E; ++Base) {
1722 // Ignore virtual bases.
1723 if (Base->isVirtual())
1724 continue;
1725
1726 // Ignore trivial destructors.
1727 CXXRecordDecl *BaseClassDecl
1728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1729 if (BaseClassDecl->hasTrivialDestructor())
1730 continue;
1731
1732 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1733 MarkDeclarationReferenced(Destructor->getLocation(),
1734 const_cast<CXXDestructorDecl*>(Dtor));
1735 }
1736
1737 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001738 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1739 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001740 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001741 CXXRecordDecl *BaseClassDecl
1742 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1743 if (BaseClassDecl->hasTrivialDestructor())
1744 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001745
1746 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1747 MarkDeclarationReferenced(Destructor->getLocation(),
1748 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001749 }
1750}
1751
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001752void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001753 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001754 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001756 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
1758 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001759 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedman49c16da2009-11-09 01:05:47 +00001760 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001761}
1762
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001763namespace {
1764 /// PureVirtualMethodCollector - traverses a class and its superclasses
1765 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001766 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001767 ASTContext &Context;
1768
Sebastian Redldfe292d2009-03-22 21:28:55 +00001769 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001770 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001771
1772 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001773 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001775 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001777 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001778 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001779 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001781 MethodList List;
1782 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001784 // Copy the temporary list to methods, and make sure to ignore any
1785 // null entries.
1786 for (size_t i = 0, e = List.size(); i != e; ++i) {
1787 if (List[i])
1788 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001789 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001790 }
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001792 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001794 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1795 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001796 };
Mike Stump1eb44332009-09-09 15:08:12 +00001797
1798 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001799 MethodList& Methods) {
1800 // First, collect the pure virtual methods for the base classes.
1801 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1802 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001803 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001804 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001805 if (BaseDecl && BaseDecl->isAbstract())
1806 Collect(BaseDecl, Methods);
1807 }
1808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001810 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001811 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001813 MethodSetTy OverriddenMethods;
1814 size_t MethodsSize = Methods.size();
1815
Mike Stump1eb44332009-09-09 15:08:12 +00001816 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001817 i != e; ++i) {
1818 // Traverse the record, looking for methods.
1819 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001820 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001821 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001822 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlsson27823022009-10-18 19:34:08 +00001824 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001825 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1826 E = MD->end_overridden_methods(); I != E; ++I) {
1827 // Keep track of the overridden methods.
1828 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001829 }
1830 }
1831 }
Mike Stump1eb44332009-09-09 15:08:12 +00001832
1833 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001834 // overridden.
1835 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1836 if (OverriddenMethods.count(Methods[i]))
1837 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001840 }
1841}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001842
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001843
Mike Stump1eb44332009-09-09 15:08:12 +00001844bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001845 unsigned DiagID, AbstractDiagSelID SelID,
1846 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001847 if (SelID == -1)
1848 return RequireNonAbstractType(Loc, T,
1849 PDiag(DiagID), CurrentRD);
1850 else
1851 return RequireNonAbstractType(Loc, T,
1852 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001853}
1854
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001855bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1856 const PartialDiagnostic &PD,
1857 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001858 if (!getLangOptions().CPlusPlus)
1859 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Anders Carlsson11f21a02009-03-23 19:10:31 +00001861 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001862 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001863 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Ted Kremenek6217b802009-07-29 21:53:49 +00001865 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001866 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001867 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001868 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001870 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001871 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Ted Kremenek6217b802009-07-29 21:53:49 +00001874 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001875 if (!RT)
1876 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001878 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1879 if (!RD)
1880 return false;
1881
Anders Carlssone65a3c82009-03-24 17:23:42 +00001882 if (CurrentRD && CurrentRD != RD)
1883 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001885 if (!RD->isAbstract())
1886 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001888 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001890 // Check if we've already emitted the list of pure virtual functions for this
1891 // class.
1892 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1893 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001895 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001896
1897 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001898 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1899 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
1901 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001902 MD->getDeclName();
1903 }
1904
1905 if (!PureVirtualClassDiagSet)
1906 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1907 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001909 return true;
1910}
1911
Anders Carlsson8211eff2009-03-24 01:19:16 +00001912namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00001913 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001914 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1915 Sema &SemaRef;
1916 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Anders Carlssone65a3c82009-03-24 17:23:42 +00001918 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001919 bool Invalid = false;
1920
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001921 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1922 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001923 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001924
Anders Carlsson8211eff2009-03-24 01:19:16 +00001925 return Invalid;
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Anders Carlssone65a3c82009-03-24 17:23:42 +00001928 public:
1929 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1930 : SemaRef(SemaRef), AbstractClass(ac) {
1931 Visit(SemaRef.Context.getTranslationUnitDecl());
1932 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001933
Anders Carlssone65a3c82009-03-24 17:23:42 +00001934 bool VisitFunctionDecl(const FunctionDecl *FD) {
1935 if (FD->isThisDeclarationADefinition()) {
1936 // No need to do the check if we're in a definition, because it requires
1937 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001938 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001939 return VisitDeclContext(FD);
1940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Anders Carlssone65a3c82009-03-24 17:23:42 +00001942 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00001943 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001944 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001945 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1946 diag::err_abstract_type_in_decl,
1947 Sema::AbstractReturnType,
1948 AbstractClass);
1949
Mike Stump1eb44332009-09-09 15:08:12 +00001950 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001951 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001952 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001953 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001954 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001955 VD->getOriginalType(),
1956 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001957 Sema::AbstractParamType,
1958 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001959 }
1960
1961 return Invalid;
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Anders Carlssone65a3c82009-03-24 17:23:42 +00001964 bool VisitDecl(const Decl* D) {
1965 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1966 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Anders Carlssone65a3c82009-03-24 17:23:42 +00001968 return false;
1969 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001970 };
1971}
1972
Douglas Gregor1ab537b2009-12-03 18:33:45 +00001973/// \brief Perform semantic checks on a class definition that has been
1974/// completing, introducing implicitly-declared members, checking for
1975/// abstract types, etc.
1976void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1977 if (!Record || Record->isInvalidDecl())
1978 return;
1979
1980 if (!Record->isAbstract()) {
1981 // Collect all the pure virtual methods and see if this is an abstract
1982 // class after all.
1983 PureVirtualMethodCollector Collector(Context, Record);
1984 if (!Collector.empty())
1985 Record->setAbstract(true);
1986 }
1987
1988 if (Record->isAbstract())
1989 (void)AbstractClassUsageDiagnoser(*this, Record);
1990
1991 if (!Record->isDependentType() && !Record->isInvalidDecl())
1992 AddImplicitlyDeclaredMembersToClass(Record);
1993}
1994
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001995void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001996 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001997 SourceLocation LBrac,
1998 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001999 if (!TagDecl)
2000 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Douglas Gregor42af25f2009-05-11 19:58:34 +00002002 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002003
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002004 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002005 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002006 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002007
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002008 CheckCompletedCXXClass(
2009 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002010}
2011
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002012/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2013/// special functions, such as the default constructor, copy
2014/// constructor, or destructor, to the given C++ class (C++
2015/// [special]p1). This routine can only be executed just before the
2016/// definition of the class is complete.
2017void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002018 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002019 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002020
Sebastian Redl465226e2009-05-27 22:11:52 +00002021 // FIXME: Implicit declarations have exception specifications, which are
2022 // the union of the specifications of the implicitly called functions.
2023
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002024 if (!ClassDecl->hasUserDeclaredConstructor()) {
2025 // C++ [class.ctor]p5:
2026 // A default constructor for a class X is a constructor of class X
2027 // that can be called without an argument. If there is no
2028 // user-declared constructor for class X, a default constructor is
2029 // implicitly declared. An implicitly-declared default constructor
2030 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002031 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002032 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002033 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002034 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002035 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002036 Context.getFunctionType(Context.VoidTy,
2037 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002038 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002039 /*isExplicit=*/false,
2040 /*isInline=*/true,
2041 /*isImplicitlyDeclared=*/true);
2042 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002043 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002044 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002045 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002046 }
2047
2048 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2049 // C++ [class.copy]p4:
2050 // If the class definition does not explicitly declare a copy
2051 // constructor, one is declared implicitly.
2052
2053 // C++ [class.copy]p5:
2054 // The implicitly-declared copy constructor for a class X will
2055 // have the form
2056 //
2057 // X::X(const X&)
2058 //
2059 // if
2060 bool HasConstCopyConstructor = true;
2061
2062 // -- each direct or virtual base class B of X has a copy
2063 // constructor whose first parameter is of type const B& or
2064 // const volatile B&, and
2065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2066 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2067 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002068 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002069 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002070 = BaseClassDecl->hasConstCopyConstructor(Context);
2071 }
2072
2073 // -- for all the nonstatic data members of X that are of a
2074 // class type M (or array thereof), each such class type
2075 // has a copy constructor whose first parameter is of type
2076 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002077 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2078 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002079 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002080 QualType FieldType = (*Field)->getType();
2081 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2082 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002083 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002084 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002085 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002086 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002087 = FieldClassDecl->hasConstCopyConstructor(Context);
2088 }
2089 }
2090
Sebastian Redl64b45f72009-01-05 20:52:13 +00002091 // Otherwise, the implicitly declared copy constructor will have
2092 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002093 //
2094 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002095 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002096 if (HasConstCopyConstructor)
2097 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002098 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002099
Sebastian Redl64b45f72009-01-05 20:52:13 +00002100 // An implicitly-declared copy constructor is an inline public
2101 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002102 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002103 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002104 CXXConstructorDecl *CopyConstructor
2105 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002106 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002107 Context.getFunctionType(Context.VoidTy,
2108 &ArgType, 1,
2109 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002110 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002111 /*isExplicit=*/false,
2112 /*isInline=*/true,
2113 /*isImplicitlyDeclared=*/true);
2114 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002115 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002116 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002117
2118 // Add the parameter to the constructor.
2119 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2120 ClassDecl->getLocation(),
2121 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002122 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002123 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002124 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002125 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002126 }
2127
Sebastian Redl64b45f72009-01-05 20:52:13 +00002128 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2129 // Note: The following rules are largely analoguous to the copy
2130 // constructor rules. Note that virtual bases are not taken into account
2131 // for determining the argument type of the operator. Note also that
2132 // operators taking an object instead of a reference are allowed.
2133 //
2134 // C++ [class.copy]p10:
2135 // If the class definition does not explicitly declare a copy
2136 // assignment operator, one is declared implicitly.
2137 // The implicitly-defined copy assignment operator for a class X
2138 // will have the form
2139 //
2140 // X& X::operator=(const X&)
2141 //
2142 // if
2143 bool HasConstCopyAssignment = true;
2144
2145 // -- each direct base class B of X has a copy assignment operator
2146 // whose parameter is of type const B&, const volatile B& or B,
2147 // and
2148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2149 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002150 assert(!Base->getType()->isDependentType() &&
2151 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002152 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002153 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002154 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002155 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002156 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002157 }
2158
2159 // -- for all the nonstatic data members of X that are of a class
2160 // type M (or array thereof), each such class type has a copy
2161 // assignment operator whose parameter is of type const M&,
2162 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002163 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2164 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002165 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002166 QualType FieldType = (*Field)->getType();
2167 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2168 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002169 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002170 const CXXRecordDecl *FieldClassDecl
2171 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002172 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002173 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002174 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002175 }
2176 }
2177
2178 // Otherwise, the implicitly declared copy assignment operator will
2179 // have the form
2180 //
2181 // X& X::operator=(X&)
2182 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002183 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002184 if (HasConstCopyAssignment)
2185 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002186 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002187
2188 // An implicitly-declared copy assignment operator is an inline public
2189 // member of its class.
2190 DeclarationName Name =
2191 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2192 CXXMethodDecl *CopyAssignment =
2193 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2194 Context.getFunctionType(RetType, &ArgType, 1,
2195 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002196 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002197 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002198 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002199 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002200 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002201
2202 // Add the parameter to the operator.
2203 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2204 ClassDecl->getLocation(),
2205 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002206 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002207 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002208 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002209
2210 // Don't call addedAssignmentOperator. There is no way to distinguish an
2211 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002212 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002213 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002214 }
2215
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002216 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002217 // C++ [class.dtor]p2:
2218 // If a class has no user-declared destructor, a destructor is
2219 // declared implicitly. An implicitly-declared destructor is an
2220 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002221 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002222 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002223 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002224 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002225 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002226 Context.getFunctionType(Context.VoidTy,
2227 0, 0, false, 0),
2228 /*isInline=*/true,
2229 /*isImplicitlyDeclared=*/true);
2230 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002231 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002232 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002233 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002234
2235 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002236 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002237}
2238
Douglas Gregor6569d682009-05-27 23:11:45 +00002239void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002240 Decl *D = TemplateD.getAs<Decl>();
2241 if (!D)
2242 return;
2243
2244 TemplateParameterList *Params = 0;
2245 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2246 Params = Template->getTemplateParameters();
2247 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2248 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2249 Params = PartialSpec->getTemplateParameters();
2250 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002251 return;
2252
Douglas Gregor6569d682009-05-27 23:11:45 +00002253 for (TemplateParameterList::iterator Param = Params->begin(),
2254 ParamEnd = Params->end();
2255 Param != ParamEnd; ++Param) {
2256 NamedDecl *Named = cast<NamedDecl>(*Param);
2257 if (Named->getDeclName()) {
2258 S->AddDecl(DeclPtrTy::make(Named));
2259 IdResolver.AddDecl(Named);
2260 }
2261 }
2262}
2263
Douglas Gregor72b505b2008-12-16 21:30:33 +00002264/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2265/// parsing a top-level (non-nested) C++ class, and we are now
2266/// parsing those parts of the given Method declaration that could
2267/// not be parsed earlier (C++ [class.mem]p2), such as default
2268/// arguments. This action should enter the scope of the given
2269/// Method declaration as if we had just parsed the qualified method
2270/// name. However, it should not bring the parameters into scope;
2271/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002272void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002273 if (!MethodD)
2274 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002276 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor72b505b2008-12-16 21:30:33 +00002278 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002279 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00002280 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002281 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2282 SS.setScopeRep(
2283 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002284 ActOnCXXEnterDeclaratorScope(S, SS);
2285}
2286
2287/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2288/// C++ method declaration. We're (re-)introducing the given
2289/// function parameter into scope for use in parsing later parts of
2290/// the method declaration. For example, we could see an
2291/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002292void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002293 if (!ParamD)
2294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Chris Lattnerb28317a2009-03-28 19:18:32 +00002296 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002297
2298 // If this parameter has an unparsed default argument, clear it out
2299 // to make way for the parsed default argument.
2300 if (Param->hasUnparsedDefaultArg())
2301 Param->setDefaultArg(0);
2302
Chris Lattnerb28317a2009-03-28 19:18:32 +00002303 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002304 if (Param->getDeclName())
2305 IdResolver.AddDecl(Param);
2306}
2307
2308/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2309/// processing the delayed method declaration for Method. The method
2310/// declaration is now considered finished. There may be a separate
2311/// ActOnStartOfFunctionDef action later (not necessarily
2312/// immediately!) for this method, if it was also defined inside the
2313/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002314void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002315 if (!MethodD)
2316 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002318 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Chris Lattnerb28317a2009-03-28 19:18:32 +00002320 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002321 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00002322 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00002323 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2324 SS.setScopeRep(
2325 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002326 ActOnCXXExitDeclaratorScope(S, SS);
2327
2328 // Now that we have our default arguments, check the constructor
2329 // again. It could produce additional diagnostics or affect whether
2330 // the class has implicitly-declared destructors, among other
2331 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002332 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2333 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002334
2335 // Check the default arguments, which we may have added.
2336 if (!Method->isInvalidDecl())
2337 CheckCXXDefaultArguments(Method);
2338}
2339
Douglas Gregor42a552f2008-11-05 20:51:48 +00002340/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002341/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002342/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002343/// emit diagnostics and set the invalid bit to true. In any case, the type
2344/// will be updated to reflect a well-formed type for the constructor and
2345/// returned.
2346QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2347 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002348 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002349
2350 // C++ [class.ctor]p3:
2351 // A constructor shall not be virtual (10.3) or static (9.4). A
2352 // constructor can be invoked for a const, volatile or const
2353 // volatile object. A constructor shall not be declared const,
2354 // volatile, or const volatile (9.3.2).
2355 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002356 if (!D.isInvalidType())
2357 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2358 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2359 << SourceRange(D.getIdentifierLoc());
2360 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002361 }
2362 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002363 if (!D.isInvalidType())
2364 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2365 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2366 << SourceRange(D.getIdentifierLoc());
2367 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002368 SC = FunctionDecl::None;
2369 }
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Chris Lattner65401802009-04-25 08:28:21 +00002371 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2372 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002373 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002374 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2375 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002376 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002377 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2378 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002379 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002380 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2381 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002382 }
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Douglas Gregor42a552f2008-11-05 20:51:48 +00002384 // Rebuild the function type "R" without any type qualifiers (in
2385 // case any of the errors above fired) and with "void" as the
2386 // return type, since constructors don't have return types. We
2387 // *always* have to do this, because GetTypeForDeclarator will
2388 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002389 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002390 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2391 Proto->getNumArgs(),
2392 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002393}
2394
Douglas Gregor72b505b2008-12-16 21:30:33 +00002395/// CheckConstructor - Checks a fully-formed constructor for
2396/// well-formedness, issuing any diagnostics required. Returns true if
2397/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002398void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002399 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002400 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2401 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002402 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002403
2404 // C++ [class.copy]p3:
2405 // A declaration of a constructor for a class X is ill-formed if
2406 // its first parameter is of type (optionally cv-qualified) X and
2407 // either there are no other parameters or else all other
2408 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002409 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002410 ((Constructor->getNumParams() == 1) ||
2411 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002412 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2413 Constructor->getTemplateSpecializationKind()
2414 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002415 QualType ParamType = Constructor->getParamDecl(0)->getType();
2416 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2417 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002418 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2419 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002420 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002421
2422 // FIXME: Rather that making the constructor invalid, we should endeavor
2423 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002424 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002425 }
2426 }
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregor72b505b2008-12-16 21:30:33 +00002428 // Notify the class that we've added a constructor.
2429 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002430}
2431
Anders Carlsson37909802009-11-30 21:24:50 +00002432/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2433/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002434bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002435 CXXRecordDecl *RD = Destructor->getParent();
2436
2437 if (Destructor->isVirtual()) {
2438 SourceLocation Loc;
2439
2440 if (!Destructor->isImplicit())
2441 Loc = Destructor->getLocation();
2442 else
2443 Loc = RD->getLocation();
2444
2445 // If we have a virtual destructor, look up the deallocation function
2446 FunctionDecl *OperatorDelete = 0;
2447 DeclarationName Name =
2448 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002449 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002450 return true;
2451
2452 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002453 }
Anders Carlsson37909802009-11-30 21:24:50 +00002454
2455 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002459FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2460 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2461 FTI.ArgInfo[0].Param &&
2462 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2463}
2464
Douglas Gregor42a552f2008-11-05 20:51:48 +00002465/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2466/// the well-formednes of the destructor declarator @p D with type @p
2467/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002468/// emit diagnostics and set the declarator to invalid. Even if this happens,
2469/// will be updated to reflect a well-formed type for the destructor and
2470/// returned.
2471QualType Sema::CheckDestructorDeclarator(Declarator &D,
2472 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002473 // C++ [class.dtor]p1:
2474 // [...] A typedef-name that names a class is a class-name
2475 // (7.1.3); however, a typedef-name that names a class shall not
2476 // be used as the identifier in the declarator for a destructor
2477 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002478 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002479 if (isa<TypedefType>(DeclaratorType)) {
2480 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002481 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002482 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002483 }
2484
2485 // C++ [class.dtor]p2:
2486 // A destructor is used to destroy objects of its class type. A
2487 // destructor takes no parameters, and no return type can be
2488 // specified for it (not even void). The address of a destructor
2489 // shall not be taken. A destructor shall not be static. A
2490 // destructor can be invoked for a const, volatile or const
2491 // volatile object. A destructor shall not be declared const,
2492 // volatile or const volatile (9.3.2).
2493 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002494 if (!D.isInvalidType())
2495 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2496 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2497 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002498 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002499 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002500 }
Chris Lattner65401802009-04-25 08:28:21 +00002501 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002502 // Destructors don't have return types, but the parser will
2503 // happily parse something like:
2504 //
2505 // class X {
2506 // float ~X();
2507 // };
2508 //
2509 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002510 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2511 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2512 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002513 }
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Chris Lattner65401802009-04-25 08:28:21 +00002515 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2516 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002517 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002518 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2519 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002520 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002521 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2522 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002523 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002524 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2525 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002526 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002527 }
2528
2529 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002530 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002531 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2532
2533 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002534 FTI.freeArgs();
2535 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002536 }
2537
Mike Stump1eb44332009-09-09 15:08:12 +00002538 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002539 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002540 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002541 D.setInvalidType();
2542 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002543
2544 // Rebuild the function type "R" without any type qualifiers or
2545 // parameters (in case any of the errors above fired) and with
2546 // "void" as the return type, since destructors don't have return
2547 // types. We *always* have to do this, because GetTypeForDeclarator
2548 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002549 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002550}
2551
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002552/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2553/// well-formednes of the conversion function declarator @p D with
2554/// type @p R. If there are any errors in the declarator, this routine
2555/// will emit diagnostics and return true. Otherwise, it will return
2556/// false. Either way, the type @p R will be updated to reflect a
2557/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002558void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002559 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002560 // C++ [class.conv.fct]p1:
2561 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002562 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002563 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002564 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002565 if (!D.isInvalidType())
2566 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2567 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2568 << SourceRange(D.getIdentifierLoc());
2569 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002570 SC = FunctionDecl::None;
2571 }
Chris Lattner6e475012009-04-25 08:35:12 +00002572 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002573 // Conversion functions don't have return types, but the parser will
2574 // happily parse something like:
2575 //
2576 // class X {
2577 // float operator bool();
2578 // };
2579 //
2580 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002581 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2582 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2583 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002584 }
2585
2586 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002587 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002588 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2589
2590 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002591 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002592 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002593 }
2594
Mike Stump1eb44332009-09-09 15:08:12 +00002595 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002596 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002597 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002598 D.setInvalidType();
2599 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002600
2601 // C++ [class.conv.fct]p4:
2602 // The conversion-type-id shall not represent a function type nor
2603 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002604 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002605 if (ConvType->isArrayType()) {
2606 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2607 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002608 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002609 } else if (ConvType->isFunctionType()) {
2610 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2611 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002612 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002613 }
2614
2615 // Rebuild the function type "R" without any parameters (in case any
2616 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002617 // return type.
2618 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002619 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002620
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002621 // C++0x explicit conversion operators.
2622 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002623 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002624 diag::warn_explicit_conversion_functions)
2625 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002626}
2627
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002628/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2629/// the declaration of the given C++ conversion function. This routine
2630/// is responsible for recording the conversion function in the C++
2631/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002632Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002633 assert(Conversion && "Expected to receive a conversion function declaration");
2634
Douglas Gregor9d350972008-12-12 08:25:50 +00002635 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002636
2637 // Make sure we aren't redeclaring the conversion function.
2638 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002639
2640 // C++ [class.conv.fct]p1:
2641 // [...] A conversion function is never used to convert a
2642 // (possibly cv-qualified) object to the (possibly cv-qualified)
2643 // same object type (or a reference to it), to a (possibly
2644 // cv-qualified) base class of that type (or a reference to it),
2645 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002646 // FIXME: Suppress this warning if the conversion function ends up being a
2647 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002648 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002649 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002650 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002651 ConvType = ConvTypeRef->getPointeeType();
2652 if (ConvType->isRecordType()) {
2653 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2654 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002655 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002656 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002657 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002658 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002659 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002660 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002661 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002662 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002663 }
2664
Douglas Gregor70316a02008-12-26 15:00:45 +00002665 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002666 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002667 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002668 = Conversion->getDescribedFunctionTemplate())
2669 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCallba135432009-11-21 08:51:07 +00002670 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2671 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002672 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002673 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002674 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002675 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002676 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002677 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002678
Chris Lattnerb28317a2009-03-28 19:18:32 +00002679 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002680}
2681
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002682//===----------------------------------------------------------------------===//
2683// Namespace Handling
2684//===----------------------------------------------------------------------===//
2685
2686/// ActOnStartNamespaceDef - This is called at the start of a namespace
2687/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002688Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2689 SourceLocation IdentLoc,
2690 IdentifierInfo *II,
2691 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002692 NamespaceDecl *Namespc =
2693 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2694 Namespc->setLBracLoc(LBrace);
2695
2696 Scope *DeclRegionScope = NamespcScope->getParent();
2697
2698 if (II) {
2699 // C++ [namespace.def]p2:
2700 // The identifier in an original-namespace-definition shall not have been
2701 // previously defined in the declarative region in which the
2702 // original-namespace-definition appears. The identifier in an
2703 // original-namespace-definition is the name of the namespace. Subsequently
2704 // in that declarative region, it is treated as an original-namespace-name.
2705
John McCallf36e02d2009-10-09 21:13:30 +00002706 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002707 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002708 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002709
Douglas Gregor44b43212008-12-11 16:49:14 +00002710 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2711 // This is an extended namespace definition.
2712 // Attach this namespace decl to the chain of extended namespace
2713 // definitions.
2714 OrigNS->setNextNamespace(Namespc);
2715 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002716
Mike Stump1eb44332009-09-09 15:08:12 +00002717 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002718 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002719 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002720 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002721 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002722 } else if (PrevDecl) {
2723 // This is an invalid name redefinition.
2724 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2725 << Namespc->getDeclName();
2726 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2727 Namespc->setInvalidDecl();
2728 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002729 } else if (II->isStr("std") &&
2730 CurContext->getLookupContext()->isTranslationUnit()) {
2731 // This is the first "real" definition of the namespace "std", so update
2732 // our cache of the "std" namespace to point at this definition.
2733 if (StdNamespace) {
2734 // We had already defined a dummy namespace "std". Link this new
2735 // namespace definition to the dummy namespace "std".
2736 StdNamespace->setNextNamespace(Namespc);
2737 StdNamespace->setLocation(IdentLoc);
2738 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2739 }
2740
2741 // Make our StdNamespace cache point at the first real definition of the
2742 // "std" namespace.
2743 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002744 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002745
2746 PushOnScopeChains(Namespc, DeclRegionScope);
2747 } else {
John McCall9aeed322009-10-01 00:25:31 +00002748 // Anonymous namespaces.
2749
2750 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2751 // behaves as if it were replaced by
2752 // namespace unique { /* empty body */ }
2753 // using namespace unique;
2754 // namespace unique { namespace-body }
2755 // where all occurrences of 'unique' in a translation unit are
2756 // replaced by the same identifier and this identifier differs
2757 // from all other identifiers in the entire program.
2758
2759 // We just create the namespace with an empty name and then add an
2760 // implicit using declaration, just like the standard suggests.
2761 //
2762 // CodeGen enforces the "universally unique" aspect by giving all
2763 // declarations semantically contained within an anonymous
2764 // namespace internal linkage.
2765
2766 assert(Namespc->isAnonymousNamespace());
2767 CurContext->addDecl(Namespc);
2768
2769 UsingDirectiveDecl* UD
2770 = UsingDirectiveDecl::Create(Context, CurContext,
2771 /* 'using' */ LBrace,
2772 /* 'namespace' */ SourceLocation(),
2773 /* qualifier */ SourceRange(),
2774 /* NNS */ NULL,
2775 /* identifier */ SourceLocation(),
2776 Namespc,
2777 /* Ancestor */ CurContext);
2778 UD->setImplicit();
2779 CurContext->addDecl(UD);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002780 }
2781
2782 // Although we could have an invalid decl (i.e. the namespace name is a
2783 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002784 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2785 // for the namespace has the declarations that showed up in that particular
2786 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002787 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002788 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002789}
2790
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002791/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2792/// is a namespace alias, returns the namespace it points to.
2793static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2794 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2795 return AD->getNamespace();
2796 return dyn_cast_or_null<NamespaceDecl>(D);
2797}
2798
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002799/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2800/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002801void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2802 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002803 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2804 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2805 Namespc->setRBracLoc(RBrace);
2806 PopDeclContext();
2807}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002808
Chris Lattnerb28317a2009-03-28 19:18:32 +00002809Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2810 SourceLocation UsingLoc,
2811 SourceLocation NamespcLoc,
2812 const CXXScopeSpec &SS,
2813 SourceLocation IdentLoc,
2814 IdentifierInfo *NamespcName,
2815 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002816 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2817 assert(NamespcName && "Invalid NamespcName.");
2818 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002819 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002820
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002821 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002822
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002823 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002824 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2825 LookupParsedName(R, S, &SS);
2826 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002827 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002828
John McCallf36e02d2009-10-09 21:13:30 +00002829 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002830 NamedDecl *Named = R.getFoundDecl();
2831 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2832 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002833 // C++ [namespace.udir]p1:
2834 // A using-directive specifies that the names in the nominated
2835 // namespace can be used in the scope in which the
2836 // using-directive appears after the using-directive. During
2837 // unqualified name lookup (3.4.1), the names appear as if they
2838 // were declared in the nearest enclosing namespace which
2839 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002840 // namespace. [Note: in this context, "contains" means "contains
2841 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002842
2843 // Find enclosing context containing both using-directive and
2844 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002845 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002846 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2847 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2848 CommonAncestor = CommonAncestor->getParent();
2849
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002850 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002851 SS.getRange(),
2852 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002853 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002854 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002855 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002856 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002857 }
2858
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002859 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002860 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002861 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002862}
2863
2864void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2865 // If scope has associated entity, then using directive is at namespace
2866 // or translation unit scope. We add UsingDirectiveDecls, into
2867 // it's lookup structure.
2868 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002869 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002870 else
2871 // Otherwise it is block-sope. using-directives will affect lookup
2872 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002873 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002874}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002875
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002876
2877Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002878 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00002879 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002880 SourceLocation UsingLoc,
2881 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002882 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002883 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00002884 bool IsTypeName,
2885 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002886 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002887
Douglas Gregor12c118a2009-11-04 16:30:06 +00002888 switch (Name.getKind()) {
2889 case UnqualifiedId::IK_Identifier:
2890 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00002891 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00002892 case UnqualifiedId::IK_ConversionFunctionId:
2893 break;
2894
2895 case UnqualifiedId::IK_ConstructorName:
John McCall604e7f12009-12-08 07:46:18 +00002896 // C++0x inherited constructors.
2897 if (getLangOptions().CPlusPlus0x) break;
2898
Douglas Gregor12c118a2009-11-04 16:30:06 +00002899 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2900 << SS.getRange();
2901 return DeclPtrTy();
2902
2903 case UnqualifiedId::IK_DestructorName:
2904 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2905 << SS.getRange();
2906 return DeclPtrTy();
2907
2908 case UnqualifiedId::IK_TemplateId:
2909 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2910 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2911 return DeclPtrTy();
2912 }
2913
2914 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00002915 if (!TargetName)
2916 return DeclPtrTy();
2917
John McCall60fa3cf2009-12-11 02:10:03 +00002918 // Warn about using declarations.
2919 // TODO: store that the declaration was written without 'using' and
2920 // talk about access decls instead of using decls in the
2921 // diagnostics.
2922 if (!HasUsingKeyword) {
2923 UsingLoc = Name.getSourceRange().getBegin();
2924
2925 Diag(UsingLoc, diag::warn_access_decl_deprecated)
2926 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
2927 "using ");
2928 }
2929
John McCall9488ea12009-11-17 05:59:44 +00002930 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00002931 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00002932 TargetName, AttrList,
2933 /* IsInstantiation */ false,
2934 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00002935 if (UD)
2936 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Anders Carlssonc72160b2009-08-28 05:40:36 +00002938 return DeclPtrTy::make(UD);
2939}
2940
John McCall9f54ad42009-12-10 09:41:52 +00002941/// Determines whether to create a using shadow decl for a particular
2942/// decl, given the set of decls existing prior to this using lookup.
2943bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
2944 const LookupResult &Previous) {
2945 // Diagnose finding a decl which is not from a base class of the
2946 // current class. We do this now because there are cases where this
2947 // function will silently decide not to build a shadow decl, which
2948 // will pre-empt further diagnostics.
2949 //
2950 // We don't need to do this in C++0x because we do the check once on
2951 // the qualifier.
2952 //
2953 // FIXME: diagnose the following if we care enough:
2954 // struct A { int foo; };
2955 // struct B : A { using A::foo; };
2956 // template <class T> struct C : A {};
2957 // template <class T> struct D : C<T> { using B::foo; } // <---
2958 // This is invalid (during instantiation) in C++03 because B::foo
2959 // resolves to the using decl in B, which is not a base class of D<T>.
2960 // We can't diagnose it immediately because C<T> is an unknown
2961 // specialization. The UsingShadowDecl in D<T> then points directly
2962 // to A::foo, which will look well-formed when we instantiate.
2963 // The right solution is to not collapse the shadow-decl chain.
2964 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
2965 DeclContext *OrigDC = Orig->getDeclContext();
2966
2967 // Handle enums and anonymous structs.
2968 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
2969 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
2970 while (OrigRec->isAnonymousStructOrUnion())
2971 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
2972
2973 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
2974 if (OrigDC == CurContext) {
2975 Diag(Using->getLocation(),
2976 diag::err_using_decl_nested_name_specifier_is_current_class)
2977 << Using->getNestedNameRange();
2978 Diag(Orig->getLocation(), diag::note_using_decl_target);
2979 return true;
2980 }
2981
2982 Diag(Using->getNestedNameRange().getBegin(),
2983 diag::err_using_decl_nested_name_specifier_is_not_base_class)
2984 << Using->getTargetNestedNameDecl()
2985 << cast<CXXRecordDecl>(CurContext)
2986 << Using->getNestedNameRange();
2987 Diag(Orig->getLocation(), diag::note_using_decl_target);
2988 return true;
2989 }
2990 }
2991
2992 if (Previous.empty()) return false;
2993
2994 NamedDecl *Target = Orig;
2995 if (isa<UsingShadowDecl>(Target))
2996 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
2997
John McCalld7533ec2009-12-11 02:33:26 +00002998 // If the target happens to be one of the previous declarations, we
2999 // don't have a conflict.
3000 //
3001 // FIXME: but we might be increasing its access, in which case we
3002 // should redeclare it.
3003 NamedDecl *NonTag = 0, *Tag = 0;
3004 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3005 I != E; ++I) {
3006 NamedDecl *D = (*I)->getUnderlyingDecl();
3007 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3008 return false;
3009
3010 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3011 }
3012
John McCall9f54ad42009-12-10 09:41:52 +00003013 if (Target->isFunctionOrFunctionTemplate()) {
3014 FunctionDecl *FD;
3015 if (isa<FunctionTemplateDecl>(Target))
3016 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3017 else
3018 FD = cast<FunctionDecl>(Target);
3019
3020 NamedDecl *OldDecl = 0;
3021 switch (CheckOverload(FD, Previous, OldDecl)) {
3022 case Ovl_Overload:
3023 return false;
3024
3025 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003026 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003027 break;
3028
3029 // We found a decl with the exact signature.
3030 case Ovl_Match:
3031 if (isa<UsingShadowDecl>(OldDecl)) {
3032 // Silently ignore the possible conflict.
3033 return false;
3034 }
3035
3036 // If we're in a record, we want to hide the target, so we
3037 // return true (without a diagnostic) to tell the caller not to
3038 // build a shadow decl.
3039 if (CurContext->isRecord())
3040 return true;
3041
3042 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003043 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003044 break;
3045 }
3046
3047 Diag(Target->getLocation(), diag::note_using_decl_target);
3048 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3049 return true;
3050 }
3051
3052 // Target is not a function.
3053
John McCall9f54ad42009-12-10 09:41:52 +00003054 if (isa<TagDecl>(Target)) {
3055 // No conflict between a tag and a non-tag.
3056 if (!Tag) return false;
3057
John McCall41ce66f2009-12-10 19:51:03 +00003058 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003059 Diag(Target->getLocation(), diag::note_using_decl_target);
3060 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3061 return true;
3062 }
3063
3064 // No conflict between a tag and a non-tag.
3065 if (!NonTag) return false;
3066
John McCall41ce66f2009-12-10 19:51:03 +00003067 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003068 Diag(Target->getLocation(), diag::note_using_decl_target);
3069 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3070 return true;
3071}
3072
John McCall9488ea12009-11-17 05:59:44 +00003073/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003074UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003075 UsingDecl *UD,
3076 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003077
3078 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003079 NamedDecl *Target = Orig;
3080 if (isa<UsingShadowDecl>(Target)) {
3081 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3082 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003083 }
3084
3085 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003086 = UsingShadowDecl::Create(Context, CurContext,
3087 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003088 UD->addShadowDecl(Shadow);
3089
3090 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003091 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003092 else
John McCall604e7f12009-12-08 07:46:18 +00003093 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003094 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003095
John McCall604e7f12009-12-08 07:46:18 +00003096 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3097 Shadow->setInvalidDecl();
3098
John McCall9f54ad42009-12-10 09:41:52 +00003099 return Shadow;
3100}
John McCall604e7f12009-12-08 07:46:18 +00003101
John McCall9f54ad42009-12-10 09:41:52 +00003102/// Hides a using shadow declaration. This is required by the current
3103/// using-decl implementation when a resolvable using declaration in a
3104/// class is followed by a declaration which would hide or override
3105/// one or more of the using decl's targets; for example:
3106///
3107/// struct Base { void foo(int); };
3108/// struct Derived : Base {
3109/// using Base::foo;
3110/// void foo(int);
3111/// };
3112///
3113/// The governing language is C++03 [namespace.udecl]p12:
3114///
3115/// When a using-declaration brings names from a base class into a
3116/// derived class scope, member functions in the derived class
3117/// override and/or hide member functions with the same name and
3118/// parameter types in a base class (rather than conflicting).
3119///
3120/// There are two ways to implement this:
3121/// (1) optimistically create shadow decls when they're not hidden
3122/// by existing declarations, or
3123/// (2) don't create any shadow decls (or at least don't make them
3124/// visible) until we've fully parsed/instantiated the class.
3125/// The problem with (1) is that we might have to retroactively remove
3126/// a shadow decl, which requires several O(n) operations because the
3127/// decl structures are (very reasonably) not designed for removal.
3128/// (2) avoids this but is very fiddly and phase-dependent.
3129void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3130 // Remove it from the DeclContext...
3131 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003132
John McCall9f54ad42009-12-10 09:41:52 +00003133 // ...and the scope, if applicable...
3134 if (S) {
3135 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3136 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003137 }
3138
John McCall9f54ad42009-12-10 09:41:52 +00003139 // ...and the using decl.
3140 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3141
3142 // TODO: complain somehow if Shadow was used. It shouldn't
3143 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003144}
3145
John McCall7ba107a2009-11-18 02:36:19 +00003146/// Builds a using declaration.
3147///
3148/// \param IsInstantiation - Whether this call arises from an
3149/// instantiation of an unresolved using declaration. We treat
3150/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003151NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3152 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003153 const CXXScopeSpec &SS,
3154 SourceLocation IdentLoc,
3155 DeclarationName Name,
3156 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003157 bool IsInstantiation,
3158 bool IsTypeName,
3159 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003160 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3161 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003162
Anders Carlsson550b14b2009-08-28 05:49:21 +00003163 // FIXME: We ignore attributes for now.
3164 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003166 if (SS.isEmpty()) {
3167 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003168 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003169 }
Mike Stump1eb44332009-09-09 15:08:12 +00003170
John McCall9f54ad42009-12-10 09:41:52 +00003171 // Do the redeclaration lookup in the current scope.
3172 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3173 ForRedeclaration);
3174 Previous.setHideTags(false);
3175 if (S) {
3176 LookupName(Previous, S);
3177
3178 // It is really dumb that we have to do this.
3179 LookupResult::Filter F = Previous.makeFilter();
3180 while (F.hasNext()) {
3181 NamedDecl *D = F.next();
3182 if (!isDeclInScope(D, CurContext, S))
3183 F.erase();
3184 }
3185 F.done();
3186 } else {
3187 assert(IsInstantiation && "no scope in non-instantiation");
3188 assert(CurContext->isRecord() && "scope not record in instantiation");
3189 LookupQualifiedName(Previous, CurContext);
3190 }
3191
Mike Stump1eb44332009-09-09 15:08:12 +00003192 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003193 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3194
John McCall9f54ad42009-12-10 09:41:52 +00003195 // Check for invalid redeclarations.
3196 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3197 return 0;
3198
3199 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003200 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3201 return 0;
3202
John McCallaf8e6ed2009-11-12 03:15:40 +00003203 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003204 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003205 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003206 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003207 // FIXME: not all declaration name kinds are legal here
3208 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3209 UsingLoc, TypenameLoc,
3210 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003211 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003212 } else {
3213 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3214 UsingLoc, SS.getRange(), NNS,
3215 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003216 }
John McCalled976492009-12-04 22:46:56 +00003217 } else {
3218 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3219 SS.getRange(), UsingLoc, NNS, Name,
3220 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003221 }
John McCalled976492009-12-04 22:46:56 +00003222 D->setAccess(AS);
3223 CurContext->addDecl(D);
3224
3225 if (!LookupContext) return D;
3226 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003227
John McCall604e7f12009-12-08 07:46:18 +00003228 if (RequireCompleteDeclContext(SS)) {
3229 UD->setInvalidDecl();
3230 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003231 }
3232
John McCall604e7f12009-12-08 07:46:18 +00003233 // Look up the target name.
3234
John McCalla24dc2e2009-11-17 02:14:36 +00003235 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003236
John McCall604e7f12009-12-08 07:46:18 +00003237 // Unlike most lookups, we don't always want to hide tag
3238 // declarations: tag names are visible through the using declaration
3239 // even if hidden by ordinary names, *except* in a dependent context
3240 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003241 if (!IsInstantiation)
3242 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003243
John McCalla24dc2e2009-11-17 02:14:36 +00003244 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003245
John McCallf36e02d2009-10-09 21:13:30 +00003246 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003247 Diag(IdentLoc, diag::err_no_member)
3248 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003249 UD->setInvalidDecl();
3250 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003251 }
3252
John McCalled976492009-12-04 22:46:56 +00003253 if (R.isAmbiguous()) {
3254 UD->setInvalidDecl();
3255 return UD;
3256 }
Mike Stump1eb44332009-09-09 15:08:12 +00003257
John McCall7ba107a2009-11-18 02:36:19 +00003258 if (IsTypeName) {
3259 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003260 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003261 Diag(IdentLoc, diag::err_using_typename_non_type);
3262 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3263 Diag((*I)->getUnderlyingDecl()->getLocation(),
3264 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003265 UD->setInvalidDecl();
3266 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003267 }
3268 } else {
3269 // If we asked for a non-typename and we got a type, error out,
3270 // but only if this is an instantiation of an unresolved using
3271 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003272 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003273 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3274 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003275 UD->setInvalidDecl();
3276 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003277 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003278 }
3279
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003280 // C++0x N2914 [namespace.udecl]p6:
3281 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003282 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003283 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3284 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003285 UD->setInvalidDecl();
3286 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003287 }
Mike Stump1eb44332009-09-09 15:08:12 +00003288
John McCall9f54ad42009-12-10 09:41:52 +00003289 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3290 if (!CheckUsingShadowDecl(UD, *I, Previous))
3291 BuildUsingShadowDecl(S, UD, *I);
3292 }
John McCall9488ea12009-11-17 05:59:44 +00003293
3294 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003295}
3296
John McCall9f54ad42009-12-10 09:41:52 +00003297/// Checks that the given using declaration is not an invalid
3298/// redeclaration. Note that this is checking only for the using decl
3299/// itself, not for any ill-formedness among the UsingShadowDecls.
3300bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3301 bool isTypeName,
3302 const CXXScopeSpec &SS,
3303 SourceLocation NameLoc,
3304 const LookupResult &Prev) {
3305 // C++03 [namespace.udecl]p8:
3306 // C++0x [namespace.udecl]p10:
3307 // A using-declaration is a declaration and can therefore be used
3308 // repeatedly where (and only where) multiple declarations are
3309 // allowed.
3310 // That's only in file contexts.
3311 if (CurContext->getLookupContext()->isFileContext())
3312 return false;
3313
3314 NestedNameSpecifier *Qual
3315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3316
3317 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3318 NamedDecl *D = *I;
3319
3320 bool DTypename;
3321 NestedNameSpecifier *DQual;
3322 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3323 DTypename = UD->isTypeName();
3324 DQual = UD->getTargetNestedNameDecl();
3325 } else if (UnresolvedUsingValueDecl *UD
3326 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3327 DTypename = false;
3328 DQual = UD->getTargetNestedNameSpecifier();
3329 } else if (UnresolvedUsingTypenameDecl *UD
3330 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3331 DTypename = true;
3332 DQual = UD->getTargetNestedNameSpecifier();
3333 } else continue;
3334
3335 // using decls differ if one says 'typename' and the other doesn't.
3336 // FIXME: non-dependent using decls?
3337 if (isTypeName != DTypename) continue;
3338
3339 // using decls differ if they name different scopes (but note that
3340 // template instantiation can cause this check to trigger when it
3341 // didn't before instantiation).
3342 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3343 Context.getCanonicalNestedNameSpecifier(DQual))
3344 continue;
3345
3346 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003347 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003348 return true;
3349 }
3350
3351 return false;
3352}
3353
John McCall604e7f12009-12-08 07:46:18 +00003354
John McCalled976492009-12-04 22:46:56 +00003355/// Checks that the given nested-name qualifier used in a using decl
3356/// in the current context is appropriately related to the current
3357/// scope. If an error is found, diagnoses it and returns true.
3358bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3359 const CXXScopeSpec &SS,
3360 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003361 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003362
John McCall604e7f12009-12-08 07:46:18 +00003363 if (!CurContext->isRecord()) {
3364 // C++03 [namespace.udecl]p3:
3365 // C++0x [namespace.udecl]p8:
3366 // A using-declaration for a class member shall be a member-declaration.
3367
3368 // If we weren't able to compute a valid scope, it must be a
3369 // dependent class scope.
3370 if (!NamedContext || NamedContext->isRecord()) {
3371 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3372 << SS.getRange();
3373 return true;
3374 }
3375
3376 // Otherwise, everything is known to be fine.
3377 return false;
3378 }
3379
3380 // The current scope is a record.
3381
3382 // If the named context is dependent, we can't decide much.
3383 if (!NamedContext) {
3384 // FIXME: in C++0x, we can diagnose if we can prove that the
3385 // nested-name-specifier does not refer to a base class, which is
3386 // still possible in some cases.
3387
3388 // Otherwise we have to conservatively report that things might be
3389 // okay.
3390 return false;
3391 }
3392
3393 if (!NamedContext->isRecord()) {
3394 // Ideally this would point at the last name in the specifier,
3395 // but we don't have that level of source info.
3396 Diag(SS.getRange().getBegin(),
3397 diag::err_using_decl_nested_name_specifier_is_not_class)
3398 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3399 return true;
3400 }
3401
3402 if (getLangOptions().CPlusPlus0x) {
3403 // C++0x [namespace.udecl]p3:
3404 // In a using-declaration used as a member-declaration, the
3405 // nested-name-specifier shall name a base class of the class
3406 // being defined.
3407
3408 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3409 cast<CXXRecordDecl>(NamedContext))) {
3410 if (CurContext == NamedContext) {
3411 Diag(NameLoc,
3412 diag::err_using_decl_nested_name_specifier_is_current_class)
3413 << SS.getRange();
3414 return true;
3415 }
3416
3417 Diag(SS.getRange().getBegin(),
3418 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3419 << (NestedNameSpecifier*) SS.getScopeRep()
3420 << cast<CXXRecordDecl>(CurContext)
3421 << SS.getRange();
3422 return true;
3423 }
3424
3425 return false;
3426 }
3427
3428 // C++03 [namespace.udecl]p4:
3429 // A using-declaration used as a member-declaration shall refer
3430 // to a member of a base class of the class being defined [etc.].
3431
3432 // Salient point: SS doesn't have to name a base class as long as
3433 // lookup only finds members from base classes. Therefore we can
3434 // diagnose here only if we can prove that that can't happen,
3435 // i.e. if the class hierarchies provably don't intersect.
3436
3437 // TODO: it would be nice if "definitely valid" results were cached
3438 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3439 // need to be repeated.
3440
3441 struct UserData {
3442 llvm::DenseSet<const CXXRecordDecl*> Bases;
3443
3444 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3445 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3446 Data->Bases.insert(Base);
3447 return true;
3448 }
3449
3450 bool hasDependentBases(const CXXRecordDecl *Class) {
3451 return !Class->forallBases(collect, this);
3452 }
3453
3454 /// Returns true if the base is dependent or is one of the
3455 /// accumulated base classes.
3456 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3457 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3458 return !Data->Bases.count(Base);
3459 }
3460
3461 bool mightShareBases(const CXXRecordDecl *Class) {
3462 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3463 }
3464 };
3465
3466 UserData Data;
3467
3468 // Returns false if we find a dependent base.
3469 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3470 return false;
3471
3472 // Returns false if the class has a dependent base or if it or one
3473 // of its bases is present in the base set of the current context.
3474 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3475 return false;
3476
3477 Diag(SS.getRange().getBegin(),
3478 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3479 << (NestedNameSpecifier*) SS.getScopeRep()
3480 << cast<CXXRecordDecl>(CurContext)
3481 << SS.getRange();
3482
3483 return true;
John McCalled976492009-12-04 22:46:56 +00003484}
3485
Mike Stump1eb44332009-09-09 15:08:12 +00003486Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003487 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003488 SourceLocation AliasLoc,
3489 IdentifierInfo *Alias,
3490 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003491 SourceLocation IdentLoc,
3492 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Anders Carlsson81c85c42009-03-28 23:53:49 +00003494 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003495 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3496 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003497
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003498 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003499 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003500 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003501 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003502 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003503 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003504 if (!R.isAmbiguous() && !R.empty() &&
3505 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003506 return DeclPtrTy();
3507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003509 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3510 diag::err_redefinition_different_kind;
3511 Diag(AliasLoc, DiagID) << Alias;
3512 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003513 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003514 }
3515
John McCalla24dc2e2009-11-17 02:14:36 +00003516 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003517 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003518
John McCallf36e02d2009-10-09 21:13:30 +00003519 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003520 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003521 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003522 }
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003524 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003525 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3526 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003527 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003528 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003530 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003531 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003532}
3533
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003534void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3535 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003536 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3537 !Constructor->isUsed()) &&
3538 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Eli Friedman80c30da2009-11-09 19:20:36 +00003540 CXXRecordDecl *ClassDecl
3541 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3542 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003543
Eli Friedman80c30da2009-11-09 19:20:36 +00003544 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003545 Diag(CurrentLocation, diag::note_member_synthesized_at)
3546 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003547 Constructor->setInvalidDecl();
3548 } else {
3549 Constructor->setUsed();
3550 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003551}
3552
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003553void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003554 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003555 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3556 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003557 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003558 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3559 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003560 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003561 // implicitly defined, all the implicitly-declared default destructors
3562 // for its base class and its non-static data members shall have been
3563 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003564 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3565 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003566 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003567 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003568 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003569 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003570 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3571 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3572 else
Mike Stump1eb44332009-09-09 15:08:12 +00003573 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003574 "DefineImplicitDestructor - missing dtor in a base class");
3575 }
3576 }
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003578 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3579 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003580 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3581 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3582 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003583 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003584 CXXRecordDecl *FieldClassDecl
3585 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3586 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003587 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003588 const_cast<CXXDestructorDecl*>(
3589 FieldClassDecl->getDestructor(Context)))
3590 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3591 else
Mike Stump1eb44332009-09-09 15:08:12 +00003592 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003593 "DefineImplicitDestructor - missing dtor in class of a data member");
3594 }
3595 }
3596 }
Anders Carlsson37909802009-11-30 21:24:50 +00003597
3598 // FIXME: If CheckDestructor fails, we should emit a note about where the
3599 // implicit destructor was needed.
3600 if (CheckDestructor(Destructor)) {
3601 Diag(CurrentLocation, diag::note_member_synthesized_at)
3602 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3603
3604 Destructor->setInvalidDecl();
3605 return;
3606 }
3607
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003608 Destructor->setUsed();
3609}
3610
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003611void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3612 CXXMethodDecl *MethodDecl) {
3613 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3614 MethodDecl->getOverloadedOperator() == OO_Equal &&
3615 !MethodDecl->isUsed()) &&
3616 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003618 CXXRecordDecl *ClassDecl
3619 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003621 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003622 // Before the implicitly-declared copy assignment operator for a class is
3623 // implicitly defined, all implicitly-declared copy assignment operators
3624 // for its direct base classes and its nonstatic data members shall have
3625 // been implicitly defined.
3626 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003627 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3628 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003629 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003630 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003631 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003632 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3633 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003634 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3635 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003636 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3637 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003638 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3639 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3640 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003641 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003642 CXXRecordDecl *FieldClassDecl
3643 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003644 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003645 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3646 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003647 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003648 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003649 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003650 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3651 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003652 Diag(CurrentLocation, diag::note_first_required_here);
3653 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003654 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003655 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003656 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3657 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003658 Diag(CurrentLocation, diag::note_first_required_here);
3659 err = true;
3660 }
3661 }
3662 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003663 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003664}
3665
3666CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003667Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3668 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003669 CXXRecordDecl *ClassDecl) {
3670 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3671 QualType RHSType(LHSType);
3672 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003673 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003674 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003675 RHSType = Context.getCVRQualifiedType(RHSType,
3676 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003677 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003678 LHSType,
3679 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003680 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003681 RHSType,
3682 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003683 Expr *Args[2] = { &*LHS, &*RHS };
3684 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003685 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003686 CandidateSet);
3687 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003688 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003689 return cast<CXXMethodDecl>(Best->Function);
3690 assert(false &&
3691 "getAssignOperatorMethod - copy assignment operator method not found");
3692 return 0;
3693}
3694
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003695void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3696 CXXConstructorDecl *CopyConstructor,
3697 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003698 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003699 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3700 !CopyConstructor->isUsed()) &&
3701 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003703 CXXRecordDecl *ClassDecl
3704 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3705 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003706 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003707 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003708 // implicitly defined, all the implicitly-declared copy constructors
3709 // for its base class and its non-static data members shall have been
3710 // implicitly defined.
3711 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3712 Base != ClassDecl->bases_end(); ++Base) {
3713 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003714 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003715 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003716 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003717 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003718 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003719 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3720 FieldEnd = ClassDecl->field_end();
3721 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003722 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3723 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3724 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003725 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003726 CXXRecordDecl *FieldClassDecl
3727 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003728 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003729 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003730 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003731 }
3732 }
3733 CopyConstructor->setUsed();
3734}
3735
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003736Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003737Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003738 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003739 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003740 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Douglas Gregor39da0b82009-09-09 23:08:42 +00003742 // C++ [class.copy]p15:
3743 // Whenever a temporary class object is copied using a copy constructor, and
3744 // this object and the copy have the same cv-unqualified type, an
3745 // implementation is permitted to treat the original and the copy as two
3746 // different ways of referring to the same object and not perform a copy at
3747 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003749 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00003750 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003751 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003752 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3753 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003754 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3755 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3756 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003757
3758 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3759 Elidable = !CE->getCallReturnType()->isReferenceType();
3760 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003761 Elidable = true;
3762 }
Mike Stump1eb44332009-09-09 15:08:12 +00003763
3764 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003765 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003766}
3767
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003768/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3769/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003770Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003771Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3772 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003773 MultiExprArg ExprArgs) {
3774 unsigned NumExprs = ExprArgs.size();
3775 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Douglas Gregor7edfb692009-11-23 12:27:39 +00003777 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003778 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3779 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003780}
3781
Anders Carlssone7624a72009-08-27 05:08:22 +00003782Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003783Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3784 QualType Ty,
3785 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003786 MultiExprArg Args,
3787 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003788 unsigned NumExprs = Args.size();
3789 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Douglas Gregor7edfb692009-11-23 12:27:39 +00003791 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003792 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3793 TyBeginLoc, Exprs,
3794 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003795}
3796
3797
Mike Stump1eb44332009-09-09 15:08:12 +00003798bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003799 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003800 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003801 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003802 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003803 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003804 if (TempResult.isInvalid())
3805 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003806
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003807 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003808 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00003809 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00003810 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Anders Carlssonfe2de492009-08-25 05:18:00 +00003812 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003813}
3814
Mike Stump1eb44332009-09-09 15:08:12 +00003815void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003816 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00003817 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003818 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00003819 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003820 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003821 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003822}
3823
Mike Stump1eb44332009-09-09 15:08:12 +00003824/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003825/// ActOnDeclarator, when a C++ direct initializer is present.
3826/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00003827void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3828 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00003829 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003830 SourceLocation *CommaLocs,
3831 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00003832 unsigned NumExprs = Exprs.size();
3833 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00003834 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003835
3836 // If there is no declaration, there was an error parsing it. Just ignore
3837 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003838 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003839 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003841 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3842 if (!VDecl) {
3843 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3844 RealDecl->setInvalidDecl();
3845 return;
3846 }
3847
Douglas Gregor83ddad32009-08-26 21:14:46 +00003848 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003849 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003850 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3851 //
3852 // Clients that want to distinguish between the two forms, can check for
3853 // direct initializer using VarDecl::hasCXXDirectInitializer().
3854 // A major benefit is that clients that don't particularly care about which
3855 // exactly form was it (like the CodeGen) can handle both cases without
3856 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003857
Douglas Gregor83ddad32009-08-26 21:14:46 +00003858 // If either the declaration has a dependent type or if any of the expressions
3859 // is type-dependent, we represent the initialization via a ParenListExpr for
3860 // later use during template instantiation.
3861 if (VDecl->getType()->isDependentType() ||
3862 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3863 // Let clients know that initialization was done with a direct initializer.
3864 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Douglas Gregor83ddad32009-08-26 21:14:46 +00003866 // Store the initialization expressions as a ParenListExpr.
3867 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003868 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003869 new (Context) ParenListExpr(Context, LParenLoc,
3870 (Expr **)Exprs.release(),
3871 NumExprs, RParenLoc));
3872 return;
3873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Douglas Gregor83ddad32009-08-26 21:14:46 +00003875
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003876 // C++ 8.5p11:
3877 // The form of initialization (using parentheses or '=') is generally
3878 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003879 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003880 QualType DeclInitType = VDecl->getType();
3881 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00003882 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003883
Douglas Gregor615c5d42009-03-24 16:43:20 +00003884 // FIXME: This isn't the right place to complete the type.
3885 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3886 diag::err_typecheck_decl_incomplete_type)) {
3887 VDecl->setInvalidDecl();
3888 return;
3889 }
3890
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003891 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003892 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3893
Douglas Gregor18fe5682008-11-03 20:45:27 +00003894 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003895 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003896 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003897 VDecl->getLocation(),
3898 SourceRange(VDecl->getLocation(),
3899 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003900 VDecl->getDeclName(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003901 InitializationKind::CreateDirect(VDecl->getLocation(),
3902 LParenLoc,
3903 RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003904 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003905 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003906 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003907 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003908 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003909 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003910 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003911 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003912 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003913 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003914 return;
3915 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003916
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003917 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003918 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3919 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003920 RealDecl->setInvalidDecl();
3921 return;
3922 }
3923
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003924 // Let clients know that initialization was done with a direct initializer.
3925 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003926
3927 assert(NumExprs == 1 && "Expected 1 expression");
3928 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003929 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3930 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003931}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003932
Douglas Gregor19aeac62009-11-14 03:27:21 +00003933/// \brief Add the applicable constructor candidates for an initialization
3934/// by constructor.
3935static void AddConstructorInitializationCandidates(Sema &SemaRef,
3936 QualType ClassType,
3937 Expr **Args,
3938 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00003939 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003940 OverloadCandidateSet &CandidateSet) {
3941 // C++ [dcl.init]p14:
3942 // If the initialization is direct-initialization, or if it is
3943 // copy-initialization where the cv-unqualified version of the
3944 // source type is the same class as, or a derived class of, the
3945 // class of the destination, constructors are considered. The
3946 // applicable constructors are enumerated (13.3.1.3), and the
3947 // best one is chosen through overload resolution (13.3). The
3948 // constructor so selected is called to initialize the object,
3949 // with the initializer expression(s) as its argument(s). If no
3950 // constructor applies, or the overload resolution is ambiguous,
3951 // the initialization is ill-formed.
3952 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3953 assert(ClassRec && "Can only initialize a class type here");
3954
3955 // FIXME: When we decide not to synthesize the implicitly-declared
3956 // constructors, we'll need to make them appear here.
3957
3958 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3959 DeclarationName ConstructorName
3960 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3961 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3962 DeclContext::lookup_const_iterator Con, ConEnd;
3963 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3964 Con != ConEnd; ++Con) {
3965 // Find the constructor (which may be a template).
3966 CXXConstructorDecl *Constructor = 0;
3967 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3968 if (ConstructorTmpl)
3969 Constructor
3970 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3971 else
3972 Constructor = cast<CXXConstructorDecl>(*Con);
3973
Douglas Gregor20093b42009-12-09 23:02:17 +00003974 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
3975 (Kind.getKind() == InitializationKind::IK_Value) ||
3976 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00003977 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003978 ((Kind.getKind() == InitializationKind::IK_Default) &&
3979 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00003980 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00003981 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3982 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00003983 Args, NumArgs, CandidateSet);
3984 else
3985 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3986 }
3987 }
3988}
3989
3990/// \brief Attempt to perform initialization by constructor
3991/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3992/// copy-initialization.
3993///
3994/// This routine determines whether initialization by constructor is possible,
3995/// but it does not emit any diagnostics in the case where the initialization
3996/// is ill-formed.
3997///
3998/// \param ClassType the type of the object being initialized, which must have
3999/// class type.
4000///
4001/// \param Args the arguments provided to initialize the object
4002///
4003/// \param NumArgs the number of arguments provided to initialize the object
4004///
4005/// \param Kind the type of initialization being performed
4006///
4007/// \returns the constructor used to initialize the object, if successful.
4008/// Otherwise, emits a diagnostic and returns NULL.
4009CXXConstructorDecl *
4010Sema::TryInitializationByConstructor(QualType ClassType,
4011 Expr **Args, unsigned NumArgs,
4012 SourceLocation Loc,
4013 InitializationKind Kind) {
4014 // Build the overload candidate set
4015 OverloadCandidateSet CandidateSet;
4016 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4017 CandidateSet);
4018
4019 // Determine whether we found a constructor we can use.
4020 OverloadCandidateSet::iterator Best;
4021 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4022 case OR_Success:
4023 case OR_Deleted:
4024 // We found a constructor. Return it.
4025 return cast<CXXConstructorDecl>(Best->Function);
4026
4027 case OR_No_Viable_Function:
4028 case OR_Ambiguous:
4029 // Overload resolution failed. Return nothing.
4030 return 0;
4031 }
4032
4033 // Silence GCC warning
4034 return 0;
4035}
4036
Douglas Gregor39da0b82009-09-09 23:08:42 +00004037/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4038/// may occur as part of direct-initialization or copy-initialization.
4039///
4040/// \param ClassType the type of the object being initialized, which must have
4041/// class type.
4042///
4043/// \param ArgsPtr the arguments provided to initialize the object
4044///
4045/// \param Loc the source location where the initialization occurs
4046///
4047/// \param Range the source range that covers the entire initialization
4048///
4049/// \param InitEntity the name of the entity being initialized, if known
4050///
4051/// \param Kind the type of initialization being performed
4052///
4053/// \param ConvertedArgs a vector that will be filled in with the
4054/// appropriately-converted arguments to the constructor (if initialization
4055/// succeeded).
4056///
4057/// \returns the constructor used to initialize the object, if successful.
4058/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004059CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004060Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004061 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004062 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004063 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004064 InitializationKind Kind,
4065 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004066
4067 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004068 Expr **Args = (Expr **)ArgsPtr.get();
4069 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004070 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004071 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4072 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004073
Douglas Gregor18fe5682008-11-03 20:45:27 +00004074 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004075 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004076 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004077 // We found a constructor. Break out so that we can convert the arguments
4078 // appropriately.
4079 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Douglas Gregor18fe5682008-11-03 20:45:27 +00004081 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004082 if (InitEntity)
4083 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004084 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004085 else
4086 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004087 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00004088 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004089 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004090
Douglas Gregor18fe5682008-11-03 20:45:27 +00004091 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004092 if (InitEntity)
4093 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4094 else
4095 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004096 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4097 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004098
4099 case OR_Deleted:
4100 if (InitEntity)
4101 Diag(Loc, diag::err_ovl_deleted_init)
4102 << Best->Function->isDeleted()
4103 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004104 else {
4105 const CXXRecordDecl *RD =
4106 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004107 Diag(Loc, diag::err_ovl_deleted_init)
4108 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004109 << RD->getDeclName() << Range;
4110 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004111 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4112 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004113 }
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Douglas Gregor39da0b82009-09-09 23:08:42 +00004115 // Convert the arguments, fill in default arguments, etc.
4116 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4117 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4118 return 0;
4119
4120 return Constructor;
4121}
4122
4123/// \brief Given a constructor and the set of arguments provided for the
4124/// constructor, convert the arguments and add any required default arguments
4125/// to form a proper call to this constructor.
4126///
4127/// \returns true if an error occurred, false otherwise.
4128bool
4129Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4130 MultiExprArg ArgsPtr,
4131 SourceLocation Loc,
4132 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4133 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4134 unsigned NumArgs = ArgsPtr.size();
4135 Expr **Args = (Expr **)ArgsPtr.get();
4136
4137 const FunctionProtoType *Proto
4138 = Constructor->getType()->getAs<FunctionProtoType>();
4139 assert(Proto && "Constructor without a prototype?");
4140 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004141
4142 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004143 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004144 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004145 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004146 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004147
4148 VariadicCallType CallType =
4149 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4150 llvm::SmallVector<Expr *, 8> AllArgs;
4151 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4152 Proto, 0, Args, NumArgs, AllArgs,
4153 CallType);
4154 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4155 ConvertedArgs.push_back(AllArgs[i]);
4156 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004157}
4158
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004159/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4160/// determine whether they are reference-related,
4161/// reference-compatible, reference-compatible with added
4162/// qualification, or incompatible, for use in C++ initialization by
4163/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4164/// type, and the first type (T1) is the pointee type of the reference
4165/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004166Sema::ReferenceCompareResult
Douglas Gregor393896f2009-11-05 13:06:35 +00004167Sema::CompareReferenceRelationship(SourceLocation Loc,
4168 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004169 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004170 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004171 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004172 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004173
Douglas Gregor393896f2009-11-05 13:06:35 +00004174 QualType T1 = Context.getCanonicalType(OrigT1);
4175 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00004176 QualType UnqualT1 = T1.getLocalUnqualifiedType();
4177 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004178
4179 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004180 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004181 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004182 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004183 if (UnqualT1 == UnqualT2)
4184 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004185 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4186 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4187 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004188 DerivedToBase = true;
4189 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004190 return Ref_Incompatible;
4191
4192 // At this point, we know that T1 and T2 are reference-related (at
4193 // least).
4194
4195 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004196 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004197 // reference-related to T2 and cv1 is the same cv-qualification
4198 // as, or greater cv-qualification than, cv2. For purposes of
4199 // overload resolution, cases for which cv1 is greater
4200 // cv-qualification than cv2 are identified as
4201 // reference-compatible with added qualification (see 13.3.3.2).
4202 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
4203 return Ref_Compatible;
4204 else if (T1.isMoreQualifiedThan(T2))
4205 return Ref_Compatible_With_Added_Qualification;
4206 else
4207 return Ref_Related;
4208}
4209
4210/// CheckReferenceInit - Check the initialization of a reference
4211/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4212/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004213/// list), and DeclType is the type of the declaration. When ICS is
4214/// non-null, this routine will compute the implicit conversion
4215/// sequence according to C++ [over.ics.ref] and will not produce any
4216/// diagnostics; when ICS is null, it will emit diagnostics when any
4217/// errors are found. Either way, a return value of true indicates
4218/// that there was a failure, a return value of false indicates that
4219/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004220///
4221/// When @p SuppressUserConversions, user-defined conversions are
4222/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004223/// When @p AllowExplicit, we also permit explicit user-defined
4224/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004225/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004226/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4227/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004228bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004229Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004230 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004231 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004232 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004233 ImplicitConversionSequence *ICS,
4234 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004235 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4236
Ted Kremenek6217b802009-07-29 21:53:49 +00004237 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004238 QualType T2 = Init->getType();
4239
Douglas Gregor904eed32008-11-10 20:40:00 +00004240 // If the initializer is the address of an overloaded function, try
4241 // to resolve the overloaded function. If all goes well, T2 is the
4242 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004243 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004245 ICS != 0);
4246 if (Fn) {
4247 // Since we're performing this reference-initialization for
4248 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004249 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004250 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004251 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004252
Anders Carlsson96ad5332009-10-21 17:16:23 +00004253 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004254 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004255
4256 T2 = Fn->getType();
4257 }
4258 }
4259
Douglas Gregor15da57e2008-10-29 02:00:59 +00004260 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004261 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004262 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004263 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4264 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004265 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004266 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004267
4268 // Most paths end in a failed conversion.
4269 if (ICS)
4270 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004271
4272 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004273 // A reference to type "cv1 T1" is initialized by an expression
4274 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004275
4276 // -- If the initializer expression
4277
Sebastian Redla9845802009-03-29 15:27:50 +00004278 // Rvalue references cannot bind to lvalues (N2812).
4279 // There is absolutely no situation where they can. In particular, note that
4280 // this is ill-formed, even if B has a user-defined conversion to A&&:
4281 // B b;
4282 // A&& r = b;
4283 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4284 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004285 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004286 << Init->getSourceRange();
4287 return true;
4288 }
4289
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004290 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004291 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4292 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004293 //
4294 // Note that the bit-field check is skipped if we are just computing
4295 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004296 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004297 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004298 BindsDirectly = true;
4299
Douglas Gregor15da57e2008-10-29 02:00:59 +00004300 if (ICS) {
4301 // C++ [over.ics.ref]p1:
4302 // When a parameter of reference type binds directly (8.5.3)
4303 // to an argument expression, the implicit conversion sequence
4304 // is the identity conversion, unless the argument expression
4305 // has a type that is a derived class of the parameter type,
4306 // in which case the implicit conversion sequence is a
4307 // derived-to-base Conversion (13.3.3.1).
4308 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4309 ICS->Standard.First = ICK_Identity;
4310 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4311 ICS->Standard.Third = ICK_Identity;
4312 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4313 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004314 ICS->Standard.ReferenceBinding = true;
4315 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004316 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004317 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004318
4319 // Nothing more to do: the inaccessibility/ambiguity check for
4320 // derived-to-base conversions is suppressed when we're
4321 // computing the implicit conversion sequence (C++
4322 // [over.best.ics]p2).
4323 return false;
4324 } else {
4325 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004326 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4327 if (DerivedToBase)
4328 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004329 else if(CheckExceptionSpecCompatibility(Init, T1))
4330 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004331 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004332 }
4333 }
4334
4335 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004336 // implicitly converted to an lvalue of type "cv3 T3,"
4337 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004338 // 92) (this conversion is selected by enumerating the
4339 // applicable conversion functions (13.3.1.6) and choosing
4340 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004341 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004342 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004343 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004344 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004345
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004346 OverloadCandidateSet CandidateSet;
John McCallba135432009-11-21 08:51:07 +00004347 const UnresolvedSet *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004348 = T2RecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00004349 for (UnresolvedSet::iterator I = Conversions->begin(),
4350 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004351 NamedDecl *D = *I;
4352 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4353 if (isa<UsingShadowDecl>(D))
4354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4355
Mike Stump1eb44332009-09-09 15:08:12 +00004356 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004357 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004358 CXXConversionDecl *Conv;
4359 if (ConvTemplate)
4360 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4361 else
John McCall701c89e2009-12-03 04:06:58 +00004362 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004363
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004364 // If the conversion function doesn't return a reference type,
4365 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004366 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004367 (AllowExplicit || !Conv->isExplicit())) {
4368 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00004369 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
4370 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004371 else
John McCall701c89e2009-12-03 04:06:58 +00004372 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004373 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004374 }
4375
4376 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004377 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004378 case OR_Success:
4379 // This is a direct binding.
4380 BindsDirectly = true;
4381
4382 if (ICS) {
4383 // C++ [over.ics.ref]p1:
4384 //
4385 // [...] If the parameter binds directly to the result of
4386 // applying a conversion function to the argument
4387 // expression, the implicit conversion sequence is a
4388 // user-defined conversion sequence (13.3.3.1.2), with the
4389 // second standard conversion sequence either an identity
4390 // conversion or, if the conversion function returns an
4391 // entity of a type that is a derived class of the parameter
4392 // type, a derived-to-base Conversion.
4393 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
4394 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4395 ICS->UserDefined.After = Best->FinalConversion;
4396 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004397 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004398 assert(ICS->UserDefined.After.ReferenceBinding &&
4399 ICS->UserDefined.After.DirectBinding &&
4400 "Expected a direct reference binding!");
4401 return false;
4402 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004403 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004404 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004405 CastExpr::CK_UserDefinedConversion,
4406 cast<CXXMethodDecl>(Best->Function),
4407 Owned(Init));
4408 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004409
4410 if (CheckExceptionSpecCompatibility(Init, T1))
4411 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004412 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4413 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004414 }
4415 break;
4416
4417 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004418 if (ICS) {
4419 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4420 Cand != CandidateSet.end(); ++Cand)
4421 if (Cand->Viable)
4422 ICS->ConversionFunctionSet.push_back(Cand->Function);
4423 break;
4424 }
4425 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4426 << Init->getSourceRange();
4427 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004428 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004429
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004430 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004431 case OR_Deleted:
4432 // There was no suitable conversion, or we found a deleted
4433 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004434 break;
4435 }
4436 }
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004438 if (BindsDirectly) {
4439 // C++ [dcl.init.ref]p4:
4440 // [...] In all cases where the reference-related or
4441 // reference-compatible relationship of two types is used to
4442 // establish the validity of a reference binding, and T1 is a
4443 // base class of T2, a program that necessitates such a binding
4444 // is ill-formed if T1 is an inaccessible (clause 11) or
4445 // ambiguous (10.2) base class of T2.
4446 //
4447 // Note that we only check this condition when we're allowed to
4448 // complain about errors, because we should not be checking for
4449 // ambiguity (or inaccessibility) unless the reference binding
4450 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004451 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004452 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004453 Init->getSourceRange(),
4454 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004455 else
4456 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004457 }
4458
4459 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004460 // type (i.e., cv1 shall be const), or the reference shall be an
4461 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004462 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004463 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004464 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00004465 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4466 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004467 return true;
4468 }
4469
4470 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004471 // class type, and "cv1 T1" is reference-compatible with
4472 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004473 // following ways (the choice is implementation-defined):
4474 //
4475 // -- The reference is bound to the object represented by
4476 // the rvalue (see 3.10) or to a sub-object within that
4477 // object.
4478 //
Eli Friedman33a31382009-08-05 19:21:58 +00004479 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004480 // a constructor is called to copy the entire rvalue
4481 // object into the temporary. The reference is bound to
4482 // the temporary or to a sub-object within the
4483 // temporary.
4484 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004485 // The constructor that would be used to make the copy
4486 // shall be callable whether or not the copy is actually
4487 // done.
4488 //
Sebastian Redla9845802009-03-29 15:27:50 +00004489 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004490 // freedom, so we will always take the first option and never build
4491 // a temporary in this case. FIXME: We will, however, have to check
4492 // for the presence of a copy constructor in C++98/03 mode.
4493 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004494 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4495 if (ICS) {
4496 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4497 ICS->Standard.First = ICK_Identity;
4498 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4499 ICS->Standard.Third = ICK_Identity;
4500 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4501 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004502 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004503 ICS->Standard.DirectBinding = false;
4504 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004505 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004506 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004507 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4508 if (DerivedToBase)
4509 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004510 else if(CheckExceptionSpecCompatibility(Init, T1))
4511 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004512 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004513 }
4514 return false;
4515 }
4516
Eli Friedman33a31382009-08-05 19:21:58 +00004517 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004518 // initialized from the initializer expression using the
4519 // rules for a non-reference copy initialization (8.5). The
4520 // reference is then bound to the temporary. If T1 is
4521 // reference-related to T2, cv1 must be the same
4522 // cv-qualification as, or greater cv-qualification than,
4523 // cv2; otherwise, the program is ill-formed.
4524 if (RefRelationship == Ref_Related) {
4525 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4526 // we would be reference-compatible or reference-compatible with
4527 // added qualification. But that wasn't the case, so the reference
4528 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004529 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004530 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00004531 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4532 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004533 return true;
4534 }
4535
Douglas Gregor734d9862009-01-30 23:27:23 +00004536 // If at least one of the types is a class type, the types are not
4537 // related, and we aren't allowed any user conversions, the
4538 // reference binding fails. This case is important for breaking
4539 // recursion, since TryImplicitConversion below will attempt to
4540 // create a temporary through the use of a copy constructor.
4541 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4542 (T1->isRecordType() || T2->isRecordType())) {
4543 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004544 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor734d9862009-01-30 23:27:23 +00004545 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4546 return true;
4547 }
4548
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004549 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004550 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004551 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004552 //
Sebastian Redla9845802009-03-29 15:27:50 +00004553 // When a parameter of reference type is not bound directly to
4554 // an argument expression, the conversion sequence is the one
4555 // required to convert the argument expression to the
4556 // underlying type of the reference according to
4557 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4558 // to copy-initializing a temporary of the underlying type with
4559 // the argument expression. Any difference in top-level
4560 // cv-qualification is subsumed by the initialization itself
4561 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004562 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4563 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004564 /*ForceRValue=*/false,
4565 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004566
Sebastian Redla9845802009-03-29 15:27:50 +00004567 // Of course, that's still a reference binding.
4568 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4569 ICS->Standard.ReferenceBinding = true;
4570 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004571 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00004572 ImplicitConversionSequence::UserDefinedConversion) {
4573 ICS->UserDefined.After.ReferenceBinding = true;
4574 ICS->UserDefined.After.RRefBinding = isRValRef;
4575 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00004576 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4577 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004578 ImplicitConversionSequence Conversions;
4579 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4580 false, false,
4581 Conversions);
4582 if (badConversion) {
4583 if ((Conversions.ConversionKind ==
4584 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian82ad87b2009-09-28 22:03:07 +00004585 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004586 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004587 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4588 for (int j = Conversions.ConversionFunctionSet.size()-1;
4589 j >= 0; j--) {
4590 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4591 Diag(Func->getLocation(), diag::err_ovl_candidate);
4592 }
4593 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004594 else {
4595 if (isRValRef)
4596 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4597 << Init->getSourceRange();
4598 else
4599 Diag(DeclLoc, diag::err_invalid_initialization)
4600 << DeclType << Init->getType() << Init->getSourceRange();
4601 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004602 }
4603 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004604 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004605}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004606
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004607static bool
Anders Carlssona3ccda52009-12-12 00:26:23 +00004608CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
4609 bool ret = false;
4610 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4611 QualType SizeTy =
4612 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4613 QualType T = SemaRef.Context.getCanonicalType((*Param)->getType());
4614 if (!T->isDependentType() && SizeTy != T) {
4615 SemaRef.Diag(FnDecl->getLocation(),
4616 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4617 << SizeTy;
4618 ret = true;
4619 }
4620 }
4621 QualType ResultTy = SemaRef.Context.getCanonicalType(FnDecl->getResultType());
4622 if (!ResultTy->isDependentType() && ResultTy != SemaRef.Context.VoidPtrTy)
4623 return SemaRef.Diag(FnDecl->getLocation(),
4624 diag::err_operator_new_delete_invalid_result_type)
4625 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4626 return ret;
4627}
4628
4629static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004630CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4631 // C++ [basic.stc.dynamic.deallocation]p1:
4632 // A program is ill-formed if deallocation functions are declared in a
4633 // namespace scope other than global scope or declared static in global
4634 // scope.
4635 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4636 if (isa<NamespaceDecl>(DC)) {
4637 return SemaRef.Diag(FnDecl->getLocation(),
4638 diag::err_operator_new_delete_declared_in_namespace)
4639 << FnDecl->getDeclName();
4640 } else if (isa<TranslationUnitDecl>(DC) &&
4641 FnDecl->getStorageClass() == FunctionDecl::Static) {
4642 return SemaRef.Diag(FnDecl->getLocation(),
4643 diag::err_operator_new_delete_declared_static)
4644 << FnDecl->getDeclName();
4645 }
4646
4647 // C++ [basic.stc.dynamic.deallocation]p2:
4648 // Each deallocation function shall return void and its first parameter
4649 // shall be void*.
4650 QualType ResultType = FnDecl->getResultType();
Anders Carlsson46991d62009-12-12 00:16:02 +00004651 if (ResultType->isDependentType())
4652 return SemaRef.Diag(FnDecl->getLocation(),
4653 diag::err_operator_new_delete_dependent_result_type)
4654 << FnDecl->getDeclName() << SemaRef.Context.VoidTy;
4655
4656 if (!ResultType->isVoidType())
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004657 return SemaRef.Diag(FnDecl->getLocation(),
4658 diag::err_operator_new_delete_invalid_result_type)
4659 << FnDecl->getDeclName() << SemaRef.Context.VoidTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004660
Anders Carlsson46991d62009-12-12 00:16:02 +00004661 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4662 return SemaRef.Diag(FnDecl->getLocation(),
4663 diag::err_operator_new_delete_template_too_few_parameters)
4664 << FnDecl->getDeclName();
4665 else if (FnDecl->getNumParams() == 0)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004666 return SemaRef.Diag(FnDecl->getLocation(),
4667 diag::err_operator_new_delete_too_few_parameters)
4668 << FnDecl->getDeclName();
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004669
Anders Carlsson46991d62009-12-12 00:16:02 +00004670 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4671 if (FirstParamType->isDependentType())
4672 return SemaRef.Diag(FnDecl->getLocation(),
4673 diag::err_operator_delete_dependent_param_type)
4674 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4675
4676 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4677 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004678 return SemaRef.Diag(FnDecl->getLocation(),
4679 diag::err_operator_delete_param_type)
4680 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004681
4682 return false;
4683}
4684
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004685/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4686/// of this overloaded operator is well-formed. If so, returns false;
4687/// otherwise, emits appropriate diagnostics and returns true.
4688bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004689 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004690 "Expected an overloaded operator declaration");
4691
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004692 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4693
Mike Stump1eb44332009-09-09 15:08:12 +00004694 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004695 // The allocation and deallocation functions, operator new,
4696 // operator new[], operator delete and operator delete[], are
4697 // described completely in 3.7.3. The attributes and restrictions
4698 // found in the rest of this subclause do not apply to them unless
4699 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004700 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004701 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004702
Anders Carlssona3ccda52009-12-12 00:26:23 +00004703 if (Op == OO_New || Op == OO_Array_New)
4704 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004705
4706 // C++ [over.oper]p6:
4707 // An operator function shall either be a non-static member
4708 // function or be a non-member function and have at least one
4709 // parameter whose type is a class, a reference to a class, an
4710 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004711 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4712 if (MethodDecl->isStatic())
4713 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004714 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004715 } else {
4716 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004717 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4718 ParamEnd = FnDecl->param_end();
4719 Param != ParamEnd; ++Param) {
4720 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004721 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4722 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004723 ClassOrEnumParam = true;
4724 break;
4725 }
4726 }
4727
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004728 if (!ClassOrEnumParam)
4729 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004730 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004731 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004732 }
4733
4734 // C++ [over.oper]p8:
4735 // An operator function cannot have default arguments (8.3.6),
4736 // except where explicitly stated below.
4737 //
Mike Stump1eb44332009-09-09 15:08:12 +00004738 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004739 // (C++ [over.call]p1).
4740 if (Op != OO_Call) {
4741 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4742 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00004743 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004744 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004745 diag::err_operator_overload_default_arg)
4746 << FnDecl->getDeclName();
4747 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004748 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004749 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004750 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004751 }
4752 }
4753
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004754 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4755 { false, false, false }
4756#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4757 , { Unary, Binary, MemberOnly }
4758#include "clang/Basic/OperatorKinds.def"
4759 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004760
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004761 bool CanBeUnaryOperator = OperatorUses[Op][0];
4762 bool CanBeBinaryOperator = OperatorUses[Op][1];
4763 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004764
4765 // C++ [over.oper]p8:
4766 // [...] Operator functions cannot have more or fewer parameters
4767 // than the number required for the corresponding operator, as
4768 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004769 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004770 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004771 if (Op != OO_Call &&
4772 ((NumParams == 1 && !CanBeUnaryOperator) ||
4773 (NumParams == 2 && !CanBeBinaryOperator) ||
4774 (NumParams < 1) || (NumParams > 2))) {
4775 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004776 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004777 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004778 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004779 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004780 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004781 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004782 assert(CanBeBinaryOperator &&
4783 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004784 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004785 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004786
Chris Lattner416e46f2008-11-21 07:57:12 +00004787 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004788 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004789 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004790
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004791 // Overloaded operators other than operator() cannot be variadic.
4792 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004793 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004794 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004795 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004796 }
4797
4798 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004799 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4800 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004801 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004802 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004803 }
4804
4805 // C++ [over.inc]p1:
4806 // The user-defined function called operator++ implements the
4807 // prefix and postfix ++ operator. If this function is a member
4808 // function with no parameters, or a non-member function with one
4809 // parameter of class or enumeration type, it defines the prefix
4810 // increment operator ++ for objects of that type. If the function
4811 // is a member function with one parameter (which shall be of type
4812 // int) or a non-member function with two parameters (the second
4813 // of which shall be of type int), it defines the postfix
4814 // increment operator ++ for objects of that type.
4815 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4816 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4817 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004818 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004819 ParamIsInt = BT->getKind() == BuiltinType::Int;
4820
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004821 if (!ParamIsInt)
4822 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004823 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004824 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004825 }
4826
Sebastian Redl64b45f72009-01-05 20:52:13 +00004827 // Notify the class if it got an assignment operator.
4828 if (Op == OO_Equal) {
4829 // Would have returned earlier otherwise.
4830 assert(isa<CXXMethodDecl>(FnDecl) &&
4831 "Overloaded = not member, but not filtered.");
4832 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4833 Method->getParent()->addedAssignmentOperator(Context, Method);
4834 }
4835
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004836 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004837}
Chris Lattner5a003a42008-12-17 07:09:26 +00004838
Douglas Gregor074149e2009-01-05 19:45:36 +00004839/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4840/// linkage specification, including the language and (if present)
4841/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4842/// the location of the language string literal, which is provided
4843/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4844/// the '{' brace. Otherwise, this linkage specification does not
4845/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004846Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4847 SourceLocation ExternLoc,
4848 SourceLocation LangLoc,
4849 const char *Lang,
4850 unsigned StrSize,
4851 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004852 LinkageSpecDecl::LanguageIDs Language;
4853 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4854 Language = LinkageSpecDecl::lang_c;
4855 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4856 Language = LinkageSpecDecl::lang_cxx;
4857 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004858 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004859 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004860 }
Mike Stump1eb44332009-09-09 15:08:12 +00004861
Chris Lattnercc98eac2008-12-17 07:13:27 +00004862 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Douglas Gregor074149e2009-01-05 19:45:36 +00004864 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004865 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004866 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004867 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004868 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004869 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004870}
4871
Douglas Gregor074149e2009-01-05 19:45:36 +00004872/// ActOnFinishLinkageSpecification - Completely the definition of
4873/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4874/// valid, it's the position of the closing '}' brace in a linkage
4875/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004876Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4877 DeclPtrTy LinkageSpec,
4878 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004879 if (LinkageSpec)
4880 PopDeclContext();
4881 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004882}
4883
Douglas Gregord308e622009-05-18 20:51:54 +00004884/// \brief Perform semantic analysis for the variable declaration that
4885/// occurs within a C++ catch clause, returning the newly-created
4886/// variable.
4887VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004888 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004889 IdentifierInfo *Name,
4890 SourceLocation Loc,
4891 SourceRange Range) {
4892 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004893
4894 // Arrays and functions decay.
4895 if (ExDeclType->isArrayType())
4896 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4897 else if (ExDeclType->isFunctionType())
4898 ExDeclType = Context.getPointerType(ExDeclType);
4899
4900 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4901 // The exception-declaration shall not denote a pointer or reference to an
4902 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004903 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004904 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004905 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004906 Invalid = true;
4907 }
Douglas Gregord308e622009-05-18 20:51:54 +00004908
Sebastian Redl4b07b292008-12-22 19:15:10 +00004909 QualType BaseType = ExDeclType;
4910 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004911 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00004912 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004913 BaseType = Ptr->getPointeeType();
4914 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004915 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004916 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004917 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004918 BaseType = Ref->getPointeeType();
4919 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004920 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004921 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004922 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00004923 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00004924 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004925
Mike Stump1eb44332009-09-09 15:08:12 +00004926 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004927 RequireNonAbstractType(Loc, ExDeclType,
4928 diag::err_abstract_type_in_decl,
4929 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004930 Invalid = true;
4931
Douglas Gregord308e622009-05-18 20:51:54 +00004932 // FIXME: Need to test for ability to copy-construct and destroy the
4933 // exception variable.
4934
Sebastian Redl8351da02008-12-22 21:35:02 +00004935 // FIXME: Need to check for abstract classes.
4936
Mike Stump1eb44332009-09-09 15:08:12 +00004937 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00004938 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004939
4940 if (Invalid)
4941 ExDecl->setInvalidDecl();
4942
4943 return ExDecl;
4944}
4945
4946/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4947/// handler.
4948Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00004949 TypeSourceInfo *TInfo = 0;
4950 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004951
4952 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004953 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00004954 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004955 // The scope should be freshly made just for us. There is just no way
4956 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004957 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004958 if (PrevDecl->isTemplateParameter()) {
4959 // Maybe we will complain about the shadowed template parameter.
4960 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004961 }
4962 }
4963
Chris Lattnereaaebc72009-04-25 08:06:05 +00004964 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004965 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4966 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004967 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004968 }
4969
John McCalla93c9342009-12-07 02:54:59 +00004970 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004971 D.getIdentifier(),
4972 D.getIdentifierLoc(),
4973 D.getDeclSpec().getSourceRange());
4974
Chris Lattnereaaebc72009-04-25 08:06:05 +00004975 if (Invalid)
4976 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Sebastian Redl4b07b292008-12-22 19:15:10 +00004978 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004979 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004980 PushOnScopeChains(ExDecl, S);
4981 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004982 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004983
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004984 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004985 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004986}
Anders Carlssonfb311762009-03-14 00:25:26 +00004987
Mike Stump1eb44332009-09-09 15:08:12 +00004988Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004989 ExprArg assertexpr,
4990 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004991 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004992 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004993 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4994
Anders Carlssonc3082412009-03-14 00:33:21 +00004995 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4996 llvm::APSInt Value(32);
4997 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4998 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4999 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005000 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005001 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005002
Anders Carlssonc3082412009-03-14 00:33:21 +00005003 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005004 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005005 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005006 }
5007 }
Mike Stump1eb44332009-09-09 15:08:12 +00005008
Anders Carlsson77d81422009-03-15 17:35:16 +00005009 assertexpr.release();
5010 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005011 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005012 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005014 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005015 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005016}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005017
John McCalldd4a3b02009-09-16 22:47:08 +00005018/// Handle a friend type declaration. This works in tandem with
5019/// ActOnTag.
5020///
5021/// Notes on friend class templates:
5022///
5023/// We generally treat friend class declarations as if they were
5024/// declaring a class. So, for example, the elaborated type specifier
5025/// in a friend declaration is required to obey the restrictions of a
5026/// class-head (i.e. no typedefs in the scope chain), template
5027/// parameters are required to match up with simple template-ids, &c.
5028/// However, unlike when declaring a template specialization, it's
5029/// okay to refer to a template specialization without an empty
5030/// template parameter declaration, e.g.
5031/// friend class A<T>::B<unsigned>;
5032/// We permit this as a special case; if there are any template
5033/// parameters present at all, require proper matching, i.e.
5034/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005035Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005036 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005037 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005038
5039 assert(DS.isFriendSpecified());
5040 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5041
John McCalldd4a3b02009-09-16 22:47:08 +00005042 // Try to convert the decl specifier to a type. This works for
5043 // friend templates because ActOnTag never produces a ClassTemplateDecl
5044 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005045 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005046 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5047 if (TheDeclarator.isInvalidType())
5048 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005049
John McCalldd4a3b02009-09-16 22:47:08 +00005050 // This is definitely an error in C++98. It's probably meant to
5051 // be forbidden in C++0x, too, but the specification is just
5052 // poorly written.
5053 //
5054 // The problem is with declarations like the following:
5055 // template <T> friend A<T>::foo;
5056 // where deciding whether a class C is a friend or not now hinges
5057 // on whether there exists an instantiation of A that causes
5058 // 'foo' to equal C. There are restrictions on class-heads
5059 // (which we declare (by fiat) elaborated friend declarations to
5060 // be) that makes this tractable.
5061 //
5062 // FIXME: handle "template <> friend class A<T>;", which
5063 // is possibly well-formed? Who even knows?
5064 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5065 Diag(Loc, diag::err_tagless_friend_type_template)
5066 << DS.getSourceRange();
5067 return DeclPtrTy();
5068 }
5069
John McCall02cace72009-08-28 07:59:38 +00005070 // C++ [class.friend]p2:
5071 // An elaborated-type-specifier shall be used in a friend declaration
5072 // for a class.*
5073 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005074 // This is one of the rare places in Clang where it's legitimate to
5075 // ask about the "spelling" of the type.
5076 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5077 // If we evaluated the type to a record type, suggest putting
5078 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005079 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005080 RecordDecl *RD = RT->getDecl();
5081
5082 std::string InsertionText = std::string(" ") + RD->getKindName();
5083
John McCalle3af0232009-10-07 23:34:25 +00005084 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5085 << (unsigned) RD->getTagKind()
5086 << T
5087 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005088 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5089 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005090 return DeclPtrTy();
5091 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005092 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5093 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005094 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005095 }
5096 }
5097
John McCalle3af0232009-10-07 23:34:25 +00005098 // Enum types cannot be friends.
5099 if (T->getAs<EnumType>()) {
5100 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5101 << SourceRange(DS.getFriendSpecLoc());
5102 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005103 }
John McCall02cace72009-08-28 07:59:38 +00005104
John McCall02cace72009-08-28 07:59:38 +00005105 // C++98 [class.friend]p1: A friend of a class is a function
5106 // or class that is not a member of the class . . .
5107 // But that's a silly restriction which nobody implements for
5108 // inner classes, and C++0x removes it anyway, so we only report
5109 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00005110 if (!getLangOptions().CPlusPlus0x)
5111 if (const RecordType *RT = T->getAs<RecordType>())
5112 if (RT->getDecl()->getDeclContext() == CurContext)
5113 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00005114
John McCalldd4a3b02009-09-16 22:47:08 +00005115 Decl *D;
5116 if (TempParams.size())
5117 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5118 TempParams.size(),
5119 (TemplateParameterList**) TempParams.release(),
5120 T.getTypePtr(),
5121 DS.getFriendSpecLoc());
5122 else
5123 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5124 DS.getFriendSpecLoc());
5125 D->setAccess(AS_public);
5126 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005127
John McCalldd4a3b02009-09-16 22:47:08 +00005128 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005129}
5130
John McCallbbbcdd92009-09-11 21:02:39 +00005131Sema::DeclPtrTy
5132Sema::ActOnFriendFunctionDecl(Scope *S,
5133 Declarator &D,
5134 bool IsDefinition,
5135 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005136 const DeclSpec &DS = D.getDeclSpec();
5137
5138 assert(DS.isFriendSpecified());
5139 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5140
5141 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005142 TypeSourceInfo *TInfo = 0;
5143 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005144
5145 // C++ [class.friend]p1
5146 // A friend of a class is a function or class....
5147 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005148 // It *doesn't* see through dependent types, which is correct
5149 // according to [temp.arg.type]p3:
5150 // If a declaration acquires a function type through a
5151 // type dependent on a template-parameter and this causes
5152 // a declaration that does not use the syntactic form of a
5153 // function declarator to have a function type, the program
5154 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005155 if (!T->isFunctionType()) {
5156 Diag(Loc, diag::err_unexpected_friend);
5157
5158 // It might be worthwhile to try to recover by creating an
5159 // appropriate declaration.
5160 return DeclPtrTy();
5161 }
5162
5163 // C++ [namespace.memdef]p3
5164 // - If a friend declaration in a non-local class first declares a
5165 // class or function, the friend class or function is a member
5166 // of the innermost enclosing namespace.
5167 // - The name of the friend is not found by simple name lookup
5168 // until a matching declaration is provided in that namespace
5169 // scope (either before or after the class declaration granting
5170 // friendship).
5171 // - If a friend function is called, its name may be found by the
5172 // name lookup that considers functions from namespaces and
5173 // classes associated with the types of the function arguments.
5174 // - When looking for a prior declaration of a class or a function
5175 // declared as a friend, scopes outside the innermost enclosing
5176 // namespace scope are not considered.
5177
John McCall02cace72009-08-28 07:59:38 +00005178 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5179 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005180 assert(Name);
5181
John McCall67d1a672009-08-06 02:15:43 +00005182 // The context we found the declaration in, or in which we should
5183 // create the declaration.
5184 DeclContext *DC;
5185
5186 // FIXME: handle local classes
5187
5188 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005189 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5190 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005191 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005192 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005193 DC = computeDeclContext(ScopeQual);
5194
5195 // FIXME: handle dependent contexts
5196 if (!DC) return DeclPtrTy();
5197
John McCall68263142009-11-18 22:49:29 +00005198 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005199
5200 // If searching in that context implicitly found a declaration in
5201 // a different context, treat it like it wasn't found at all.
5202 // TODO: better diagnostics for this case. Suggesting the right
5203 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005204 // FIXME: getRepresentativeDecl() is not right here at all
5205 if (Previous.empty() ||
5206 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005207 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005208 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5209 return DeclPtrTy();
5210 }
5211
5212 // C++ [class.friend]p1: A friend of a class is a function or
5213 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005214 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005215 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5216
John McCall67d1a672009-08-06 02:15:43 +00005217 // Otherwise walk out to the nearest namespace scope looking for matches.
5218 } else {
5219 // TODO: handle local class contexts.
5220
5221 DC = CurContext;
5222 while (true) {
5223 // Skip class contexts. If someone can cite chapter and verse
5224 // for this behavior, that would be nice --- it's what GCC and
5225 // EDG do, and it seems like a reasonable intent, but the spec
5226 // really only says that checks for unqualified existing
5227 // declarations should stop at the nearest enclosing namespace,
5228 // not that they should only consider the nearest enclosing
5229 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005230 while (DC->isRecord())
5231 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005232
John McCall68263142009-11-18 22:49:29 +00005233 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005234
5235 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005236 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005237 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005238
John McCall67d1a672009-08-06 02:15:43 +00005239 if (DC->isFileContext()) break;
5240 DC = DC->getParent();
5241 }
5242
5243 // C++ [class.friend]p1: A friend of a class is a function or
5244 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005245 // C++0x changes this for both friend types and functions.
5246 // Most C++ 98 compilers do seem to give an error here, so
5247 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005248 if (!Previous.empty() && DC->Equals(CurContext)
5249 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005250 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5251 }
5252
Douglas Gregor182ddf02009-09-28 00:08:27 +00005253 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005254 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005255 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5256 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5257 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005258 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005259 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5260 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005261 return DeclPtrTy();
5262 }
John McCall67d1a672009-08-06 02:15:43 +00005263 }
5264
Douglas Gregor182ddf02009-09-28 00:08:27 +00005265 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005266 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005267 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005268 IsDefinition,
5269 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005270 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005271
Douglas Gregor182ddf02009-09-28 00:08:27 +00005272 assert(ND->getDeclContext() == DC);
5273 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005274
John McCallab88d972009-08-31 22:39:49 +00005275 // Add the function declaration to the appropriate lookup tables,
5276 // adjusting the redeclarations list as necessary. We don't
5277 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005278 //
John McCallab88d972009-08-31 22:39:49 +00005279 // Also update the scope-based lookup if the target context's
5280 // lookup context is in lexical scope.
5281 if (!CurContext->isDependentContext()) {
5282 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005283 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005284 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005285 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005286 }
John McCall02cace72009-08-28 07:59:38 +00005287
5288 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005289 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005290 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005291 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005292 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005293
Douglas Gregor182ddf02009-09-28 00:08:27 +00005294 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005295}
5296
Chris Lattnerb28317a2009-03-28 19:18:32 +00005297void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005298 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Chris Lattnerb28317a2009-03-28 19:18:32 +00005300 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005301 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5302 if (!Fn) {
5303 Diag(DelLoc, diag::err_deleted_non_function);
5304 return;
5305 }
5306 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5307 Diag(DelLoc, diag::err_deleted_decl_not_first);
5308 Diag(Prev->getLocation(), diag::note_previous_declaration);
5309 // If the declaration wasn't the first, we delete the function anyway for
5310 // recovery.
5311 }
5312 Fn->setDeleted();
5313}
Sebastian Redl13e88542009-04-27 21:33:24 +00005314
5315static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5316 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5317 ++CI) {
5318 Stmt *SubStmt = *CI;
5319 if (!SubStmt)
5320 continue;
5321 if (isa<ReturnStmt>(SubStmt))
5322 Self.Diag(SubStmt->getSourceRange().getBegin(),
5323 diag::err_return_in_constructor_handler);
5324 if (!isa<Expr>(SubStmt))
5325 SearchForReturnInStmt(Self, SubStmt);
5326 }
5327}
5328
5329void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5330 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5331 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5332 SearchForReturnInStmt(*this, Handler);
5333 }
5334}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005335
Mike Stump1eb44332009-09-09 15:08:12 +00005336bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005337 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005338 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5339 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005340
5341 QualType CNewTy = Context.getCanonicalType(NewTy);
5342 QualType COldTy = Context.getCanonicalType(OldTy);
5343
Mike Stump1eb44332009-09-09 15:08:12 +00005344 if (CNewTy == COldTy &&
Douglas Gregora4923eb2009-11-16 21:35:15 +00005345 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005346 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005347
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005348 // Check if the return types are covariant
5349 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005351 /// Both types must be pointers or references to classes.
5352 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
5353 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
5354 NewClassTy = NewPT->getPointeeType();
5355 OldClassTy = OldPT->getPointeeType();
5356 }
5357 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
5358 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
5359 NewClassTy = NewRT->getPointeeType();
5360 OldClassTy = OldRT->getPointeeType();
5361 }
5362 }
Mike Stump1eb44332009-09-09 15:08:12 +00005363
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005364 // The return types aren't either both pointers or references to a class type.
5365 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005366 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005367 diag::err_different_return_type_for_overriding_virtual_function)
5368 << New->getDeclName() << NewTy << OldTy;
5369 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005371 return true;
5372 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005373
Douglas Gregora4923eb2009-11-16 21:35:15 +00005374 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005375 // Check if the new class derives from the old class.
5376 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5377 Diag(New->getLocation(),
5378 diag::err_covariant_return_not_derived)
5379 << New->getDeclName() << NewTy << OldTy;
5380 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5381 return true;
5382 }
Mike Stump1eb44332009-09-09 15:08:12 +00005383
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005384 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005385 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005386 diag::err_covariant_return_inaccessible_base,
5387 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5388 // FIXME: Should this point to the return type?
5389 New->getLocation(), SourceRange(), New->getDeclName())) {
5390 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5391 return true;
5392 }
5393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005395 // The qualifiers of the return types must be the same.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005396 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005397 Diag(New->getLocation(),
5398 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005399 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005400 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5401 return true;
5402 };
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005404
5405 // The new class type must have the same or less qualifiers as the old type.
5406 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5407 Diag(New->getLocation(),
5408 diag::err_covariant_return_type_class_type_more_qualified)
5409 << New->getDeclName() << NewTy << OldTy;
5410 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5411 return true;
5412 };
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005414 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005415}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005416
Sean Huntbbd37c62009-11-21 08:43:09 +00005417bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5418 const CXXMethodDecl *Old)
5419{
5420 if (Old->hasAttr<FinalAttr>()) {
5421 Diag(New->getLocation(), diag::err_final_function_overridden)
5422 << New->getDeclName();
5423 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5424 return true;
5425 }
5426
5427 return false;
5428}
5429
Douglas Gregor4ba31362009-12-01 17:24:26 +00005430/// \brief Mark the given method pure.
5431///
5432/// \param Method the method to be marked pure.
5433///
5434/// \param InitRange the source range that covers the "0" initializer.
5435bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5436 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5437 Method->setPure();
5438
5439 // A class is abstract if at least one function is pure virtual.
5440 Method->getParent()->setAbstract(true);
5441 return false;
5442 }
5443
5444 if (!Method->isInvalidDecl())
5445 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5446 << Method->getDeclName() << InitRange;
5447 return true;
5448}
5449
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005450/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5451/// initializer for the declaration 'Dcl'.
5452/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5453/// static data member of class X, names should be looked up in the scope of
5454/// class X.
5455void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005456 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005458 Decl *D = Dcl.getAs<Decl>();
5459 // If there is no declaration, there was an error parsing it.
5460 if (D == 0)
5461 return;
5462
5463 // Check whether it is a declaration with a nested name specifier like
5464 // int foo::bar;
5465 if (!D->isOutOfLine())
5466 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005467
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005468 // C++ [basic.lookup.unqual]p13
5469 //
5470 // A name used in the definition of a static data member of class X
5471 // (after the qualified-id of the static member) is looked up as if the name
5472 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00005473
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005474 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00005475 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005476}
5477
5478/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5479/// initializer for the declaration 'Dcl'.
5480void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005481 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005482
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005483 Decl *D = Dcl.getAs<Decl>();
5484 // If there is no declaration, there was an error parsing it.
5485 if (D == 0)
5486 return;
5487
5488 // Check whether it is a declaration with a nested name specifier like
5489 // int foo::bar;
5490 if (!D->isOutOfLine())
5491 return;
5492
5493 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00005494 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005495}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005496
5497/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5498/// C++ if/switch/while/for statement.
5499/// e.g: "if (int x = f()) {...}"
5500Action::DeclResult
5501Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5502 // C++ 6.4p2:
5503 // The declarator shall not specify a function or an array.
5504 // The type-specifier-seq shall not contain typedef and shall not declare a
5505 // new class or enumeration.
5506 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5507 "Parser allowed 'typedef' as storage class of condition decl.");
5508
John McCalla93c9342009-12-07 02:54:59 +00005509 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005510 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005511 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005512
5513 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5514 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5515 // would be created and CXXConditionDeclExpr wants a VarDecl.
5516 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5517 << D.getSourceRange();
5518 return DeclResult();
5519 } else if (OwnedTag && OwnedTag->isDefinition()) {
5520 // The type-specifier-seq shall not declare a new class or enumeration.
5521 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5522 }
5523
5524 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5525 if (!Dcl)
5526 return DeclResult();
5527
5528 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5529 VD->setDeclaredInCondition(true);
5530 return Dcl;
5531}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005532
Anders Carlssond6a637f2009-12-07 08:24:59 +00005533void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5534 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005535 // Ignore dependent types.
5536 if (MD->isDependentContext())
5537 return;
5538
5539 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005540
5541 // Ignore classes without a vtable.
5542 if (!RD->isDynamicClass())
5543 return;
5544
Anders Carlssond6a637f2009-12-07 08:24:59 +00005545 if (!MD->isOutOfLine()) {
5546 // The only inline functions we care about are constructors. We also defer
5547 // marking the virtual members as referenced until we've reached the end
5548 // of the translation unit. We do this because we need to know the key
5549 // function of the class in order to determine the key function.
5550 if (isa<CXXConstructorDecl>(MD))
5551 ClassesWithUnmarkedVirtualMembers.insert(std::make_pair(RD, Loc));
5552 return;
5553 }
5554
Anders Carlssonf53df232009-12-07 04:35:11 +00005555 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005556
5557 if (!KeyFunction) {
5558 // This record does not have a key function, so we assume that the vtable
5559 // will be emitted when it's used by the constructor.
5560 if (!isa<CXXConstructorDecl>(MD))
5561 return;
5562 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5563 // We don't have the right key function.
5564 return;
5565 }
5566
Anders Carlssond6a637f2009-12-07 08:24:59 +00005567 // Mark the members as referenced.
5568 MarkVirtualMembersReferenced(Loc, RD);
5569 ClassesWithUnmarkedVirtualMembers.erase(RD);
5570}
5571
5572bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5573 if (ClassesWithUnmarkedVirtualMembers.empty())
5574 return false;
5575
5576 for (std::map<CXXRecordDecl *, SourceLocation>::iterator i =
5577 ClassesWithUnmarkedVirtualMembers.begin(),
5578 e = ClassesWithUnmarkedVirtualMembers.end(); i != e; ++i) {
5579 CXXRecordDecl *RD = i->first;
5580
5581 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5582 if (KeyFunction) {
5583 // We know that the class has a key function. If the key function was
5584 // declared in this translation unit, then it the class decl would not
5585 // have been in the ClassesWithUnmarkedVirtualMembers map.
5586 continue;
5587 }
5588
5589 SourceLocation Loc = i->second;
5590 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005591 }
5592
Anders Carlssond6a637f2009-12-07 08:24:59 +00005593 ClassesWithUnmarkedVirtualMembers.clear();
5594 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005595}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005596
5597void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5598 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5599 e = RD->method_end(); i != e; ++i) {
5600 CXXMethodDecl *MD = *i;
5601
5602 // C++ [basic.def.odr]p2:
5603 // [...] A virtual member function is used if it is not pure. [...]
5604 if (MD->isVirtual() && !MD->isPure())
5605 MarkDeclarationReferenced(Loc, MD);
5606 }
5607}
5608