blob: 58b5633afad7f417216f05a760f957cfb9e55959 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonf98849e2009-12-02 17:15:43 +000018#include "clang/AST/RecordLayout.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000021#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000022#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000024#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000026#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000027#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000029#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000030#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000031
32using namespace clang;
33
Chris Lattner58258242008-04-10 02:22:51 +000034//===----------------------------------------------------------------------===//
35// CheckDefaultArgumentVisitor
36//===----------------------------------------------------------------------===//
37
Chris Lattnerb0d38442008-04-12 23:52:44 +000038namespace {
39 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
40 /// the default argument of a parameter to determine whether it
41 /// contains any ill-formed subexpressions. For example, this will
42 /// diagnose the use of local variables or parameters within the
43 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000044 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000045 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000046 Expr *DefaultArg;
47 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000048
Chris Lattnerb0d38442008-04-12 23:52:44 +000049 public:
Mike Stump11289f42009-09-09 15:08:12 +000050 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000052
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 bool VisitExpr(Expr *Node);
54 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000055 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 };
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 /// VisitExpr - Visit all of the children of this expression.
59 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
60 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000061 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000062 E = Node->child_end(); I != E; ++I)
63 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000065 }
66
Chris Lattnerb0d38442008-04-12 23:52:44 +000067 /// VisitDeclRefExpr - Visit a reference to a declaration, to
68 /// determine whether this declaration can be used in the default
69 /// argument expression.
70 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
73 // C++ [dcl.fct.default]p9
74 // Default arguments are evaluated each time the function is
75 // called. The order of evaluation of function arguments is
76 // unspecified. Consequently, parameters of a function shall not
77 // be used in default argument expressions, even if they are not
78 // evaluated. Parameters of a function declared before a default
79 // argument expression are in scope and can hide namespace and
80 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000081 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000082 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000083 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000084 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 // C++ [dcl.fct.default]p7
86 // Local variables shall not be used in default argument
87 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000088 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000089 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000090 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000091 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000092 }
Chris Lattner58258242008-04-10 02:22:51 +000093
Douglas Gregor8e12c382008-11-04 13:41:56 +000094 return false;
95 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000096
Douglas Gregor97a9c812008-11-04 14:32:21 +000097 /// VisitCXXThisExpr - Visit a C++ "this" expression.
98 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
99 // C++ [dcl.fct.default]p8:
100 // The keyword this shall not be used in a default argument of a
101 // member function.
102 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_this)
104 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106}
107
Anders Carlssonc80a1272009-08-25 02:29:20 +0000108bool
109Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000110 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000111 QualType ParamType = Param->getType();
112
Anders Carlsson114056f2009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssonc80a1272009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlssonc80a1272009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000127 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000128 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000129 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000130
131 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000132
Anders Carlssonc80a1272009-08-25 02:29:20 +0000133 // Okay: add the default argument to the parameter
134 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000137
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000138 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139}
140
Chris Lattner58258242008-04-10 02:22:51 +0000141/// ActOnParamDefaultArgument - Check whether the default argument
142/// provided for a function parameter is well-formed. If so, attach it
143/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000144void
Mike Stump11289f42009-09-09 15:08:12 +0000145Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000146 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000147 if (!param || !defarg.get())
148 return;
Mike Stump11289f42009-09-09 15:08:12 +0000149
Chris Lattner83f095c2009-03-28 19:18:32 +0000150 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000151 UnparsedDefaultArgLocs.erase(Param);
152
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000153 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000154 QualType ParamType = Param->getType();
155
156 // Default arguments are only permitted in C++
157 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000158 Diag(EqualLoc, diag::err_param_default_argument)
159 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000160 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000161 return;
162 }
163
Anders Carlssonf1c26952009-08-25 01:02:06 +0000164 // Check that the default argument is well-formed
165 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
166 if (DefaultArgChecker.Visit(DefaultArg.get())) {
167 Param->setInvalidDecl();
168 return;
169 }
Mike Stump11289f42009-09-09 15:08:12 +0000170
Anders Carlssonc80a1272009-08-25 02:29:20 +0000171 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000172}
173
Douglas Gregor58354032008-12-24 00:01:03 +0000174/// ActOnParamUnparsedDefaultArgument - We've seen a default
175/// argument for a function parameter, but we can't parse it yet
176/// because we're inside a class definition. Note that this default
177/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000178void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000179 SourceLocation EqualLoc,
180 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000181 if (!param)
182 return;
Mike Stump11289f42009-09-09 15:08:12 +0000183
Chris Lattner83f095c2009-03-28 19:18:32 +0000184 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000185 if (Param)
186 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000187
Anders Carlsson84613c42009-06-12 16:51:40 +0000188 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000189}
190
Douglas Gregor4d87df52008-12-16 21:30:33 +0000191/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
192/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000193void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000194 if (!param)
195 return;
Mike Stump11289f42009-09-09 15:08:12 +0000196
Anders Carlsson84613c42009-06-12 16:51:40 +0000197 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000198
Anders Carlsson84613c42009-06-12 16:51:40 +0000199 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000200
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000202}
203
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000204/// CheckExtraCXXDefaultArguments - Check for any extra default
205/// arguments in the declarator, which is not a function declaration
206/// or definition and therefore is not permitted to have default
207/// arguments. This routine should be invoked for every declarator
208/// that is not a function declaration or definition.
209void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
210 // C++ [dcl.fct.default]p3
211 // A default argument expression shall be specified only in the
212 // parameter-declaration-clause of a function declaration or in a
213 // template-parameter (14.1). It shall not be specified for a
214 // parameter pack. If it is specified in a
215 // parameter-declaration-clause, it shall not occur within a
216 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000217 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000218 DeclaratorChunk &chunk = D.getTypeObject(i);
219 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000220 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
221 ParmVarDecl *Param =
222 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000223 if (Param->hasUnparsedDefaultArg()) {
224 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000225 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
226 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
227 delete Toks;
228 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000229 } else if (Param->getDefaultArg()) {
230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << Param->getDefaultArg()->getSourceRange();
232 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000233 }
234 }
235 }
236 }
237}
238
Chris Lattner199abbc2008-04-08 05:04:30 +0000239// MergeCXXFunctionDecl - Merge two declarations of the same C++
240// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000241// type. Subroutine of MergeFunctionDecl. Returns true if there was an
242// error, false otherwise.
243bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
244 bool Invalid = false;
245
Chris Lattner199abbc2008-04-08 05:04:30 +0000246 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000247 // For non-template functions, default arguments can be added in
248 // later declarations of a function in the same
249 // scope. Declarations in different scopes have completely
250 // distinct sets of default arguments. That is, declarations in
251 // inner scopes do not acquire default arguments from
252 // declarations in outer scopes, and vice versa. In a given
253 // function declaration, all parameters subsequent to a
254 // parameter with a default argument shall have default
255 // arguments supplied in this or previous declarations. A
256 // default argument shall not be redefined by a later
257 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000258 //
259 // C++ [dcl.fct.default]p6:
260 // Except for member functions of class templates, the default arguments
261 // in a member function definition that appears outside of the class
262 // definition are added to the set of default arguments provided by the
263 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000264 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
265 ParmVarDecl *OldParam = Old->getParamDecl(p);
266 ParmVarDecl *NewParam = New->getParamDecl(p);
267
Douglas Gregorc732aba2009-09-11 18:44:32 +0000268 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000269 // FIXME: If the parameter doesn't have an identifier then the location
270 // points to the '=' which means that the fixit hint won't remove any
271 // extra spaces between the type and the '='.
272 SourceLocation Begin = NewParam->getLocation();
Anders Carlsson1566eb52009-11-10 03:32:44 +0000273 if (NewParam->getIdentifier())
274 Begin = PP.getLocForEndOfToken(Begin);
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000275
Mike Stump11289f42009-09-09 15:08:12 +0000276 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000277 diag::err_param_default_argument_redefinition)
Anders Carlsson0b8ea552009-11-10 03:24:44 +0000278 << NewParam->getDefaultArgRange()
279 << CodeModificationHint::CreateRemoval(SourceRange(Begin,
280 NewParam->getLocEnd()));
Douglas Gregorc732aba2009-09-11 18:44:32 +0000281
282 // Look for the function declaration where the default argument was
283 // actually written, which may be a declaration prior to Old.
284 for (FunctionDecl *Older = Old->getPreviousDeclaration();
285 Older; Older = Older->getPreviousDeclaration()) {
286 if (!Older->getParamDecl(p)->hasDefaultArg())
287 break;
288
289 OldParam = Older->getParamDecl(p);
290 }
291
292 Diag(OldParam->getLocation(), diag::note_previous_definition)
293 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000294 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000295 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000296 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000297 if (OldParam->hasUninstantiatedDefaultArg())
298 NewParam->setUninstantiatedDefaultArg(
299 OldParam->getUninstantiatedDefaultArg());
300 else
301 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000302 } else if (NewParam->hasDefaultArg()) {
303 if (New->getDescribedFunctionTemplate()) {
304 // Paragraph 4, quoted above, only applies to non-template functions.
305 Diag(NewParam->getLocation(),
306 diag::err_param_default_argument_template_redecl)
307 << NewParam->getDefaultArgRange();
308 Diag(Old->getLocation(), diag::note_template_prev_declaration)
309 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000310 } else if (New->getTemplateSpecializationKind()
311 != TSK_ImplicitInstantiation &&
312 New->getTemplateSpecializationKind() != TSK_Undeclared) {
313 // C++ [temp.expr.spec]p21:
314 // Default function arguments shall not be specified in a declaration
315 // or a definition for one of the following explicit specializations:
316 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000317 // - the explicit specialization of a member function template;
318 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000319 // template where the class template specialization to which the
320 // member function specialization belongs is implicitly
321 // instantiated.
322 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
323 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
324 << New->getDeclName()
325 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000326 } else if (New->getDeclContext()->isDependentContext()) {
327 // C++ [dcl.fct.default]p6 (DR217):
328 // Default arguments for a member function of a class template shall
329 // be specified on the initial declaration of the member function
330 // within the class template.
331 //
332 // Reading the tea leaves a bit in DR217 and its reference to DR205
333 // leads me to the conclusion that one cannot add default function
334 // arguments for an out-of-line definition of a member function of a
335 // dependent type.
336 int WhichKind = 2;
337 if (CXXRecordDecl *Record
338 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
339 if (Record->getDescribedClassTemplate())
340 WhichKind = 0;
341 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
342 WhichKind = 1;
343 else
344 WhichKind = 2;
345 }
346
347 Diag(NewParam->getLocation(),
348 diag::err_param_default_argument_member_template_redecl)
349 << WhichKind
350 << NewParam->getDefaultArgRange();
351 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000352 }
353 }
354
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000355 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000356 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregored5731f2009-11-25 17:50:39 +0000357 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000358 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000359
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000360 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000361}
362
363/// CheckCXXDefaultArguments - Verify that the default arguments for a
364/// function declaration are well-formed according to C++
365/// [dcl.fct.default].
366void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
367 unsigned NumParams = FD->getNumParams();
368 unsigned p;
369
370 // Find first parameter with a default argument
371 for (p = 0; p < NumParams; ++p) {
372 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000373 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000374 break;
375 }
376
377 // C++ [dcl.fct.default]p4:
378 // In a given function declaration, all parameters
379 // subsequent to a parameter with a default argument shall
380 // have default arguments supplied in this or previous
381 // declarations. A default argument shall not be redefined
382 // by a later declaration (not even to the same value).
383 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000384 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000386 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000387 if (Param->isInvalidDecl())
388 /* We already complained about this parameter. */;
389 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000390 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000391 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000392 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000393 else
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000395 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 LastMissingDefaultArg = p;
398 }
399 }
400
401 if (LastMissingDefaultArg > 0) {
402 // Some default arguments were missing. Clear out all of the
403 // default arguments up to (and including) the last missing
404 // default argument, so that we leave the function parameters
405 // in a semantically valid state.
406 for (p = 0; p <= LastMissingDefaultArg; ++p) {
407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000408 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000409 if (!Param->hasUnparsedDefaultArg())
410 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000411 Param->setDefaultArg(0);
412 }
413 }
414 }
415}
Douglas Gregor556877c2008-04-13 21:30:24 +0000416
Douglas Gregor61956c42008-10-31 09:07:45 +0000417/// isCurrentClassName - Determine whether the identifier II is the
418/// name of the class type currently being defined. In the case of
419/// nested classes, this will only return true if II is the name of
420/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000421bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
422 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000423 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000424 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000425 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000426 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
427 } else
428 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
429
430 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000431 return &II == CurDecl->getIdentifier();
432 else
433 return false;
434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000437///
438/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
439/// and returns NULL otherwise.
440CXXBaseSpecifier *
441Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
442 SourceRange SpecifierRange,
443 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000444 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000445 SourceLocation BaseLoc) {
446 // C++ [class.union]p1:
447 // A union shall not have base classes.
448 if (Class->isUnion()) {
449 Diag(Class->getLocation(), diag::err_base_clause_on_union)
450 << SpecifierRange;
451 return 0;
452 }
453
454 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000455 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000456 Class->getTagKind() == RecordDecl::TK_class,
457 Access, BaseType);
458
459 // Base specifiers must be record types.
460 if (!BaseType->isRecordType()) {
461 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
462 return 0;
463 }
464
465 // C++ [class.union]p1:
466 // A union shall not be used as a base class.
467 if (BaseType->isUnionType()) {
468 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.derived]p2:
473 // The class-name in a base-specifier shall not be an incompletely
474 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000475 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000476 PDiag(diag::err_incomplete_base_class)
477 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000478 return 0;
479
Eli Friedmanc96d4962009-08-15 21:55:26 +0000480 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000481 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000482 assert(BaseDecl && "Record type has no declaration");
483 BaseDecl = BaseDecl->getDefinition(Context);
484 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000485 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
486 assert(CXXBaseDecl && "Base type is not a C++ type");
487 if (!CXXBaseDecl->isEmpty())
488 Class->setEmpty(false);
489 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 Class->setPolymorphic(true);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000491 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
492 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
493 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000494 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
495 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 return 0;
497 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000498
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000499 SetClassDeclAttributesFromBase(Class, cast<CXXRecordDecl>(BaseDecl), Virtual);
500
501 // Create the base specifier.
502 // FIXME: Allocate via ASTContext?
503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
504 Class->getTagKind() == RecordDecl::TK_class,
505 Access, BaseType);
506}
507
508void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
509 const CXXRecordDecl *BaseClass,
510 bool BaseIsVirtual) {
511
Douglas Gregor463421d2009-03-03 04:44:36 +0000512 // C++ [dcl.init.aggr]p1:
513 // An aggregate is [...] a class with [...] no base classes [...].
514 Class->setAggregate(false);
515 Class->setPOD(false);
516
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000517 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000518 // C++ [class.ctor]p5:
519 // A constructor is trivial if its class has no virtual base classes.
520 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000521
522 // C++ [class.copy]p6:
523 // A copy constructor is trivial if its class has no virtual base classes.
524 Class->setHasTrivialCopyConstructor(false);
525
526 // C++ [class.copy]p11:
527 // A copy assignment operator is trivial if its class has no virtual
528 // base classes.
529 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000530
531 // C++0x [meta.unary.prop] is_empty:
532 // T is a class type, but not a union type, with ... no virtual base
533 // classes
534 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000535 } else {
536 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000537 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000538 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000540 Class->setHasTrivialConstructor(false);
541
542 // C++ [class.copy]p6:
543 // A copy constructor is trivial if all the direct base classes of its
544 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000545 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000546 Class->setHasTrivialCopyConstructor(false);
547
548 // C++ [class.copy]p11:
549 // A copy assignment operator is trivial if all the direct base classes
550 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000551 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000552 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000553 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000554
555 // C++ [class.ctor]p3:
556 // A destructor is trivial if all the direct base classes of its class
557 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000558 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000559 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000560}
561
Douglas Gregor556877c2008-04-13 21:30:24 +0000562/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
563/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000564/// example:
565/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000566/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000567Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000568Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000569 bool Virtual, AccessSpecifier Access,
570 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000571 if (!classdecl)
572 return true;
573
Douglas Gregorc40290e2009-03-09 23:48:35 +0000574 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000575 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000576 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
578 Virtual, Access,
579 BaseType, BaseLoc))
580 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000581
Douglas Gregor463421d2009-03-03 04:44:36 +0000582 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000583}
Douglas Gregor556877c2008-04-13 21:30:24 +0000584
Douglas Gregor463421d2009-03-03 04:44:36 +0000585/// \brief Performs the actual work of attaching the given base class
586/// specifiers to a C++ class.
587bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
588 unsigned NumBases) {
589 if (NumBases == 0)
590 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000591
592 // Used to keep track of which base types we have already seen, so
593 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000594 // that the key is always the unqualified canonical type of the base
595 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000596 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
597
598 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000599 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000600 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000601 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000602 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000604 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000605
Douglas Gregor29a92472008-10-22 17:49:05 +0000606 if (KnownBaseTypes[NewBaseType]) {
607 // C++ [class.mi]p3:
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000610 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000611 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000612 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000613 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000617 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000618
619 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000620 } else {
621 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 KnownBaseTypes[NewBaseType] = Bases[idx];
623 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000624 }
625 }
626
627 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000628 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000629
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000634
635 return Invalid;
636}
637
638/// ActOnBaseSpecifiers - Attach the given base specifiers to the
639/// class, after checking whether there are any duplicate base
640/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000641void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000642 unsigned NumBases) {
643 if (!ClassDecl || !Bases || !NumBases)
644 return;
645
646 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000647 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000649}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000650
Douglas Gregor36d1b142009-10-06 17:59:45 +0000651/// \brief Determine whether the type \p Derived is a C++ class that is
652/// derived from the type \p Base.
653bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
654 if (!getLangOptions().CPlusPlus)
655 return false;
656
657 const RecordType *DerivedRT = Derived->getAs<RecordType>();
658 if (!DerivedRT)
659 return false;
660
661 const RecordType *BaseRT = Base->getAs<RecordType>();
662 if (!BaseRT)
663 return false;
664
665 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
666 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
667 return DerivedRD->isDerivedFrom(BaseRD);
668}
669
670/// \brief Determine whether the type \p Derived is a C++ class that is
671/// derived from the type \p Base.
672bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
673 if (!getLangOptions().CPlusPlus)
674 return false;
675
676 const RecordType *DerivedRT = Derived->getAs<RecordType>();
677 if (!DerivedRT)
678 return false;
679
680 const RecordType *BaseRT = Base->getAs<RecordType>();
681 if (!BaseRT)
682 return false;
683
684 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
685 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
686 return DerivedRD->isDerivedFrom(BaseRD, Paths);
687}
688
689/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
690/// conversion (where Derived and Base are class types) is
691/// well-formed, meaning that the conversion is unambiguous (and
692/// that all of the base classes are accessible). Returns true
693/// and emits a diagnostic if the code is ill-formed, returns false
694/// otherwise. Loc is the location where this routine should point to
695/// if there is an error, and Range is the source range to highlight
696/// if there is an error.
697bool
698Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
699 unsigned InaccessibleBaseID,
700 unsigned AmbigiousBaseConvID,
701 SourceLocation Loc, SourceRange Range,
702 DeclarationName Name) {
703 // First, determine whether the path from Derived to Base is
704 // ambiguous. This is slightly more expensive than checking whether
705 // the Derived to Base conversion exists, because here we need to
706 // explore multiple paths to determine if there is an ambiguity.
707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
708 /*DetectVirtual=*/false);
709 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
710 assert(DerivationOkay &&
711 "Can only be used with a derived-to-base conversion");
712 (void)DerivationOkay;
713
714 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000715 if (InaccessibleBaseID == 0)
716 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000717 // Check that the base class can be accessed.
718 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
719 Name);
720 }
721
722 // We know that the derived-to-base conversion is ambiguous, and
723 // we're going to produce a diagnostic. Perform the derived-to-base
724 // search just one more time to compute all of the possible paths so
725 // that we can print them out. This is more expensive than any of
726 // the previous derived-to-base checks we've done, but at this point
727 // performance isn't as much of an issue.
728 Paths.clear();
729 Paths.setRecordingPaths(true);
730 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
731 assert(StillOkay && "Can only be used with a derived-to-base conversion");
732 (void)StillOkay;
733
734 // Build up a textual representation of the ambiguous paths, e.g.,
735 // D -> B -> A, that will be used to illustrate the ambiguous
736 // conversions in the diagnostic. We only print one of the paths
737 // to each base class subobject.
738 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
739
740 Diag(Loc, AmbigiousBaseConvID)
741 << Derived << Base << PathDisplayStr << Range << Name;
742 return true;
743}
744
745bool
746Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000747 SourceLocation Loc, SourceRange Range,
748 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000749 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000750 IgnoreAccess ? 0 :
751 diag::err_conv_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000752 diag::err_ambiguous_derived_to_base_conv,
753 Loc, Range, DeclarationName());
754}
755
756
757/// @brief Builds a string representing ambiguous paths from a
758/// specific derived class to different subobjects of the same base
759/// class.
760///
761/// This function builds a string that can be used in error messages
762/// to show the different paths that one can take through the
763/// inheritance hierarchy to go from the derived class to different
764/// subobjects of a base class. The result looks something like this:
765/// @code
766/// struct D -> struct B -> struct A
767/// struct D -> struct C -> struct A
768/// @endcode
769std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
770 std::string PathDisplayStr;
771 std::set<unsigned> DisplayedPaths;
772 for (CXXBasePaths::paths_iterator Path = Paths.begin();
773 Path != Paths.end(); ++Path) {
774 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
775 // We haven't displayed a path to this particular base
776 // class subobject yet.
777 PathDisplayStr += "\n ";
778 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
779 for (CXXBasePath::const_iterator Element = Path->begin();
780 Element != Path->end(); ++Element)
781 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
782 }
783 }
784
785 return PathDisplayStr;
786}
787
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000788//===----------------------------------------------------------------------===//
789// C++ class member Handling
790//===----------------------------------------------------------------------===//
791
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000792/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
793/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
794/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000795/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000796Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000797Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000798 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000799 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
800 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000801 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000802 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000803 Expr *BitWidth = static_cast<Expr*>(BW);
804 Expr *Init = static_cast<Expr*>(InitExpr);
805 SourceLocation Loc = D.getIdentifierLoc();
806
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000807 bool isFunc = D.isFunctionDeclarator();
808
John McCall07e91c02009-08-06 02:15:43 +0000809 assert(!DS.isFriendSpecified());
810
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000811 // C++ 9.2p6: A member shall not be declared to have automatic storage
812 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000813 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
814 // data members and cannot be applied to names declared const or static,
815 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000816 switch (DS.getStorageClassSpec()) {
817 case DeclSpec::SCS_unspecified:
818 case DeclSpec::SCS_typedef:
819 case DeclSpec::SCS_static:
820 // FALL THROUGH.
821 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000822 case DeclSpec::SCS_mutable:
823 if (isFunc) {
824 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000825 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000826 else
Chris Lattner3b054132008-11-19 05:08:23 +0000827 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000828
Sebastian Redl8071edb2008-11-17 23:24:37 +0000829 // FIXME: It would be nicer if the keyword was ignored only for this
830 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000831 D.getMutableDeclSpec().ClearStorageClassSpecs();
832 } else {
833 QualType T = GetTypeForDeclarator(D, S);
834 diag::kind err = static_cast<diag::kind>(0);
835 if (T->isReferenceType())
836 err = diag::err_mutable_reference;
837 else if (T.isConstQualified())
838 err = diag::err_mutable_const;
839 if (err != 0) {
840 if (DS.getStorageClassSpecLoc().isValid())
841 Diag(DS.getStorageClassSpecLoc(), err);
842 else
843 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000844 // FIXME: It would be nicer if the keyword was ignored only for this
845 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000846 D.getMutableDeclSpec().ClearStorageClassSpecs();
847 }
848 }
849 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000850 default:
851 if (DS.getStorageClassSpecLoc().isValid())
852 Diag(DS.getStorageClassSpecLoc(),
853 diag::err_storageclass_invalid_for_member);
854 else
855 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
856 D.getMutableDeclSpec().ClearStorageClassSpecs();
857 }
858
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000859 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000860 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000861 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000862 // Check also for this case:
863 //
864 // typedef int f();
865 // f a;
866 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000867 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000868 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000869 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000870
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000871 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
872 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000873 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000874
875 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000876 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000877 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000878 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
879 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000880 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000881 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000882 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000883 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000884 if (!Member) {
885 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000886 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000887 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000888
889 // Non-instance-fields can't have a bitfield.
890 if (BitWidth) {
891 if (Member->isInvalidDecl()) {
892 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000893 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000894 // C++ 9.6p3: A bit-field shall not be a static member.
895 // "static member 'A' cannot be a bit-field"
896 Diag(Loc, diag::err_static_not_bitfield)
897 << Name << BitWidth->getSourceRange();
898 } else if (isa<TypedefDecl>(Member)) {
899 // "typedef member 'x' cannot be a bit-field"
900 Diag(Loc, diag::err_typedef_not_bitfield)
901 << Name << BitWidth->getSourceRange();
902 } else {
903 // A function typedef ("typedef int f(); f a;").
904 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
905 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000906 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000907 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000908 }
Mike Stump11289f42009-09-09 15:08:12 +0000909
Chris Lattnerd26760a2009-03-05 23:01:03 +0000910 DeleteExpr(BitWidth);
911 BitWidth = 0;
912 Member->setInvalidDecl();
913 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000914
915 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000916
Douglas Gregor3447e762009-08-20 22:52:58 +0000917 // If we have declared a member function template, set the access of the
918 // templated declaration as well.
919 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
920 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000921 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000922
Douglas Gregor92751d42008-11-17 22:58:34 +0000923 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000924
Douglas Gregor0c880302009-03-11 23:00:04 +0000925 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000926 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000927 if (Deleted) // FIXME: Source location is not very good.
928 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000929
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000930 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000931 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000932 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000933 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000934 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935}
936
Douglas Gregore8381c02008-11-05 04:29:56 +0000937/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000938Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000939Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000940 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000941 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000942 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000943 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000944 SourceLocation IdLoc,
945 SourceLocation LParenLoc,
946 ExprTy **Args, unsigned NumArgs,
947 SourceLocation *CommaLocs,
948 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000949 if (!ConstructorD)
950 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000952 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000953
954 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000955 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000956 if (!Constructor) {
957 // The user wrote a constructor initializer on a function that is
958 // not a C++ constructor. Ignore the error for now, because we may
959 // have more member initializers coming; we'll diagnose it just
960 // once in ActOnMemInitializers.
961 return true;
962 }
963
964 CXXRecordDecl *ClassDecl = Constructor->getParent();
965
966 // C++ [class.base.init]p2:
967 // Names in a mem-initializer-id are looked up in the scope of the
968 // constructor’s class and, if not found in that scope, are looked
969 // up in the scope containing the constructor’s
970 // definition. [Note: if the constructor’s class contains a member
971 // with the same name as a direct or virtual base class of the
972 // class, a mem-initializer-id naming the member or base class and
973 // composed of a single identifier refers to the class member. A
974 // mem-initializer-id for the hidden base class may be specified
975 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000976 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000977 // Look for a member, first.
978 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000979 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000980 = ClassDecl->lookup(MemberOrBase);
981 if (Result.first != Result.second)
982 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000983
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000984 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000985
Eli Friedman8e1433b2009-07-29 19:44:27 +0000986 if (Member)
987 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000988 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000989 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000990 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +0000991 QualType BaseType;
992
993 DeclaratorInfo *DInfo = 0;
994 if (TemplateTypeTy)
995 BaseType = GetTypeFromParser(TemplateTypeTy, &DInfo);
996 else
997 BaseType = QualType::getFromOpaquePtr(getTypeName(*MemberOrBase, IdLoc,
998 S, &SS));
999 if (BaseType.isNull())
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001000 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1001 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001002
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001003 if (!DInfo)
1004 DInfo = Context.getTrivialDeclaratorInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001005
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001006 return BuildBaseInitializer(BaseType, DInfo, (Expr **)Args, NumArgs,
1007 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001008}
1009
John McCalle22a04a2009-11-04 23:02:40 +00001010/// Checks an initializer expression for use of uninitialized fields, such as
1011/// containing the field that is being initialized. Returns true if there is an
1012/// uninitialized field was used an updates the SourceLocation parameter; false
1013/// otherwise.
1014static bool InitExprContainsUninitializedFields(const Stmt* S,
1015 const FieldDecl* LhsField,
1016 SourceLocation* L) {
1017 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1018 if (ME) {
1019 const NamedDecl* RhsField = ME->getMemberDecl();
1020 if (RhsField == LhsField) {
1021 // Initializing a field with itself. Throw a warning.
1022 // But wait; there are exceptions!
1023 // Exception #1: The field may not belong to this record.
1024 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1025 const Expr* base = ME->getBase();
1026 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1027 // Even though the field matches, it does not belong to this record.
1028 return false;
1029 }
1030 // None of the exceptions triggered; return true to indicate an
1031 // uninitialized field was used.
1032 *L = ME->getMemberLoc();
1033 return true;
1034 }
1035 }
1036 bool found = false;
1037 for (Stmt::const_child_iterator it = S->child_begin();
1038 it != S->child_end() && found == false;
1039 ++it) {
1040 if (isa<CallExpr>(S)) {
1041 // Do not descend into function calls or constructors, as the use
1042 // of an uninitialized field may be valid. One would have to inspect
1043 // the contents of the function/ctor to determine if it is safe or not.
1044 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1045 // may be safe, depending on what the function/ctor does.
1046 continue;
1047 }
1048 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1049 }
1050 return found;
1051}
1052
Eli Friedman8e1433b2009-07-29 19:44:27 +00001053Sema::MemInitResult
1054Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1055 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001056 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001057 SourceLocation RParenLoc) {
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001058 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1059 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1060 ExprTemporaries.clear();
1061
John McCalle22a04a2009-11-04 23:02:40 +00001062 // Diagnose value-uses of fields to initialize themselves, e.g.
1063 // foo(foo)
1064 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001065 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001066 for (unsigned i = 0; i < NumArgs; ++i) {
1067 SourceLocation L;
1068 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1069 // FIXME: Return true in the case when other fields are used before being
1070 // uninitialized. For example, let this field be the i'th field. When
1071 // initializing the i'th field, throw a warning if any of the >= i'th
1072 // fields are used, as they are not yet initialized.
1073 // Right now we are only handling the case where the i'th field uses
1074 // itself in its initializer.
1075 Diag(L, diag::warn_field_is_uninit);
1076 }
1077 }
1078
Eli Friedman8e1433b2009-07-29 19:44:27 +00001079 bool HasDependentArg = false;
1080 for (unsigned i = 0; i < NumArgs; i++)
1081 HasDependentArg |= Args[i]->isTypeDependent();
1082
1083 CXXConstructorDecl *C = 0;
1084 QualType FieldType = Member->getType();
1085 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1086 FieldType = Array->getElementType();
1087 if (FieldType->isDependentType()) {
1088 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001089 } else if (FieldType->isRecordType()) {
1090 // Member is a record (struct/union/class), so pass the initializer
1091 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001092 if (!HasDependentArg) {
1093 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1094
1095 C = PerformInitializationByConstructor(FieldType,
1096 MultiExprArg(*this,
1097 (void**)Args,
1098 NumArgs),
1099 IdLoc,
1100 SourceRange(IdLoc, RParenLoc),
1101 Member->getDeclName(), IK_Direct,
1102 ConstructorArgs);
1103
1104 if (C) {
1105 // Take over the constructor arguments as our own.
1106 NumArgs = ConstructorArgs.size();
1107 Args = (Expr **)ConstructorArgs.take();
1108 }
1109 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001110 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001111 // The member type is not a record type (or an array of record
1112 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001113 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001114 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1115 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001116 Expr *NewExp;
1117 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001118 if (FieldType->isReferenceType()) {
1119 Diag(IdLoc, diag::err_null_intialized_reference_member)
1120 << Member->getDeclName();
1121 return Diag(Member->getLocation(), diag::note_declared_at);
1122 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001123 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1124 NumArgs = 1;
1125 }
1126 else
1127 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001128 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1129 return true;
1130 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001131 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001132
1133 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1134 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1135 ExprTemporaries.clear();
1136
Eli Friedman8e1433b2009-07-29 19:44:27 +00001137 // FIXME: Perform direct initialization of the member.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001138 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1139 C, LParenLoc, (Expr **)Args,
1140 NumArgs, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001141}
1142
1143Sema::MemInitResult
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001144Sema::BuildBaseInitializer(QualType BaseType, DeclaratorInfo *BaseDInfo,
1145 Expr **Args, unsigned NumArgs,
1146 SourceLocation LParenLoc, SourceLocation RParenLoc,
1147 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001148 bool HasDependentArg = false;
1149 for (unsigned i = 0; i < NumArgs; i++)
1150 HasDependentArg |= Args[i]->isTypeDependent();
1151
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001152 SourceLocation BaseLoc = BaseDInfo->getTypeLoc().getSourceRange().getBegin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001153 if (!BaseType->isDependentType()) {
1154 if (!BaseType->isRecordType())
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001155 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1156 << BaseType << BaseDInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001157
1158 // C++ [class.base.init]p2:
1159 // [...] Unless the mem-initializer-id names a nonstatic data
1160 // member of the constructor’s class or a direct or virtual base
1161 // of that class, the mem-initializer is ill-formed. A
1162 // mem-initializer-list can initialize a base class using any
1163 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001164
Eli Friedman8e1433b2009-07-29 19:44:27 +00001165 // First, check for a direct base class.
1166 const CXXBaseSpecifier *DirectBaseSpec = 0;
1167 for (CXXRecordDecl::base_class_const_iterator Base =
1168 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001169 if (Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001170 // We found a direct base of this type. That's what we're
1171 // initializing.
1172 DirectBaseSpec = &*Base;
1173 break;
1174 }
1175 }
Mike Stump11289f42009-09-09 15:08:12 +00001176
Eli Friedman8e1433b2009-07-29 19:44:27 +00001177 // Check for a virtual base class.
1178 // FIXME: We might be able to short-circuit this if we know in advance that
1179 // there are no virtual bases.
1180 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1181 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1182 // We haven't found a base yet; search the class hierarchy for a
1183 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001184 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1185 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001186 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001187 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001188 Path != Paths.end(); ++Path) {
1189 if (Path->back().Base->isVirtual()) {
1190 VirtualBaseSpec = Path->back().Base;
1191 break;
1192 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001193 }
1194 }
1195 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001196
1197 // C++ [base.class.init]p2:
1198 // If a mem-initializer-id is ambiguous because it designates both
1199 // a direct non-virtual base class and an inherited virtual base
1200 // class, the mem-initializer is ill-formed.
1201 if (DirectBaseSpec && VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001202 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1203 << BaseType << BaseDInfo->getTypeLoc().getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001204 // C++ [base.class.init]p2:
1205 // Unless the mem-initializer-id names a nonstatic data membeer of the
1206 // constructor's class ot a direst or virtual base of that class, the
1207 // mem-initializer is ill-formed.
1208 if (!DirectBaseSpec && !VirtualBaseSpec)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001209 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1210 << BaseType << ClassDecl->getNameAsCString()
1211 << BaseDInfo->getTypeLoc().getSourceRange();
Douglas Gregore8381c02008-11-05 04:29:56 +00001212 }
1213
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001214 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001215 if (!BaseType->isDependentType() && !HasDependentArg) {
1216 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001217 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001218 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1219
1220 C = PerformInitializationByConstructor(BaseType,
1221 MultiExprArg(*this,
1222 (void**)Args, NumArgs),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001223 BaseLoc,
1224 SourceRange(BaseLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001225 Name, IK_Direct,
1226 ConstructorArgs);
1227 if (C) {
1228 // Take over the constructor arguments as our own.
1229 NumArgs = ConstructorArgs.size();
1230 Args = (Expr **)ConstructorArgs.take();
1231 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001232 }
1233
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001234 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1235 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1236 ExprTemporaries.clear();
1237
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001238 return new (Context) CXXBaseOrMemberInitializer(Context, BaseDInfo, C,
1239 LParenLoc, (Expr **)Args,
1240 NumArgs, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001241}
1242
Eli Friedman9cf6b592009-11-09 19:20:36 +00001243bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001244Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001245 CXXBaseOrMemberInitializer **Initializers,
1246 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001247 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001248 // We need to build the initializer AST according to order of construction
1249 // and not what user specified in the Initializers list.
1250 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1251 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1252 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1253 bool HasDependentBaseInit = false;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001254 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001255
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001256 for (unsigned i = 0; i < NumInitializers; i++) {
1257 CXXBaseOrMemberInitializer *Member = Initializers[i];
1258 if (Member->isBaseInitializer()) {
1259 if (Member->getBaseClass()->isDependentType())
1260 HasDependentBaseInit = true;
1261 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1262 } else {
1263 AllBaseFields[Member->getMember()] = Member;
1264 }
1265 }
Mike Stump11289f42009-09-09 15:08:12 +00001266
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001267 if (HasDependentBaseInit) {
1268 // FIXME. This does not preserve the ordering of the initializers.
1269 // Try (with -Wreorder)
1270 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001271 // template<class X> struct B : A<X> {
1272 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001273 // int x1;
1274 // };
1275 // B<int> x;
1276 // On seeing one dependent type, we should essentially exit this routine
1277 // while preserving user-declared initializer list. When this routine is
1278 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001279 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001280
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001281 // If we have a dependent base initialization, we can't determine the
1282 // association between initializers and bases; just dump the known
1283 // initializers into the list, and don't try to deal with other bases.
1284 for (unsigned i = 0; i < NumInitializers; i++) {
1285 CXXBaseOrMemberInitializer *Member = Initializers[i];
1286 if (Member->isBaseInitializer())
1287 AllToInit.push_back(Member);
1288 }
1289 } else {
1290 // Push virtual bases before others.
1291 for (CXXRecordDecl::base_class_iterator VBase =
1292 ClassDecl->vbases_begin(),
1293 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1294 if (VBase->getType()->isDependentType())
1295 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001296 if (CXXBaseOrMemberInitializer *Value
1297 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001298 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001299 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001300 else {
Mike Stump11289f42009-09-09 15:08:12 +00001301 CXXRecordDecl *VBaseDecl =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001302 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001303 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001304 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001305 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001306 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1307 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1308 << 0 << VBase->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001309 Diag(VBaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001310 << Context.getTagDeclType(VBaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001311 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001312 continue;
1313 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001314
Anders Carlsson561f7932009-10-29 15:46:07 +00001315 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1316 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1317 Constructor->getLocation(), CtorArgs))
1318 continue;
1319
1320 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1321
Anders Carlssonbdd12402009-11-13 20:11:49 +00001322 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001323 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1324 // necessary.
1325 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001326 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001327 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001328 new (Context) CXXBaseOrMemberInitializer(Context,
1329 Context.getTrivialDeclaratorInfo(VBase->getType(),
1330 SourceLocation()),
1331 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001332 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001333 CtorArgs.takeAs<Expr>(),
1334 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001335 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001336 AllToInit.push_back(Member);
1337 }
1338 }
Mike Stump11289f42009-09-09 15:08:12 +00001339
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001340 for (CXXRecordDecl::base_class_iterator Base =
1341 ClassDecl->bases_begin(),
1342 E = ClassDecl->bases_end(); Base != E; ++Base) {
1343 // Virtuals are in the virtual base list and already constructed.
1344 if (Base->isVirtual())
1345 continue;
1346 // Skip dependent types.
1347 if (Base->getType()->isDependentType())
1348 continue;
Douglas Gregor598caee2009-11-15 08:51:10 +00001349 if (CXXBaseOrMemberInitializer *Value
1350 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001351 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001352 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001353 else {
Mike Stump11289f42009-09-09 15:08:12 +00001354 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001355 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001356 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001357 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001358 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001359 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1360 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1361 << 0 << Base->getType();
Douglas Gregore7488b92009-12-01 16:58:18 +00001362 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001363 << Context.getTagDeclType(BaseDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001364 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001365 continue;
1366 }
1367
1368 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1369 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1370 Constructor->getLocation(), CtorArgs))
1371 continue;
1372
1373 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001374
Anders Carlssonbdd12402009-11-13 20:11:49 +00001375 // FIXME: CXXBaseOrMemberInitializer should only contain a single
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001376 // subexpression so we can wrap it in a CXXExprWithTemporaries if
1377 // necessary.
1378 // FIXME: Is there any better source-location information we can give?
Anders Carlssonbdd12402009-11-13 20:11:49 +00001379 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001380 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001381 new (Context) CXXBaseOrMemberInitializer(Context,
1382 Context.getTrivialDeclaratorInfo(Base->getType(),
1383 SourceLocation()),
1384 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001385 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001386 CtorArgs.takeAs<Expr>(),
1387 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001388 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001389 AllToInit.push_back(Member);
1390 }
1391 }
1392 }
Mike Stump11289f42009-09-09 15:08:12 +00001393
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001394 // non-static data members.
1395 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1396 E = ClassDecl->field_end(); Field != E; ++Field) {
1397 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001399 Field->getType()->getAs<RecordType>()) {
1400 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001401 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001402 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001403 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1404 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1405 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1406 // set to the anonymous union data member used in the initializer
1407 // list.
1408 Value->setMember(*Field);
1409 Value->setAnonUnionMember(*FA);
1410 AllToInit.push_back(Value);
1411 break;
1412 }
1413 }
1414 }
1415 continue;
1416 }
1417 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1418 AllToInit.push_back(Value);
1419 continue;
1420 }
Mike Stump11289f42009-09-09 15:08:12 +00001421
Eli Friedmand7686ef2009-11-09 01:05:47 +00001422 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001423 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001424
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001425 QualType FT = Context.getBaseElementType((*Field)->getType());
1426 if (const RecordType* RT = FT->getAs<RecordType>()) {
1427 CXXConstructorDecl *Ctor =
1428 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001429 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001430 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1431 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1432 << 1 << (*Field)->getDeclName();
1433 Diag(Field->getLocation(), diag::note_field_decl);
Douglas Gregore7488b92009-12-01 16:58:18 +00001434 Diag(RT->getDecl()->getLocation(), diag::note_previous_decl)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001435 << Context.getTagDeclType(RT->getDecl());
Eli Friedman9cf6b592009-11-09 19:20:36 +00001436 HadError = true;
Anders Carlsson561f7932009-10-29 15:46:07 +00001437 continue;
1438 }
Eli Friedman22683fe2009-11-16 23:07:59 +00001439
1440 if (FT.isConstQualified() && Ctor->isTrivial()) {
1441 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1442 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1443 << 1 << (*Field)->getDeclName();
1444 Diag((*Field)->getLocation(), diag::note_declared_at);
1445 HadError = true;
1446 }
1447
1448 // Don't create initializers for trivial constructors, since they don't
1449 // actually need to be run.
1450 if (Ctor->isTrivial())
1451 continue;
1452
Anders Carlsson561f7932009-10-29 15:46:07 +00001453 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1454 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1455 Constructor->getLocation(), CtorArgs))
1456 continue;
1457
Anders Carlssonbdd12402009-11-13 20:11:49 +00001458 // FIXME: CXXBaseOrMemberInitializer should only contain a single
1459 // subexpression so we can wrap it in a CXXExprWithTemporaries if necessary.
1460 ExprTemporaries.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001461 CXXBaseOrMemberInitializer *Member =
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001462 new (Context) CXXBaseOrMemberInitializer(Context,
1463 *Field, SourceLocation(),
1464 Ctor,
Anders Carlsson561f7932009-10-29 15:46:07 +00001465 SourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001466 CtorArgs.takeAs<Expr>(),
1467 CtorArgs.size(),
Anders Carlsson561f7932009-10-29 15:46:07 +00001468 SourceLocation());
1469
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001470 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001471 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001472 }
1473 else if (FT->isReferenceType()) {
1474 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001475 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1476 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001477 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001478 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001479 }
1480 else if (FT.isConstQualified()) {
1481 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001482 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1483 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001484 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman9cf6b592009-11-09 19:20:36 +00001485 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001486 }
1487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001489 NumInitializers = AllToInit.size();
1490 if (NumInitializers > 0) {
1491 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1492 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1493 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001494
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001495 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1496 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1497 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1498 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001499
1500 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001501}
1502
Eli Friedman952c15d2009-07-21 19:28:10 +00001503static void *GetKeyForTopLevelField(FieldDecl *Field) {
1504 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001506 if (RT->getDecl()->isAnonymousStructOrUnion())
1507 return static_cast<void *>(RT->getDecl());
1508 }
1509 return static_cast<void *>(Field);
1510}
1511
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001512static void *GetKeyForBase(QualType BaseType) {
1513 if (const RecordType *RT = BaseType->getAs<RecordType>())
1514 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001515
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001516 assert(0 && "Unexpected base type!");
1517 return 0;
1518}
1519
Mike Stump11289f42009-09-09 15:08:12 +00001520static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001521 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001522 // For fields injected into the class via declaration of an anonymous union,
1523 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001524 if (Member->isMemberInitializer()) {
1525 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001526
Eli Friedmand7686ef2009-11-09 01:05:47 +00001527 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001528 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001529 // in AnonUnionMember field.
1530 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1531 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001532 if (Field->getDeclContext()->isRecord()) {
1533 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1534 if (RD->isAnonymousStructOrUnion())
1535 return static_cast<void *>(RD);
1536 }
1537 return static_cast<void *>(Field);
1538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001540 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001541}
1542
John McCallc90f6d72009-11-04 23:13:52 +00001543/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001544void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001545 SourceLocation ColonLoc,
1546 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001547 if (!ConstructorDecl)
1548 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001549
1550 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001551
1552 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001553 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001554
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001555 if (!Constructor) {
1556 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1557 return;
1558 }
Mike Stump11289f42009-09-09 15:08:12 +00001559
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001560 if (!Constructor->isDependentContext()) {
1561 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1562 bool err = false;
1563 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001564 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001565 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1566 void *KeyToMember = GetKeyForMember(Member);
1567 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1568 if (!PrevMember) {
1569 PrevMember = Member;
1570 continue;
1571 }
1572 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001573 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001574 diag::error_multiple_mem_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001575 << Field->getNameAsString()
1576 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001577 else {
1578 Type *BaseClass = Member->getBaseClass();
1579 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001580 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001581 diag::error_multiple_base_initialization)
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001582 << QualType(BaseClass, 0)
1583 << Member->getSourceRange();
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001584 }
1585 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1586 << 0;
1587 err = true;
1588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001590 if (err)
1591 return;
1592 }
Mike Stump11289f42009-09-09 15:08:12 +00001593
Eli Friedmand7686ef2009-11-09 01:05:47 +00001594 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001595 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001596 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001597
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001598 if (Constructor->isDependentContext())
1599 return;
Mike Stump11289f42009-09-09 15:08:12 +00001600
1601 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001602 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001603 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001604 Diagnostic::Ignored)
1605 return;
Mike Stump11289f42009-09-09 15:08:12 +00001606
Anders Carlssone0eebb32009-08-27 05:45:01 +00001607 // Also issue warning if order of ctor-initializer list does not match order
1608 // of 1) base class declarations and 2) order of non-static data members.
1609 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001610
Anders Carlssone0eebb32009-08-27 05:45:01 +00001611 CXXRecordDecl *ClassDecl
1612 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1613 // Push virtual bases before others.
1614 for (CXXRecordDecl::base_class_iterator VBase =
1615 ClassDecl->vbases_begin(),
1616 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001617 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001618
Anders Carlssone0eebb32009-08-27 05:45:01 +00001619 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1620 E = ClassDecl->bases_end(); Base != E; ++Base) {
1621 // Virtuals are alread in the virtual base list and are constructed
1622 // first.
1623 if (Base->isVirtual())
1624 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001625 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
Anders Carlssone0eebb32009-08-27 05:45:01 +00001628 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1629 E = ClassDecl->field_end(); Field != E; ++Field)
1630 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlssone0eebb32009-08-27 05:45:01 +00001632 int Last = AllBaseOrMembers.size();
1633 int curIndex = 0;
1634 CXXBaseOrMemberInitializer *PrevMember = 0;
1635 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001636 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001637 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1638 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001639
Anders Carlssone0eebb32009-08-27 05:45:01 +00001640 for (; curIndex < Last; curIndex++)
1641 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1642 break;
1643 if (curIndex == Last) {
1644 assert(PrevMember && "Member not in member list?!");
1645 // Initializer as specified in ctor-initializer list is out of order.
1646 // Issue a warning diagnostic.
1647 if (PrevMember->isBaseInitializer()) {
1648 // Diagnostics is for an initialized base class.
1649 Type *BaseClass = PrevMember->getBaseClass();
1650 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001651 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001652 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001653 } else {
1654 FieldDecl *Field = PrevMember->getMember();
1655 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001656 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001657 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001658 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001659 // Also the note!
1660 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001661 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001662 diag::note_fieldorbase_initialized_here) << 0
1663 << Field->getNameAsString();
1664 else {
1665 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001666 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001667 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001668 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001669 }
1670 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001671 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001672 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001673 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001674 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001675 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001676}
1677
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001678void
Anders Carlssondee9a302009-11-17 04:44:12 +00001679Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1680 // Ignore dependent destructors.
1681 if (Destructor->isDependentContext())
1682 return;
1683
1684 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00001685
Anders Carlssondee9a302009-11-17 04:44:12 +00001686 // Non-static data members.
1687 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1688 E = ClassDecl->field_end(); I != E; ++I) {
1689 FieldDecl *Field = *I;
1690
1691 QualType FieldType = Context.getBaseElementType(Field->getType());
1692
1693 const RecordType* RT = FieldType->getAs<RecordType>();
1694 if (!RT)
1695 continue;
1696
1697 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1698 if (FieldClassDecl->hasTrivialDestructor())
1699 continue;
1700
1701 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1702 MarkDeclarationReferenced(Destructor->getLocation(),
1703 const_cast<CXXDestructorDecl*>(Dtor));
1704 }
1705
1706 // Bases.
1707 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1708 E = ClassDecl->bases_end(); Base != E; ++Base) {
1709 // Ignore virtual bases.
1710 if (Base->isVirtual())
1711 continue;
1712
1713 // Ignore trivial destructors.
1714 CXXRecordDecl *BaseClassDecl
1715 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1716 if (BaseClassDecl->hasTrivialDestructor())
1717 continue;
1718
1719 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1720 MarkDeclarationReferenced(Destructor->getLocation(),
1721 const_cast<CXXDestructorDecl*>(Dtor));
1722 }
1723
1724 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001725 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1726 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlssondee9a302009-11-17 04:44:12 +00001727 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001728 CXXRecordDecl *BaseClassDecl
1729 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1730 if (BaseClassDecl->hasTrivialDestructor())
1731 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00001732
1733 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1734 MarkDeclarationReferenced(Destructor->getLocation(),
1735 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001736 }
1737}
1738
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001739void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001740 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001741 return;
Mike Stump11289f42009-09-09 15:08:12 +00001742
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001743 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001744
1745 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001746 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001747 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001748}
1749
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001750namespace {
1751 /// PureVirtualMethodCollector - traverses a class and its superclasses
1752 /// and determines if it has any pure virtual methods.
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001753 class PureVirtualMethodCollector {
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001754 ASTContext &Context;
1755
Sebastian Redlb7d64912009-03-22 21:28:55 +00001756 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001757 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001758
1759 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001760 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001761
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001762 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001764 public:
Mike Stump11289f42009-09-09 15:08:12 +00001765 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001766 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001767
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001768 MethodList List;
1769 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001770
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001771 // Copy the temporary list to methods, and make sure to ignore any
1772 // null entries.
1773 for (size_t i = 0, e = List.size(); i != e; ++i) {
1774 if (List[i])
1775 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001776 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001779 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001780
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001781 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1782 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001783 };
Mike Stump11289f42009-09-09 15:08:12 +00001784
1785 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001786 MethodList& Methods) {
1787 // First, collect the pure virtual methods for the base classes.
1788 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1789 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001790 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001791 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001792 if (BaseDecl && BaseDecl->isAbstract())
1793 Collect(BaseDecl, Methods);
1794 }
1795 }
Mike Stump11289f42009-09-09 15:08:12 +00001796
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001797 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001798 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001799
Anders Carlsson3c012712009-05-17 00:00:05 +00001800 MethodSetTy OverriddenMethods;
1801 size_t MethodsSize = Methods.size();
1802
Mike Stump11289f42009-09-09 15:08:12 +00001803 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001804 i != e; ++i) {
1805 // Traverse the record, looking for methods.
1806 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001807 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001808 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001809 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Anders Carlsson700179432009-10-18 19:34:08 +00001811 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001812 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1813 E = MD->end_overridden_methods(); I != E; ++I) {
1814 // Keep track of the overridden methods.
1815 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001816 }
1817 }
1818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
1820 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001821 // overridden.
1822 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1823 if (OverriddenMethods.count(Methods[i]))
1824 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001827 }
1828}
Douglas Gregore8381c02008-11-05 04:29:56 +00001829
Anders Carlssoneabf7702009-08-27 00:13:57 +00001830
Mike Stump11289f42009-09-09 15:08:12 +00001831bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001832 unsigned DiagID, AbstractDiagSelID SelID,
1833 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001834 if (SelID == -1)
1835 return RequireNonAbstractType(Loc, T,
1836 PDiag(DiagID), CurrentRD);
1837 else
1838 return RequireNonAbstractType(Loc, T,
1839 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001840}
1841
Anders Carlssoneabf7702009-08-27 00:13:57 +00001842bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1843 const PartialDiagnostic &PD,
1844 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001845 if (!getLangOptions().CPlusPlus)
1846 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001848 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001849 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001850 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001852 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001853 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001854 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001855 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001856
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001857 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001858 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001861 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001862 if (!RT)
1863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001865 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1866 if (!RD)
1867 return false;
1868
Anders Carlssonb57738b2009-03-24 17:23:42 +00001869 if (CurrentRD && CurrentRD != RD)
1870 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001872 if (!RD->isAbstract())
1873 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001874
Anders Carlssoneabf7702009-08-27 00:13:57 +00001875 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001876
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001877 // Check if we've already emitted the list of pure virtual functions for this
1878 // class.
1879 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1880 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001881
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001882 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001883
1884 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001885 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1886 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001887
1888 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001889 MD->getDeclName();
1890 }
1891
1892 if (!PureVirtualClassDiagSet)
1893 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1894 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001895
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001896 return true;
1897}
1898
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001899namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00001900 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001901 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1902 Sema &SemaRef;
1903 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001904
Anders Carlssonb57738b2009-03-24 17:23:42 +00001905 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001906 bool Invalid = false;
1907
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001908 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1909 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001910 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001911
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001912 return Invalid;
1913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssonb57738b2009-03-24 17:23:42 +00001915 public:
1916 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1917 : SemaRef(SemaRef), AbstractClass(ac) {
1918 Visit(SemaRef.Context.getTranslationUnitDecl());
1919 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001920
Anders Carlssonb57738b2009-03-24 17:23:42 +00001921 bool VisitFunctionDecl(const FunctionDecl *FD) {
1922 if (FD->isThisDeclarationADefinition()) {
1923 // No need to do the check if we're in a definition, because it requires
1924 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001925 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001926 return VisitDeclContext(FD);
1927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
Anders Carlssonb57738b2009-03-24 17:23:42 +00001929 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001930 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001931 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001932 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1933 diag::err_abstract_type_in_decl,
1934 Sema::AbstractReturnType,
1935 AbstractClass);
1936
Mike Stump11289f42009-09-09 15:08:12 +00001937 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001938 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001939 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001940 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001941 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001942 VD->getOriginalType(),
1943 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001944 Sema::AbstractParamType,
1945 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001946 }
1947
1948 return Invalid;
1949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Anders Carlssonb57738b2009-03-24 17:23:42 +00001951 bool VisitDecl(const Decl* D) {
1952 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1953 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Anders Carlssonb57738b2009-03-24 17:23:42 +00001955 return false;
1956 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001957 };
1958}
1959
Douglas Gregorc99f1552009-12-03 18:33:45 +00001960/// \brief Perform semantic checks on a class definition that has been
1961/// completing, introducing implicitly-declared members, checking for
1962/// abstract types, etc.
1963void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
1964 if (!Record || Record->isInvalidDecl())
1965 return;
1966
1967 if (!Record->isAbstract()) {
1968 // Collect all the pure virtual methods and see if this is an abstract
1969 // class after all.
1970 PureVirtualMethodCollector Collector(Context, Record);
1971 if (!Collector.empty())
1972 Record->setAbstract(true);
1973 }
1974
1975 if (Record->isAbstract())
1976 (void)AbstractClassUsageDiagnoser(*this, Record);
1977
1978 if (!Record->isDependentType() && !Record->isInvalidDecl())
1979 AddImplicitlyDeclaredMembersToClass(Record);
1980}
1981
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001982void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001983 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001984 SourceLocation LBrac,
1985 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001986 if (!TagDecl)
1987 return;
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001989 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00001990
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001991 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001992 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001993 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001994
Douglas Gregorc99f1552009-12-03 18:33:45 +00001995 CheckCompletedCXXClass(
1996 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001997}
1998
Douglas Gregor05379422008-11-03 17:51:48 +00001999/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2000/// special functions, such as the default constructor, copy
2001/// constructor, or destructor, to the given C++ class (C++
2002/// [special]p1). This routine can only be executed just before the
2003/// definition of the class is complete.
2004void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002005 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002006 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002007
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002008 // FIXME: Implicit declarations have exception specifications, which are
2009 // the union of the specifications of the implicitly called functions.
2010
Douglas Gregor05379422008-11-03 17:51:48 +00002011 if (!ClassDecl->hasUserDeclaredConstructor()) {
2012 // C++ [class.ctor]p5:
2013 // A default constructor for a class X is a constructor of class X
2014 // that can be called without an argument. If there is no
2015 // user-declared constructor for class X, a default constructor is
2016 // implicitly declared. An implicitly-declared default constructor
2017 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002018 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002019 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002020 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002021 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002022 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002023 Context.getFunctionType(Context.VoidTy,
2024 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002025 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002026 /*isExplicit=*/false,
2027 /*isInline=*/true,
2028 /*isImplicitlyDeclared=*/true);
2029 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002030 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002031 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002032 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002033 }
2034
2035 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2036 // C++ [class.copy]p4:
2037 // If the class definition does not explicitly declare a copy
2038 // constructor, one is declared implicitly.
2039
2040 // C++ [class.copy]p5:
2041 // The implicitly-declared copy constructor for a class X will
2042 // have the form
2043 //
2044 // X::X(const X&)
2045 //
2046 // if
2047 bool HasConstCopyConstructor = true;
2048
2049 // -- each direct or virtual base class B of X has a copy
2050 // constructor whose first parameter is of type const B& or
2051 // const volatile B&, and
2052 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2053 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2054 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002056 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002057 = BaseClassDecl->hasConstCopyConstructor(Context);
2058 }
2059
2060 // -- for all the nonstatic data members of X that are of a
2061 // class type M (or array thereof), each such class type
2062 // has a copy constructor whose first parameter is of type
2063 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002064 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2065 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002066 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002067 QualType FieldType = (*Field)->getType();
2068 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2069 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002070 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002071 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002072 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002073 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002074 = FieldClassDecl->hasConstCopyConstructor(Context);
2075 }
2076 }
2077
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002078 // Otherwise, the implicitly declared copy constructor will have
2079 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002080 //
2081 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002082 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002083 if (HasConstCopyConstructor)
2084 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002085 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002086
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002087 // An implicitly-declared copy constructor is an inline public
2088 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002089 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002090 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002091 CXXConstructorDecl *CopyConstructor
2092 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002093 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002094 Context.getFunctionType(Context.VoidTy,
2095 &ArgType, 1,
2096 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002097 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002098 /*isExplicit=*/false,
2099 /*isInline=*/true,
2100 /*isImplicitlyDeclared=*/true);
2101 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002102 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002103 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002104
2105 // Add the parameter to the constructor.
2106 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2107 ClassDecl->getLocation(),
2108 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002109 ArgType, /*DInfo=*/0,
2110 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002111 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002112 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002113 }
2114
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002115 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2116 // Note: The following rules are largely analoguous to the copy
2117 // constructor rules. Note that virtual bases are not taken into account
2118 // for determining the argument type of the operator. Note also that
2119 // operators taking an object instead of a reference are allowed.
2120 //
2121 // C++ [class.copy]p10:
2122 // If the class definition does not explicitly declare a copy
2123 // assignment operator, one is declared implicitly.
2124 // The implicitly-defined copy assignment operator for a class X
2125 // will have the form
2126 //
2127 // X& X::operator=(const X&)
2128 //
2129 // if
2130 bool HasConstCopyAssignment = true;
2131
2132 // -- each direct base class B of X has a copy assignment operator
2133 // whose parameter is of type const B&, const volatile B& or B,
2134 // and
2135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2136 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002137 assert(!Base->getType()->isDependentType() &&
2138 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002139 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002141 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002142 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002143 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002144 }
2145
2146 // -- for all the nonstatic data members of X that are of a class
2147 // type M (or array thereof), each such class type has a copy
2148 // assignment operator whose parameter is of type const M&,
2149 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002150 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2151 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002152 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002153 QualType FieldType = (*Field)->getType();
2154 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2155 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002156 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002157 const CXXRecordDecl *FieldClassDecl
2158 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002159 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002160 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002161 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002162 }
2163 }
2164
2165 // Otherwise, the implicitly declared copy assignment operator will
2166 // have the form
2167 //
2168 // X& X::operator=(X&)
2169 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002170 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002171 if (HasConstCopyAssignment)
2172 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002173 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002174
2175 // An implicitly-declared copy assignment operator is an inline public
2176 // member of its class.
2177 DeclarationName Name =
2178 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2179 CXXMethodDecl *CopyAssignment =
2180 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2181 Context.getFunctionType(RetType, &ArgType, 1,
2182 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002183 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002184 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002185 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002186 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002187 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002188
2189 // Add the parameter to the operator.
2190 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2191 ClassDecl->getLocation(),
2192 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002193 ArgType, /*DInfo=*/0,
2194 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002195 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002196
2197 // Don't call addedAssignmentOperator. There is no way to distinguish an
2198 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002199 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002200 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002201 }
2202
Douglas Gregor1349b452008-12-15 21:24:18 +00002203 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002204 // C++ [class.dtor]p2:
2205 // If a class has no user-declared destructor, a destructor is
2206 // declared implicitly. An implicitly-declared destructor is an
2207 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002208 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002209 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002210 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002211 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002212 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002213 Context.getFunctionType(Context.VoidTy,
2214 0, 0, false, 0),
2215 /*isInline=*/true,
2216 /*isImplicitlyDeclared=*/true);
2217 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002218 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002219 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002220 ClassDecl->addDecl(Destructor);
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002221
2222 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002223 }
Douglas Gregor05379422008-11-03 17:51:48 +00002224}
2225
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002226void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002227 Decl *D = TemplateD.getAs<Decl>();
2228 if (!D)
2229 return;
2230
2231 TemplateParameterList *Params = 0;
2232 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2233 Params = Template->getTemplateParameters();
2234 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2235 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2236 Params = PartialSpec->getTemplateParameters();
2237 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002238 return;
2239
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002240 for (TemplateParameterList::iterator Param = Params->begin(),
2241 ParamEnd = Params->end();
2242 Param != ParamEnd; ++Param) {
2243 NamedDecl *Named = cast<NamedDecl>(*Param);
2244 if (Named->getDeclName()) {
2245 S->AddDecl(DeclPtrTy::make(Named));
2246 IdResolver.AddDecl(Named);
2247 }
2248 }
2249}
2250
Douglas Gregor4d87df52008-12-16 21:30:33 +00002251/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2252/// parsing a top-level (non-nested) C++ class, and we are now
2253/// parsing those parts of the given Method declaration that could
2254/// not be parsed earlier (C++ [class.mem]p2), such as default
2255/// arguments. This action should enter the scope of the given
2256/// Method declaration as if we had just parsed the qualified method
2257/// name. However, it should not bring the parameters into scope;
2258/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002259void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002260 if (!MethodD)
2261 return;
Mike Stump11289f42009-09-09 15:08:12 +00002262
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002263 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002264
Douglas Gregor4d87df52008-12-16 21:30:33 +00002265 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002266 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002267 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002268 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2269 SS.setScopeRep(
2270 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002271 ActOnCXXEnterDeclaratorScope(S, SS);
2272}
2273
2274/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2275/// C++ method declaration. We're (re-)introducing the given
2276/// function parameter into scope for use in parsing later parts of
2277/// the method declaration. For example, we could see an
2278/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002279void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002280 if (!ParamD)
2281 return;
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattner83f095c2009-03-28 19:18:32 +00002283 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002284
2285 // If this parameter has an unparsed default argument, clear it out
2286 // to make way for the parsed default argument.
2287 if (Param->hasUnparsedDefaultArg())
2288 Param->setDefaultArg(0);
2289
Chris Lattner83f095c2009-03-28 19:18:32 +00002290 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002291 if (Param->getDeclName())
2292 IdResolver.AddDecl(Param);
2293}
2294
2295/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2296/// processing the delayed method declaration for Method. The method
2297/// declaration is now considered finished. There may be a separate
2298/// ActOnStartOfFunctionDef action later (not necessarily
2299/// immediately!) for this method, if it was also defined inside the
2300/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002301void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002302 if (!MethodD)
2303 return;
Mike Stump11289f42009-09-09 15:08:12 +00002304
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002305 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002306
Chris Lattner83f095c2009-03-28 19:18:32 +00002307 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002308 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002309 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002310 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2311 SS.setScopeRep(
2312 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002313 ActOnCXXExitDeclaratorScope(S, SS);
2314
2315 // Now that we have our default arguments, check the constructor
2316 // again. It could produce additional diagnostics or affect whether
2317 // the class has implicitly-declared destructors, among other
2318 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002319 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2320 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002321
2322 // Check the default arguments, which we may have added.
2323 if (!Method->isInvalidDecl())
2324 CheckCXXDefaultArguments(Method);
2325}
2326
Douglas Gregor831c93f2008-11-05 20:51:48 +00002327/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002328/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002329/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002330/// emit diagnostics and set the invalid bit to true. In any case, the type
2331/// will be updated to reflect a well-formed type for the constructor and
2332/// returned.
2333QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2334 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002335 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002336
2337 // C++ [class.ctor]p3:
2338 // A constructor shall not be virtual (10.3) or static (9.4). A
2339 // constructor can be invoked for a const, volatile or const
2340 // volatile object. A constructor shall not be declared const,
2341 // volatile, or const volatile (9.3.2).
2342 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002343 if (!D.isInvalidType())
2344 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2345 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2346 << SourceRange(D.getIdentifierLoc());
2347 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002348 }
2349 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002350 if (!D.isInvalidType())
2351 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2352 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2353 << SourceRange(D.getIdentifierLoc());
2354 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002355 SC = FunctionDecl::None;
2356 }
Mike Stump11289f42009-09-09 15:08:12 +00002357
Chris Lattner38378bf2009-04-25 08:28:21 +00002358 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2359 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002360 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002361 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2362 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002363 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002364 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2365 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002366 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002367 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2368 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Douglas Gregor831c93f2008-11-05 20:51:48 +00002371 // Rebuild the function type "R" without any type qualifiers (in
2372 // case any of the errors above fired) and with "void" as the
2373 // return type, since constructors don't have return types. We
2374 // *always* have to do this, because GetTypeForDeclarator will
2375 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002376 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002377 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2378 Proto->getNumArgs(),
2379 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002380}
2381
Douglas Gregor4d87df52008-12-16 21:30:33 +00002382/// CheckConstructor - Checks a fully-formed constructor for
2383/// well-formedness, issuing any diagnostics required. Returns true if
2384/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002385void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002386 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002387 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2388 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002389 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002390
2391 // C++ [class.copy]p3:
2392 // A declaration of a constructor for a class X is ill-formed if
2393 // its first parameter is of type (optionally cv-qualified) X and
2394 // either there are no other parameters or else all other
2395 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002396 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002397 ((Constructor->getNumParams() == 1) ||
2398 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002399 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2400 Constructor->getTemplateSpecializationKind()
2401 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002402 QualType ParamType = Constructor->getParamDecl(0)->getType();
2403 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2404 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002405 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2406 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002407 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002408
2409 // FIXME: Rather that making the constructor invalid, we should endeavor
2410 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002411 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002412 }
2413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
Douglas Gregor4d87df52008-12-16 21:30:33 +00002415 // Notify the class that we've added a constructor.
2416 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002417}
2418
Anders Carlsson26a807d2009-11-30 21:24:50 +00002419/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2420/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002421bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002422 CXXRecordDecl *RD = Destructor->getParent();
2423
2424 if (Destructor->isVirtual()) {
2425 SourceLocation Loc;
2426
2427 if (!Destructor->isImplicit())
2428 Loc = Destructor->getLocation();
2429 else
2430 Loc = RD->getLocation();
2431
2432 // If we have a virtual destructor, look up the deallocation function
2433 FunctionDecl *OperatorDelete = 0;
2434 DeclarationName Name =
2435 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002436 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002437 return true;
2438
2439 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002440 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002441
2442 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002443}
2444
Mike Stump11289f42009-09-09 15:08:12 +00002445static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002446FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2447 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2448 FTI.ArgInfo[0].Param &&
2449 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2450}
2451
Douglas Gregor831c93f2008-11-05 20:51:48 +00002452/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2453/// the well-formednes of the destructor declarator @p D with type @p
2454/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002455/// emit diagnostics and set the declarator to invalid. Even if this happens,
2456/// will be updated to reflect a well-formed type for the destructor and
2457/// returned.
2458QualType Sema::CheckDestructorDeclarator(Declarator &D,
2459 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002460 // C++ [class.dtor]p1:
2461 // [...] A typedef-name that names a class is a class-name
2462 // (7.1.3); however, a typedef-name that names a class shall not
2463 // be used as the identifier in the declarator for a destructor
2464 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002465 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002466 if (isa<TypedefType>(DeclaratorType)) {
2467 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002468 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002469 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002470 }
2471
2472 // C++ [class.dtor]p2:
2473 // A destructor is used to destroy objects of its class type. A
2474 // destructor takes no parameters, and no return type can be
2475 // specified for it (not even void). The address of a destructor
2476 // shall not be taken. A destructor shall not be static. A
2477 // destructor can be invoked for a const, volatile or const
2478 // volatile object. A destructor shall not be declared const,
2479 // volatile or const volatile (9.3.2).
2480 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002481 if (!D.isInvalidType())
2482 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2483 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2484 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002485 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002486 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002487 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002488 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002489 // Destructors don't have return types, but the parser will
2490 // happily parse something like:
2491 //
2492 // class X {
2493 // float ~X();
2494 // };
2495 //
2496 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002497 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2498 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2499 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002500 }
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattner38378bf2009-04-25 08:28:21 +00002502 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2503 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002504 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2506 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002507 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002508 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2509 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002510 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002511 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2512 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002513 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002514 }
2515
2516 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002517 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002518 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2519
2520 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002521 FTI.freeArgs();
2522 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002523 }
2524
Mike Stump11289f42009-09-09 15:08:12 +00002525 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002526 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002527 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002528 D.setInvalidType();
2529 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002530
2531 // Rebuild the function type "R" without any type qualifiers or
2532 // parameters (in case any of the errors above fired) and with
2533 // "void" as the return type, since destructors don't have return
2534 // types. We *always* have to do this, because GetTypeForDeclarator
2535 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002536 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002537}
2538
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002539/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2540/// well-formednes of the conversion function declarator @p D with
2541/// type @p R. If there are any errors in the declarator, this routine
2542/// will emit diagnostics and return true. Otherwise, it will return
2543/// false. Either way, the type @p R will be updated to reflect a
2544/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002545void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002546 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002547 // C++ [class.conv.fct]p1:
2548 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002549 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002550 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002551 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002552 if (!D.isInvalidType())
2553 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2554 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2555 << SourceRange(D.getIdentifierLoc());
2556 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002557 SC = FunctionDecl::None;
2558 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002559 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002560 // Conversion functions don't have return types, but the parser will
2561 // happily parse something like:
2562 //
2563 // class X {
2564 // float operator bool();
2565 // };
2566 //
2567 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002568 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2569 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2570 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002571 }
2572
2573 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002574 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002575 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2576
2577 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002578 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002579 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002580 }
2581
Mike Stump11289f42009-09-09 15:08:12 +00002582 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002583 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002584 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002585 D.setInvalidType();
2586 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002587
2588 // C++ [class.conv.fct]p4:
2589 // The conversion-type-id shall not represent a function type nor
2590 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002591 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002592 if (ConvType->isArrayType()) {
2593 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2594 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002595 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002596 } else if (ConvType->isFunctionType()) {
2597 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2598 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002599 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002600 }
2601
2602 // Rebuild the function type "R" without any parameters (in case any
2603 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002604 // return type.
2605 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002606 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002607
Douglas Gregor5fb53972009-01-14 15:45:31 +00002608 // C++0x explicit conversion operators.
2609 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002610 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002611 diag::warn_explicit_conversion_functions)
2612 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002613}
2614
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002615/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2616/// the declaration of the given C++ conversion function. This routine
2617/// is responsible for recording the conversion function in the C++
2618/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002619Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002620 assert(Conversion && "Expected to receive a conversion function declaration");
2621
Douglas Gregor4287b372008-12-12 08:25:50 +00002622 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002623
2624 // Make sure we aren't redeclaring the conversion function.
2625 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002626
2627 // C++ [class.conv.fct]p1:
2628 // [...] A conversion function is never used to convert a
2629 // (possibly cv-qualified) object to the (possibly cv-qualified)
2630 // same object type (or a reference to it), to a (possibly
2631 // cv-qualified) base class of that type (or a reference to it),
2632 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002633 // FIXME: Suppress this warning if the conversion function ends up being a
2634 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002635 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002636 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002637 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002638 ConvType = ConvTypeRef->getPointeeType();
2639 if (ConvType->isRecordType()) {
2640 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2641 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002642 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002643 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002644 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002645 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002646 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002647 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002648 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002649 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002650 }
2651
Douglas Gregor1dc98262008-12-26 15:00:45 +00002652 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002653 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002654 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002655 = Conversion->getDescribedFunctionTemplate())
2656 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
John McCalld14a8642009-11-21 08:51:07 +00002657 if (ClassDecl->replaceConversion(ExpectedPrevDecl, Conversion))
2658 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002659 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002660 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002661 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002662 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002663 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002664 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002665
Chris Lattner83f095c2009-03-28 19:18:32 +00002666 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002667}
2668
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002669//===----------------------------------------------------------------------===//
2670// Namespace Handling
2671//===----------------------------------------------------------------------===//
2672
2673/// ActOnStartNamespaceDef - This is called at the start of a namespace
2674/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002675Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2676 SourceLocation IdentLoc,
2677 IdentifierInfo *II,
2678 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002679 NamespaceDecl *Namespc =
2680 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2681 Namespc->setLBracLoc(LBrace);
2682
2683 Scope *DeclRegionScope = NamespcScope->getParent();
2684
2685 if (II) {
2686 // C++ [namespace.def]p2:
2687 // The identifier in an original-namespace-definition shall not have been
2688 // previously defined in the declarative region in which the
2689 // original-namespace-definition appears. The identifier in an
2690 // original-namespace-definition is the name of the namespace. Subsequently
2691 // in that declarative region, it is treated as an original-namespace-name.
2692
John McCall9f3059a2009-10-09 21:13:30 +00002693 NamedDecl *PrevDecl
John McCall27b18f82009-11-17 02:14:36 +00002694 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00002695 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00002696
Douglas Gregor91f84212008-12-11 16:49:14 +00002697 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2698 // This is an extended namespace definition.
2699 // Attach this namespace decl to the chain of extended namespace
2700 // definitions.
2701 OrigNS->setNextNamespace(Namespc);
2702 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002703
Mike Stump11289f42009-09-09 15:08:12 +00002704 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002705 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002706 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002707 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002708 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002709 } else if (PrevDecl) {
2710 // This is an invalid name redefinition.
2711 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2712 << Namespc->getDeclName();
2713 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2714 Namespc->setInvalidDecl();
2715 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002716 } else if (II->isStr("std") &&
2717 CurContext->getLookupContext()->isTranslationUnit()) {
2718 // This is the first "real" definition of the namespace "std", so update
2719 // our cache of the "std" namespace to point at this definition.
2720 if (StdNamespace) {
2721 // We had already defined a dummy namespace "std". Link this new
2722 // namespace definition to the dummy namespace "std".
2723 StdNamespace->setNextNamespace(Namespc);
2724 StdNamespace->setLocation(IdentLoc);
2725 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2726 }
2727
2728 // Make our StdNamespace cache point at the first real definition of the
2729 // "std" namespace.
2730 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002731 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002732
2733 PushOnScopeChains(Namespc, DeclRegionScope);
2734 } else {
John McCall4fa53422009-10-01 00:25:31 +00002735 // Anonymous namespaces.
2736
2737 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2738 // behaves as if it were replaced by
2739 // namespace unique { /* empty body */ }
2740 // using namespace unique;
2741 // namespace unique { namespace-body }
2742 // where all occurrences of 'unique' in a translation unit are
2743 // replaced by the same identifier and this identifier differs
2744 // from all other identifiers in the entire program.
2745
2746 // We just create the namespace with an empty name and then add an
2747 // implicit using declaration, just like the standard suggests.
2748 //
2749 // CodeGen enforces the "universally unique" aspect by giving all
2750 // declarations semantically contained within an anonymous
2751 // namespace internal linkage.
2752
2753 assert(Namespc->isAnonymousNamespace());
2754 CurContext->addDecl(Namespc);
2755
2756 UsingDirectiveDecl* UD
2757 = UsingDirectiveDecl::Create(Context, CurContext,
2758 /* 'using' */ LBrace,
2759 /* 'namespace' */ SourceLocation(),
2760 /* qualifier */ SourceRange(),
2761 /* NNS */ NULL,
2762 /* identifier */ SourceLocation(),
2763 Namespc,
2764 /* Ancestor */ CurContext);
2765 UD->setImplicit();
2766 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002767 }
2768
2769 // Although we could have an invalid decl (i.e. the namespace name is a
2770 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002771 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2772 // for the namespace has the declarations that showed up in that particular
2773 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002774 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002775 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002776}
2777
Sebastian Redla6602e92009-11-23 15:34:23 +00002778/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2779/// is a namespace alias, returns the namespace it points to.
2780static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2781 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2782 return AD->getNamespace();
2783 return dyn_cast_or_null<NamespaceDecl>(D);
2784}
2785
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002786/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2787/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002788void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2789 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002790 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2791 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2792 Namespc->setRBracLoc(RBrace);
2793 PopDeclContext();
2794}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002795
Chris Lattner83f095c2009-03-28 19:18:32 +00002796Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2797 SourceLocation UsingLoc,
2798 SourceLocation NamespcLoc,
2799 const CXXScopeSpec &SS,
2800 SourceLocation IdentLoc,
2801 IdentifierInfo *NamespcName,
2802 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002803 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2804 assert(NamespcName && "Invalid NamespcName.");
2805 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002806 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002807
Douglas Gregor889ceb72009-02-03 19:21:40 +00002808 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002809
Douglas Gregor34074322009-01-14 22:20:51 +00002810 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00002811 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2812 LookupParsedName(R, S, &SS);
2813 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00002814 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00002815
John McCall9f3059a2009-10-09 21:13:30 +00002816 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00002817 NamedDecl *Named = R.getFoundDecl();
2818 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2819 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002820 // C++ [namespace.udir]p1:
2821 // A using-directive specifies that the names in the nominated
2822 // namespace can be used in the scope in which the
2823 // using-directive appears after the using-directive. During
2824 // unqualified name lookup (3.4.1), the names appear as if they
2825 // were declared in the nearest enclosing namespace which
2826 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002827 // namespace. [Note: in this context, "contains" means "contains
2828 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002829
2830 // Find enclosing context containing both using-directive and
2831 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00002832 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002833 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2834 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2835 CommonAncestor = CommonAncestor->getParent();
2836
Sebastian Redla6602e92009-11-23 15:34:23 +00002837 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002838 SS.getRange(),
2839 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00002840 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002841 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002842 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002843 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002844 }
2845
Douglas Gregor889ceb72009-02-03 19:21:40 +00002846 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002847 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002848 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002849}
2850
2851void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2852 // If scope has associated entity, then using directive is at namespace
2853 // or translation unit scope. We add UsingDirectiveDecls, into
2854 // it's lookup structure.
2855 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002856 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002857 else
2858 // Otherwise it is block-sope. using-directives will affect lookup
2859 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002860 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002861}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002862
Douglas Gregorfec52632009-06-20 00:51:54 +00002863
2864Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002865 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002866 SourceLocation UsingLoc,
2867 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002868 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002869 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002870 bool IsTypeName,
2871 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002872 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002873
Douglas Gregor220f4272009-11-04 16:30:06 +00002874 switch (Name.getKind()) {
2875 case UnqualifiedId::IK_Identifier:
2876 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00002877 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00002878 case UnqualifiedId::IK_ConversionFunctionId:
2879 break;
2880
2881 case UnqualifiedId::IK_ConstructorName:
2882 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2883 << SS.getRange();
2884 return DeclPtrTy();
2885
2886 case UnqualifiedId::IK_DestructorName:
2887 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2888 << SS.getRange();
2889 return DeclPtrTy();
2890
2891 case UnqualifiedId::IK_TemplateId:
2892 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2893 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2894 return DeclPtrTy();
2895 }
2896
2897 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3f746822009-11-17 05:59:44 +00002898 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002899 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00002900 TargetName, AttrList,
2901 /* IsInstantiation */ false,
2902 IsTypeName, TypenameLoc);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002903 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002904 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002905 UD->setAccess(AS);
2906 }
Mike Stump11289f42009-09-09 15:08:12 +00002907
Anders Carlsson696a3f12009-08-28 05:40:36 +00002908 return DeclPtrTy::make(UD);
2909}
2910
John McCall3f746822009-11-17 05:59:44 +00002911/// Builds a shadow declaration corresponding to a 'using' declaration.
2912static UsingShadowDecl *BuildUsingShadowDecl(Sema &SemaRef, Scope *S,
2913 AccessSpecifier AS,
2914 UsingDecl *UD, NamedDecl *Orig) {
2915 // FIXME: diagnose hiding, collisions
2916
2917 // If we resolved to another shadow declaration, just coalesce them.
2918 if (isa<UsingShadowDecl>(Orig)) {
2919 Orig = cast<UsingShadowDecl>(Orig)->getTargetDecl();
2920 assert(!isa<UsingShadowDecl>(Orig) && "nested shadow declaration");
2921 }
2922
2923 UsingShadowDecl *Shadow
2924 = UsingShadowDecl::Create(SemaRef.Context, SemaRef.CurContext,
2925 UD->getLocation(), UD, Orig);
2926 UD->addShadowDecl(Shadow);
2927
2928 if (S)
2929 SemaRef.PushOnScopeChains(Shadow, S);
2930 else
2931 SemaRef.CurContext->addDecl(Shadow);
2932 Shadow->setAccess(AS);
2933
2934 return Shadow;
2935}
2936
John McCalle61f2ba2009-11-18 02:36:19 +00002937/// Builds a using declaration.
2938///
2939/// \param IsInstantiation - Whether this call arises from an
2940/// instantiation of an unresolved using declaration. We treat
2941/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00002942NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
2943 SourceLocation UsingLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00002944 const CXXScopeSpec &SS,
2945 SourceLocation IdentLoc,
2946 DeclarationName Name,
2947 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00002948 bool IsInstantiation,
2949 bool IsTypeName,
2950 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002951 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2952 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002953
Anders Carlssonf038fc22009-08-28 05:49:21 +00002954 // FIXME: We ignore attributes for now.
2955 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002956
Anders Carlsson59140b32009-08-28 03:16:11 +00002957 if (SS.isEmpty()) {
2958 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002959 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961
2962 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002963 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2964
John McCall84c16cf2009-11-12 03:15:40 +00002965 DeclContext *LookupContext = computeDeclContext(SS);
2966 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00002967 if (IsTypeName) {
2968 return UnresolvedUsingTypenameDecl::Create(Context, CurContext,
2969 UsingLoc, TypenameLoc,
2970 SS.getRange(), NNS,
2971 IdentLoc, Name);
2972 } else {
2973 return UnresolvedUsingValueDecl::Create(Context, CurContext,
2974 UsingLoc, SS.getRange(), NNS,
2975 IdentLoc, Name);
2976 }
Anders Carlssonf038fc22009-08-28 05:49:21 +00002977 }
Mike Stump11289f42009-09-09 15:08:12 +00002978
Anders Carlsson59140b32009-08-28 03:16:11 +00002979 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2980 // C++0x N2914 [namespace.udecl]p3:
2981 // A using-declaration used as a member-declaration shall refer to a member
2982 // of a base class of the class being defined, shall refer to a member of an
2983 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002984 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002985 // a member of a base class of the class being defined.
John McCall3f746822009-11-17 05:59:44 +00002986
John McCall84c16cf2009-11-12 03:15:40 +00002987 CXXRecordDecl *LookupRD = dyn_cast<CXXRecordDecl>(LookupContext);
2988 if (!LookupRD || !RD->isDerivedFrom(LookupRD)) {
Anders Carlsson59140b32009-08-28 03:16:11 +00002989 Diag(SS.getRange().getBegin(),
2990 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2991 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002992 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002993 }
Anders Carlsson59140b32009-08-28 03:16:11 +00002994 } else {
2995 // C++0x N2914 [namespace.udecl]p8:
2996 // A using-declaration for a class member shall be a member-declaration.
John McCall84c16cf2009-11-12 03:15:40 +00002997 if (isa<CXXRecordDecl>(LookupContext)) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002998 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002999 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003000 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003001 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003002 }
3003
John McCall3f746822009-11-17 05:59:44 +00003004 // Look up the target name. Unlike most lookups, we do not want to
3005 // hide tag declarations: tag names are visible through the using
3006 // declaration even if hidden by ordinary names.
John McCall27b18f82009-11-17 02:14:36 +00003007 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003008
3009 // We don't hide tags behind ordinary decls if we're in a
3010 // non-dependent context, but in a dependent context, this is
3011 // important for the stability of two-phase lookup.
3012 if (!IsInstantiation)
3013 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003014
John McCall27b18f82009-11-17 02:14:36 +00003015 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003016
John McCall9f3059a2009-10-09 21:13:30 +00003017 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003018 Diag(IdentLoc, diag::err_no_member)
3019 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003020 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00003021 }
3022
John McCall3f746822009-11-17 05:59:44 +00003023 if (R.isAmbiguous())
3024 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003025
John McCalle61f2ba2009-11-18 02:36:19 +00003026 if (IsTypeName) {
3027 // If we asked for a typename and got a non-type decl, error out.
3028 if (R.getResultKind() != LookupResult::Found
3029 || !isa<TypeDecl>(R.getFoundDecl())) {
3030 Diag(IdentLoc, diag::err_using_typename_non_type);
3031 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3032 Diag((*I)->getUnderlyingDecl()->getLocation(),
3033 diag::note_using_decl_target);
3034 return 0;
3035 }
3036 } else {
3037 // If we asked for a non-typename and we got a type, error out,
3038 // but only if this is an instantiation of an unresolved using
3039 // decl. Otherwise just silently find the type name.
3040 if (IsInstantiation &&
3041 R.getResultKind() == LookupResult::Found &&
3042 isa<TypeDecl>(R.getFoundDecl())) {
3043 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3044 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3045 return 0;
3046 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003047 }
3048
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003049 // C++0x N2914 [namespace.udecl]p6:
3050 // A using-declaration shall not name a namespace.
John McCall3f746822009-11-17 05:59:44 +00003051 if (R.getResultKind() == LookupResult::Found
3052 && isa<NamespaceDecl>(R.getFoundDecl())) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003053 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3054 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003055 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003056 }
Mike Stump11289f42009-09-09 15:08:12 +00003057
John McCall3f746822009-11-17 05:59:44 +00003058 UsingDecl *UD = UsingDecl::Create(Context, CurContext, IdentLoc,
3059 SS.getRange(), UsingLoc, NNS, Name,
3060 IsTypeName);
3061
3062 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3063 BuildUsingShadowDecl(*this, S, AS, UD, *I);
3064
3065 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003066}
3067
Mike Stump11289f42009-09-09 15:08:12 +00003068Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003069 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003070 SourceLocation AliasLoc,
3071 IdentifierInfo *Alias,
3072 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003073 SourceLocation IdentLoc,
3074 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00003075
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003076 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003077 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3078 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003079
Anders Carlssondca83c42009-03-28 06:23:46 +00003080 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003081 if (NamedDecl *PrevDecl
John McCall5cebab12009-11-18 07:57:50 +00003082 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003083 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00003084 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003085 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00003086 if (!R.isAmbiguous() && !R.empty() &&
3087 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00003088 return DeclPtrTy();
3089 }
Mike Stump11289f42009-09-09 15:08:12 +00003090
Anders Carlssondca83c42009-03-28 06:23:46 +00003091 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3092 diag::err_redefinition_different_kind;
3093 Diag(AliasLoc, DiagID) << Alias;
3094 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00003095 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00003096 }
3097
John McCall27b18f82009-11-17 02:14:36 +00003098 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003099 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00003100
John McCall9f3059a2009-10-09 21:13:30 +00003101 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00003102 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00003103 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00003104 }
Mike Stump11289f42009-09-09 15:08:12 +00003105
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003106 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00003107 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3108 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00003109 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00003110 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003111
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003112 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00003113 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00003114}
3115
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003116void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3117 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00003118 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3119 !Constructor->isUsed()) &&
3120 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003121
Eli Friedman9cf6b592009-11-09 19:20:36 +00003122 CXXRecordDecl *ClassDecl
3123 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3124 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00003125
Eli Friedman9cf6b592009-11-09 19:20:36 +00003126 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00003127 Diag(CurrentLocation, diag::note_member_synthesized_at)
3128 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00003129 Constructor->setInvalidDecl();
3130 } else {
3131 Constructor->setUsed();
3132 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00003133
3134 MaybeMarkVirtualImplicitMembersReferenced(CurrentLocation, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00003135}
3136
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003137void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00003138 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003139 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3140 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00003141 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003142 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3143 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00003144 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003145 // implicitly defined, all the implicitly-declared default destructors
3146 // for its base class and its non-static data members shall have been
3147 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3149 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003150 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003151 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003152 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003153 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003154 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3155 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3156 else
Mike Stump11289f42009-09-09 15:08:12 +00003157 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003158 "DefineImplicitDestructor - missing dtor in a base class");
3159 }
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003162 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3163 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003164 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3165 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3166 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003167 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003168 CXXRecordDecl *FieldClassDecl
3169 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3170 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003171 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003172 const_cast<CXXDestructorDecl*>(
3173 FieldClassDecl->getDestructor(Context)))
3174 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3175 else
Mike Stump11289f42009-09-09 15:08:12 +00003176 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003177 "DefineImplicitDestructor - missing dtor in class of a data member");
3178 }
3179 }
3180 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003181
3182 // FIXME: If CheckDestructor fails, we should emit a note about where the
3183 // implicit destructor was needed.
3184 if (CheckDestructor(Destructor)) {
3185 Diag(CurrentLocation, diag::note_member_synthesized_at)
3186 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3187
3188 Destructor->setInvalidDecl();
3189 return;
3190 }
3191
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003192 Destructor->setUsed();
3193}
3194
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003195void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3196 CXXMethodDecl *MethodDecl) {
3197 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3198 MethodDecl->getOverloadedOperator() == OO_Equal &&
3199 !MethodDecl->isUsed()) &&
3200 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003201
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003202 CXXRecordDecl *ClassDecl
3203 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003204
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003205 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003206 // Before the implicitly-declared copy assignment operator for a class is
3207 // implicitly defined, all implicitly-declared copy assignment operators
3208 // for its direct base classes and its nonstatic data members shall have
3209 // been implicitly defined.
3210 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003211 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3212 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003213 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003214 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003215 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003216 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3217 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3218 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003219 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3220 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003221 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3222 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3223 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003224 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003225 CXXRecordDecl *FieldClassDecl
3226 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003227 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003228 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3229 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003230 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003231 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003232 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3233 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003234 Diag(CurrentLocation, diag::note_first_required_here);
3235 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003236 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003237 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003238 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3239 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003240 Diag(CurrentLocation, diag::note_first_required_here);
3241 err = true;
3242 }
3243 }
3244 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003245 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003246}
3247
3248CXXMethodDecl *
3249Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3250 CXXRecordDecl *ClassDecl) {
3251 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3252 QualType RHSType(LHSType);
3253 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003254 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003255 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003256 RHSType = Context.getCVRQualifiedType(RHSType,
3257 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003258 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3259 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003260 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003261 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3262 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003263 SourceLocation()));
3264 Expr *Args[2] = { &*LHS, &*RHS };
3265 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003266 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003267 CandidateSet);
3268 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003269 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003270 ClassDecl->getLocation(), Best) == OR_Success)
3271 return cast<CXXMethodDecl>(Best->Function);
3272 assert(false &&
3273 "getAssignOperatorMethod - copy assignment operator method not found");
3274 return 0;
3275}
3276
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003277void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3278 CXXConstructorDecl *CopyConstructor,
3279 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003280 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003281 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3282 !CopyConstructor->isUsed()) &&
3283 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003284
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003285 CXXRecordDecl *ClassDecl
3286 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3287 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003288 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003289 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003290 // implicitly defined, all the implicitly-declared copy constructors
3291 // for its base class and its non-static data members shall have been
3292 // implicitly defined.
3293 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3294 Base != ClassDecl->bases_end(); ++Base) {
3295 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003296 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003297 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003298 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003299 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003300 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003301 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3302 FieldEnd = ClassDecl->field_end();
3303 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003304 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3305 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3306 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003307 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003308 CXXRecordDecl *FieldClassDecl
3309 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003310 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003311 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003312 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003313 }
3314 }
3315 CopyConstructor->setUsed();
3316}
3317
Anders Carlsson6eb55572009-08-25 05:12:04 +00003318Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003319Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003320 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003321 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003322 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003324 // C++ [class.copy]p15:
3325 // Whenever a temporary class object is copied using a copy constructor, and
3326 // this object and the copy have the same cv-unqualified type, an
3327 // implementation is permitted to treat the original and the copy as two
3328 // different ways of referring to the same object and not perform a copy at
3329 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003330
Anders Carlsson250aada2009-08-16 05:13:48 +00003331 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003332 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003333 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003334 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3335 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003336 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3337 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3338 E = ICE->getSubExpr();
3339
Anders Carlsson250aada2009-08-16 05:13:48 +00003340 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3341 Elidable = true;
3342 }
Mike Stump11289f42009-09-09 15:08:12 +00003343
3344 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003345 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003346}
3347
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003348/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3349/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003350Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003351Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3352 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003353 MultiExprArg ExprArgs) {
3354 unsigned NumExprs = ExprArgs.size();
3355 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003356
Douglas Gregor27381f32009-11-23 12:27:39 +00003357 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003358 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3359 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003360}
3361
Anders Carlsson574315a2009-08-27 05:08:22 +00003362Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003363Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3364 QualType Ty,
3365 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003366 MultiExprArg Args,
3367 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003368 unsigned NumExprs = Args.size();
3369 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003370
Douglas Gregor27381f32009-11-23 12:27:39 +00003371 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003372 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3373 TyBeginLoc, Exprs,
3374 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003375}
3376
3377
Mike Stump11289f42009-09-09 15:08:12 +00003378bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003379 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003380 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003381 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003382 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003383 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003384 if (TempResult.isInvalid())
3385 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003386
Anders Carlsson6eb55572009-08-25 05:12:04 +00003387 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003388 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003389 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003390 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003391
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003392 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003393}
3394
Mike Stump11289f42009-09-09 15:08:12 +00003395void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003396 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003397 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003398 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003399 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003400 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003401 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003402}
3403
Mike Stump11289f42009-09-09 15:08:12 +00003404/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003405/// ActOnDeclarator, when a C++ direct initializer is present.
3406/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003407void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3408 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003409 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003410 SourceLocation *CommaLocs,
3411 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003412 unsigned NumExprs = Exprs.size();
3413 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003414 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003415
3416 // If there is no declaration, there was an error parsing it. Just ignore
3417 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003418 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003419 return;
Mike Stump11289f42009-09-09 15:08:12 +00003420
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003421 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3422 if (!VDecl) {
3423 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3424 RealDecl->setInvalidDecl();
3425 return;
3426 }
3427
Douglas Gregor402250f2009-08-26 21:14:46 +00003428 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003429 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003430 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3431 //
3432 // Clients that want to distinguish between the two forms, can check for
3433 // direct initializer using VarDecl::hasCXXDirectInitializer().
3434 // A major benefit is that clients that don't particularly care about which
3435 // exactly form was it (like the CodeGen) can handle both cases without
3436 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003437
Douglas Gregor402250f2009-08-26 21:14:46 +00003438 // If either the declaration has a dependent type or if any of the expressions
3439 // is type-dependent, we represent the initialization via a ParenListExpr for
3440 // later use during template instantiation.
3441 if (VDecl->getType()->isDependentType() ||
3442 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3443 // Let clients know that initialization was done with a direct initializer.
3444 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003445
Douglas Gregor402250f2009-08-26 21:14:46 +00003446 // Store the initialization expressions as a ParenListExpr.
3447 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003448 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003449 new (Context) ParenListExpr(Context, LParenLoc,
3450 (Expr **)Exprs.release(),
3451 NumExprs, RParenLoc));
3452 return;
3453 }
Mike Stump11289f42009-09-09 15:08:12 +00003454
Douglas Gregor402250f2009-08-26 21:14:46 +00003455
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003456 // C++ 8.5p11:
3457 // The form of initialization (using parentheses or '=') is generally
3458 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003459 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003460 QualType DeclInitType = VDecl->getType();
3461 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003462 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003463
Douglas Gregor4044d992009-03-24 16:43:20 +00003464 // FIXME: This isn't the right place to complete the type.
3465 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3466 diag::err_typecheck_decl_incomplete_type)) {
3467 VDecl->setInvalidDecl();
3468 return;
3469 }
3470
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003471 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003472 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3473
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003474 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003475 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003476 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003477 VDecl->getLocation(),
3478 SourceRange(VDecl->getLocation(),
3479 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003480 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003481 IK_Direct,
3482 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003483 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003484 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003485 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003486 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003487 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003488 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003489 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003490 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003491 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003492 return;
3493 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003494
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003495 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003496 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3497 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003498 RealDecl->setInvalidDecl();
3499 return;
3500 }
3501
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003502 // Let clients know that initialization was done with a direct initializer.
3503 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003504
3505 assert(NumExprs == 1 && "Expected 1 expression");
3506 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003507 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3508 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003509}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003510
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003511/// \brief Add the applicable constructor candidates for an initialization
3512/// by constructor.
3513static void AddConstructorInitializationCandidates(Sema &SemaRef,
3514 QualType ClassType,
3515 Expr **Args,
3516 unsigned NumArgs,
3517 Sema::InitializationKind Kind,
3518 OverloadCandidateSet &CandidateSet) {
3519 // C++ [dcl.init]p14:
3520 // If the initialization is direct-initialization, or if it is
3521 // copy-initialization where the cv-unqualified version of the
3522 // source type is the same class as, or a derived class of, the
3523 // class of the destination, constructors are considered. The
3524 // applicable constructors are enumerated (13.3.1.3), and the
3525 // best one is chosen through overload resolution (13.3). The
3526 // constructor so selected is called to initialize the object,
3527 // with the initializer expression(s) as its argument(s). If no
3528 // constructor applies, or the overload resolution is ambiguous,
3529 // the initialization is ill-formed.
3530 const RecordType *ClassRec = ClassType->getAs<RecordType>();
3531 assert(ClassRec && "Can only initialize a class type here");
3532
3533 // FIXME: When we decide not to synthesize the implicitly-declared
3534 // constructors, we'll need to make them appear here.
3535
3536 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3537 DeclarationName ConstructorName
3538 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
3539 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
3540 DeclContext::lookup_const_iterator Con, ConEnd;
3541 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3542 Con != ConEnd; ++Con) {
3543 // Find the constructor (which may be a template).
3544 CXXConstructorDecl *Constructor = 0;
3545 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3546 if (ConstructorTmpl)
3547 Constructor
3548 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3549 else
3550 Constructor = cast<CXXConstructorDecl>(*Con);
3551
3552 if ((Kind == Sema::IK_Direct) ||
3553 (Kind == Sema::IK_Copy &&
3554 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3555 (Kind == Sema::IK_Default && Constructor->isDefaultConstructor())) {
3556 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00003557 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
3558 /*ExplicitArgs*/ 0,
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003559 Args, NumArgs, CandidateSet);
3560 else
3561 SemaRef.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3562 }
3563 }
3564}
3565
3566/// \brief Attempt to perform initialization by constructor
3567/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
3568/// copy-initialization.
3569///
3570/// This routine determines whether initialization by constructor is possible,
3571/// but it does not emit any diagnostics in the case where the initialization
3572/// is ill-formed.
3573///
3574/// \param ClassType the type of the object being initialized, which must have
3575/// class type.
3576///
3577/// \param Args the arguments provided to initialize the object
3578///
3579/// \param NumArgs the number of arguments provided to initialize the object
3580///
3581/// \param Kind the type of initialization being performed
3582///
3583/// \returns the constructor used to initialize the object, if successful.
3584/// Otherwise, emits a diagnostic and returns NULL.
3585CXXConstructorDecl *
3586Sema::TryInitializationByConstructor(QualType ClassType,
3587 Expr **Args, unsigned NumArgs,
3588 SourceLocation Loc,
3589 InitializationKind Kind) {
3590 // Build the overload candidate set
3591 OverloadCandidateSet CandidateSet;
3592 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3593 CandidateSet);
3594
3595 // Determine whether we found a constructor we can use.
3596 OverloadCandidateSet::iterator Best;
3597 switch (BestViableFunction(CandidateSet, Loc, Best)) {
3598 case OR_Success:
3599 case OR_Deleted:
3600 // We found a constructor. Return it.
3601 return cast<CXXConstructorDecl>(Best->Function);
3602
3603 case OR_No_Viable_Function:
3604 case OR_Ambiguous:
3605 // Overload resolution failed. Return nothing.
3606 return 0;
3607 }
3608
3609 // Silence GCC warning
3610 return 0;
3611}
3612
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003613/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3614/// may occur as part of direct-initialization or copy-initialization.
3615///
3616/// \param ClassType the type of the object being initialized, which must have
3617/// class type.
3618///
3619/// \param ArgsPtr the arguments provided to initialize the object
3620///
3621/// \param Loc the source location where the initialization occurs
3622///
3623/// \param Range the source range that covers the entire initialization
3624///
3625/// \param InitEntity the name of the entity being initialized, if known
3626///
3627/// \param Kind the type of initialization being performed
3628///
3629/// \param ConvertedArgs a vector that will be filled in with the
3630/// appropriately-converted arguments to the constructor (if initialization
3631/// succeeded).
3632///
3633/// \returns the constructor used to initialize the object, if successful.
3634/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003635CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003636Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003637 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003638 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003639 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003640 InitializationKind Kind,
3641 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003642
3643 // Build the overload candidate set
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003644 Expr **Args = (Expr **)ArgsPtr.get();
3645 unsigned NumArgs = ArgsPtr.size();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003646 OverloadCandidateSet CandidateSet;
Douglas Gregorbf3f3222009-11-14 03:27:21 +00003647 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
3648 CandidateSet);
Douglas Gregor1349b452008-12-15 21:24:18 +00003649
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003650 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003651 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003652 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003653 // We found a constructor. Break out so that we can convert the arguments
3654 // appropriately.
3655 break;
Mike Stump11289f42009-09-09 15:08:12 +00003656
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003657 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003658 if (InitEntity)
3659 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003660 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003661 else
3662 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003663 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003664 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003665 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003666
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003667 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003668 if (InitEntity)
3669 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3670 else
3671 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003672 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3673 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003674
3675 case OR_Deleted:
3676 if (InitEntity)
3677 Diag(Loc, diag::err_ovl_deleted_init)
3678 << Best->Function->isDeleted()
3679 << InitEntity << Range;
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003680 else {
3681 const CXXRecordDecl *RD =
3682 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003683 Diag(Loc, diag::err_ovl_deleted_init)
3684 << Best->Function->isDeleted()
Fariborz Jahanianf82ec6d2009-11-25 21:53:11 +00003685 << RD->getDeclName() << Range;
3686 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00003687 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3688 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003689 }
Mike Stump11289f42009-09-09 15:08:12 +00003690
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003691 // Convert the arguments, fill in default arguments, etc.
3692 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3693 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3694 return 0;
3695
3696 return Constructor;
3697}
3698
3699/// \brief Given a constructor and the set of arguments provided for the
3700/// constructor, convert the arguments and add any required default arguments
3701/// to form a proper call to this constructor.
3702///
3703/// \returns true if an error occurred, false otherwise.
3704bool
3705Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3706 MultiExprArg ArgsPtr,
3707 SourceLocation Loc,
3708 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3709 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3710 unsigned NumArgs = ArgsPtr.size();
3711 Expr **Args = (Expr **)ArgsPtr.get();
3712
3713 const FunctionProtoType *Proto
3714 = Constructor->getType()->getAs<FunctionProtoType>();
3715 assert(Proto && "Constructor without a prototype?");
3716 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003717
3718 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003719 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003720 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003721 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003722 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003723
3724 VariadicCallType CallType =
3725 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
3726 llvm::SmallVector<Expr *, 8> AllArgs;
3727 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
3728 Proto, 0, Args, NumArgs, AllArgs,
3729 CallType);
3730 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
3731 ConvertedArgs.push_back(AllArgs[i]);
3732 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003733}
3734
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003735/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3736/// determine whether they are reference-related,
3737/// reference-compatible, reference-compatible with added
3738/// qualification, or incompatible, for use in C++ initialization by
3739/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3740/// type, and the first type (T1) is the pointee type of the reference
3741/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003742Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003743Sema::CompareReferenceRelationship(SourceLocation Loc,
3744 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003745 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003746 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003747 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003748 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003749
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003750 QualType T1 = Context.getCanonicalType(OrigT1);
3751 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003752 QualType UnqualT1 = T1.getLocalUnqualifiedType();
3753 QualType UnqualT2 = T2.getLocalUnqualifiedType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003754
3755 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003756 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003757 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003758 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003759 if (UnqualT1 == UnqualT2)
3760 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003761 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3762 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3763 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003764 DerivedToBase = true;
3765 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003766 return Ref_Incompatible;
3767
3768 // At this point, we know that T1 and T2 are reference-related (at
3769 // least).
3770
3771 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003772 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003773 // reference-related to T2 and cv1 is the same cv-qualification
3774 // as, or greater cv-qualification than, cv2. For purposes of
3775 // overload resolution, cases for which cv1 is greater
3776 // cv-qualification than cv2 are identified as
3777 // reference-compatible with added qualification (see 13.3.3.2).
3778 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3779 return Ref_Compatible;
3780 else if (T1.isMoreQualifiedThan(T2))
3781 return Ref_Compatible_With_Added_Qualification;
3782 else
3783 return Ref_Related;
3784}
3785
3786/// CheckReferenceInit - Check the initialization of a reference
3787/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3788/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003789/// list), and DeclType is the type of the declaration. When ICS is
3790/// non-null, this routine will compute the implicit conversion
3791/// sequence according to C++ [over.ics.ref] and will not produce any
3792/// diagnostics; when ICS is null, it will emit diagnostics when any
3793/// errors are found. Either way, a return value of true indicates
3794/// that there was a failure, a return value of false indicates that
3795/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003796///
3797/// When @p SuppressUserConversions, user-defined conversions are
3798/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003799/// When @p AllowExplicit, we also permit explicit user-defined
3800/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003801/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redl7c353682009-11-14 21:15:49 +00003802/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
3803/// This is used when this is called from a C-style cast.
Mike Stump11289f42009-09-09 15:08:12 +00003804bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003805Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003806 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003807 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003808 bool AllowExplicit, bool ForceRValue,
Sebastian Redl7c353682009-11-14 21:15:49 +00003809 ImplicitConversionSequence *ICS,
3810 bool IgnoreBaseAccess) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003811 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3812
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003813 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003814 QualType T2 = Init->getType();
3815
Douglas Gregorcd695e52008-11-10 20:40:00 +00003816 // If the initializer is the address of an overloaded function, try
3817 // to resolve the overloaded function. If all goes well, T2 is the
3818 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003819 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003821 ICS != 0);
3822 if (Fn) {
3823 // Since we're performing this reference-initialization for
3824 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003825 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003826 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003827 return true;
3828
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003829 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003830 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003831
3832 T2 = Fn->getType();
3833 }
3834 }
3835
Douglas Gregor786ab212008-10-29 02:00:59 +00003836 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003837 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003838 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003839 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3840 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003841 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003842 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003843
3844 // Most paths end in a failed conversion.
3845 if (ICS)
3846 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003847
3848 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003849 // A reference to type "cv1 T1" is initialized by an expression
3850 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003851
3852 // -- If the initializer expression
3853
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003854 // Rvalue references cannot bind to lvalues (N2812).
3855 // There is absolutely no situation where they can. In particular, note that
3856 // this is ill-formed, even if B has a user-defined conversion to A&&:
3857 // B b;
3858 // A&& r = b;
3859 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3860 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003861 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003862 << Init->getSourceRange();
3863 return true;
3864 }
3865
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003866 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003867 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3868 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003869 //
3870 // Note that the bit-field check is skipped if we are just computing
3871 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003872 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003873 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003874 BindsDirectly = true;
3875
Douglas Gregor786ab212008-10-29 02:00:59 +00003876 if (ICS) {
3877 // C++ [over.ics.ref]p1:
3878 // When a parameter of reference type binds directly (8.5.3)
3879 // to an argument expression, the implicit conversion sequence
3880 // is the identity conversion, unless the argument expression
3881 // has a type that is a derived class of the parameter type,
3882 // in which case the implicit conversion sequence is a
3883 // derived-to-base Conversion (13.3.3.1).
3884 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3885 ICS->Standard.First = ICK_Identity;
3886 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3887 ICS->Standard.Third = ICK_Identity;
3888 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3889 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003890 ICS->Standard.ReferenceBinding = true;
3891 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003892 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003893 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003894
3895 // Nothing more to do: the inaccessibility/ambiguity check for
3896 // derived-to-base conversions is suppressed when we're
3897 // computing the implicit conversion sequence (C++
3898 // [over.best.ics]p2).
3899 return false;
3900 } else {
3901 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003902 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3903 if (DerivedToBase)
3904 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003905 else if(CheckExceptionSpecCompatibility(Init, T1))
3906 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003907 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003908 }
3909 }
3910
3911 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003912 // implicitly converted to an lvalue of type "cv3 T3,"
3913 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003914 // 92) (this conversion is selected by enumerating the
3915 // applicable conversion functions (13.3.1.6) and choosing
3916 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003917 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003918 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003919 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003920 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003921
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003922 OverloadCandidateSet CandidateSet;
John McCalld14a8642009-11-21 08:51:07 +00003923 const UnresolvedSet *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003924 = T2RecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003925 for (UnresolvedSet::iterator I = Conversions->begin(),
3926 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00003927 NamedDecl *D = *I;
3928 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3929 if (isa<UsingShadowDecl>(D))
3930 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3931
Mike Stump11289f42009-09-09 15:08:12 +00003932 FunctionTemplateDecl *ConvTemplate
John McCall6e9f8f62009-12-03 04:06:58 +00003933 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor05155d82009-08-21 23:19:43 +00003934 CXXConversionDecl *Conv;
3935 if (ConvTemplate)
3936 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3937 else
John McCall6e9f8f62009-12-03 04:06:58 +00003938 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003939
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003940 // If the conversion function doesn't return a reference type,
3941 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003942 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003943 (AllowExplicit || !Conv->isExplicit())) {
3944 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00003945 AddTemplateConversionCandidate(ConvTemplate, ActingDC,
3946 Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003947 else
John McCall6e9f8f62009-12-03 04:06:58 +00003948 AddConversionCandidate(Conv, ActingDC, Init, DeclType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003949 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003950 }
3951
3952 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003953 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003954 case OR_Success:
3955 // This is a direct binding.
3956 BindsDirectly = true;
3957
3958 if (ICS) {
3959 // C++ [over.ics.ref]p1:
3960 //
3961 // [...] If the parameter binds directly to the result of
3962 // applying a conversion function to the argument
3963 // expression, the implicit conversion sequence is a
3964 // user-defined conversion sequence (13.3.3.1.2), with the
3965 // second standard conversion sequence either an identity
3966 // conversion or, if the conversion function returns an
3967 // entity of a type that is a derived class of the parameter
3968 // type, a derived-to-base Conversion.
3969 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3970 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3971 ICS->UserDefined.After = Best->FinalConversion;
3972 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003973 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003974 assert(ICS->UserDefined.After.ReferenceBinding &&
3975 ICS->UserDefined.After.DirectBinding &&
3976 "Expected a direct reference binding!");
3977 return false;
3978 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003979 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003980 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003981 CastExpr::CK_UserDefinedConversion,
3982 cast<CXXMethodDecl>(Best->Function),
3983 Owned(Init));
3984 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003985
3986 if (CheckExceptionSpecCompatibility(Init, T1))
3987 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003988 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3989 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003990 }
3991 break;
3992
3993 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003994 if (ICS) {
3995 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3996 Cand != CandidateSet.end(); ++Cand)
3997 if (Cand->Viable)
3998 ICS->ConversionFunctionSet.push_back(Cand->Function);
3999 break;
4000 }
4001 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4002 << Init->getSourceRange();
4003 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004004 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004005
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004006 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00004007 case OR_Deleted:
4008 // There was no suitable conversion, or we found a deleted
4009 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00004010 break;
4011 }
4012 }
Mike Stump11289f42009-09-09 15:08:12 +00004013
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004014 if (BindsDirectly) {
4015 // C++ [dcl.init.ref]p4:
4016 // [...] In all cases where the reference-related or
4017 // reference-compatible relationship of two types is used to
4018 // establish the validity of a reference binding, and T1 is a
4019 // base class of T2, a program that necessitates such a binding
4020 // is ill-formed if T1 is an inaccessible (clause 11) or
4021 // ambiguous (10.2) base class of T2.
4022 //
4023 // Note that we only check this condition when we're allowed to
4024 // complain about errors, because we should not be checking for
4025 // ambiguity (or inaccessibility) unless the reference binding
4026 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00004027 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004028 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redl7c353682009-11-14 21:15:49 +00004029 Init->getSourceRange(),
4030 IgnoreBaseAccess);
Douglas Gregor786ab212008-10-29 02:00:59 +00004031 else
4032 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004033 }
4034
4035 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004036 // type (i.e., cv1 shall be const), or the reference shall be an
4037 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00004038 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00004039 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004040 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004041 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4042 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004043 return true;
4044 }
4045
4046 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00004047 // class type, and "cv1 T1" is reference-compatible with
4048 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004049 // following ways (the choice is implementation-defined):
4050 //
4051 // -- The reference is bound to the object represented by
4052 // the rvalue (see 3.10) or to a sub-object within that
4053 // object.
4054 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00004055 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004056 // a constructor is called to copy the entire rvalue
4057 // object into the temporary. The reference is bound to
4058 // the temporary or to a sub-object within the
4059 // temporary.
4060 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004061 // The constructor that would be used to make the copy
4062 // shall be callable whether or not the copy is actually
4063 // done.
4064 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004065 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004066 // freedom, so we will always take the first option and never build
4067 // a temporary in this case. FIXME: We will, however, have to check
4068 // for the presence of a copy constructor in C++98/03 mode.
4069 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00004070 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4071 if (ICS) {
4072 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
4073 ICS->Standard.First = ICK_Identity;
4074 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4075 ICS->Standard.Third = ICK_Identity;
4076 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4077 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00004078 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004079 ICS->Standard.DirectBinding = false;
4080 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004081 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00004082 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004083 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4084 if (DerivedToBase)
4085 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00004086 else if(CheckExceptionSpecCompatibility(Init, T1))
4087 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004088 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004089 }
4090 return false;
4091 }
4092
Eli Friedman44b83ee2009-08-05 19:21:58 +00004093 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004094 // initialized from the initializer expression using the
4095 // rules for a non-reference copy initialization (8.5). The
4096 // reference is then bound to the temporary. If T1 is
4097 // reference-related to T2, cv1 must be the same
4098 // cv-qualification as, or greater cv-qualification than,
4099 // cv2; otherwise, the program is ill-formed.
4100 if (RefRelationship == Ref_Related) {
4101 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4102 // we would be reference-compatible or reference-compatible with
4103 // added qualification. But that wasn't the case, so the reference
4104 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00004105 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004106 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004107 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
4108 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004109 return true;
4110 }
4111
Douglas Gregor576e98c2009-01-30 23:27:23 +00004112 // If at least one of the types is a class type, the types are not
4113 // related, and we aren't allowed any user conversions, the
4114 // reference binding fails. This case is important for breaking
4115 // recursion, since TryImplicitConversion below will attempt to
4116 // create a temporary through the use of a copy constructor.
4117 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4118 (T1->isRecordType() || T2->isRecordType())) {
4119 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00004120 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00004121 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
4122 return true;
4123 }
4124
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004125 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00004126 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004127 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004128 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004129 // When a parameter of reference type is not bound directly to
4130 // an argument expression, the conversion sequence is the one
4131 // required to convert the argument expression to the
4132 // underlying type of the reference according to
4133 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4134 // to copy-initializing a temporary of the underlying type with
4135 // the argument expression. Any difference in top-level
4136 // cv-qualification is subsumed by the initialization itself
4137 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00004138 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4139 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00004140 /*ForceRValue=*/false,
4141 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004142
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004143 // Of course, that's still a reference binding.
4144 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
4145 ICS->Standard.ReferenceBinding = true;
4146 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00004147 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00004148 ImplicitConversionSequence::UserDefinedConversion) {
4149 ICS->UserDefined.After.ReferenceBinding = true;
4150 ICS->UserDefined.After.RRefBinding = isRValRef;
4151 }
Douglas Gregor786ab212008-10-29 02:00:59 +00004152 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
4153 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004154 ImplicitConversionSequence Conversions;
4155 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
4156 false, false,
4157 Conversions);
4158 if (badConversion) {
4159 if ((Conversions.ConversionKind ==
4160 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00004161 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00004162 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004163 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4164 for (int j = Conversions.ConversionFunctionSet.size()-1;
4165 j >= 0; j--) {
4166 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
4167 Diag(Func->getLocation(), diag::err_ovl_candidate);
4168 }
4169 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00004170 else {
4171 if (isRValRef)
4172 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4173 << Init->getSourceRange();
4174 else
4175 Diag(DeclLoc, diag::err_invalid_initialization)
4176 << DeclType << Init->getType() << Init->getSourceRange();
4177 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00004178 }
4179 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00004180 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004181}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004182
4183/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4184/// of this overloaded operator is well-formed. If so, returns false;
4185/// otherwise, emits appropriate diagnostics and returns true.
4186bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004187 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004188 "Expected an overloaded operator declaration");
4189
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004190 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4191
Mike Stump11289f42009-09-09 15:08:12 +00004192 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004193 // The allocation and deallocation functions, operator new,
4194 // operator new[], operator delete and operator delete[], are
4195 // described completely in 3.7.3. The attributes and restrictions
4196 // found in the rest of this subclause do not apply to them unless
4197 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00004198 // FIXME: Write a separate routine for checking this. For now, just allow it.
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004199 if (Op == OO_Delete || Op == OO_Array_Delete)
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004200 return false;
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004201
4202 if (Op == OO_New || Op == OO_Array_New) {
4203 bool ret = false;
4204 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
4205 QualType SizeTy = Context.getCanonicalType(Context.getSizeType());
4206 QualType T = Context.getCanonicalType((*Param)->getType());
4207 if (!T->isDependentType() && SizeTy != T) {
4208 Diag(FnDecl->getLocation(),
4209 diag::err_operator_new_param_type) << FnDecl->getDeclName()
4210 << SizeTy;
4211 ret = true;
4212 }
4213 }
4214 QualType ResultTy = Context.getCanonicalType(FnDecl->getResultType());
4215 if (!ResultTy->isDependentType() && ResultTy != Context.VoidPtrTy)
4216 return Diag(FnDecl->getLocation(),
4217 diag::err_operator_new_result_type) << FnDecl->getDeclName()
Douglas Gregor6051c8d2009-11-12 16:49:45 +00004218 << static_cast<QualType>(Context.VoidPtrTy);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004219 return ret;
4220 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004221
4222 // C++ [over.oper]p6:
4223 // An operator function shall either be a non-static member
4224 // function or be a non-member function and have at least one
4225 // parameter whose type is a class, a reference to a class, an
4226 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004227 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4228 if (MethodDecl->isStatic())
4229 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004230 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004231 } else {
4232 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004233 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4234 ParamEnd = FnDecl->param_end();
4235 Param != ParamEnd; ++Param) {
4236 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004237 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4238 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004239 ClassOrEnumParam = true;
4240 break;
4241 }
4242 }
4243
Douglas Gregord69246b2008-11-17 16:14:12 +00004244 if (!ClassOrEnumParam)
4245 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004246 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004247 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004248 }
4249
4250 // C++ [over.oper]p8:
4251 // An operator function cannot have default arguments (8.3.6),
4252 // except where explicitly stated below.
4253 //
Mike Stump11289f42009-09-09 15:08:12 +00004254 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004255 // (C++ [over.call]p1).
4256 if (Op != OO_Call) {
4257 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4258 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004259 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004260 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004261 diag::err_operator_overload_default_arg)
4262 << FnDecl->getDeclName();
4263 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004264 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004265 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004266 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004267 }
4268 }
4269
Douglas Gregor6cf08062008-11-10 13:38:07 +00004270 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4271 { false, false, false }
4272#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4273 , { Unary, Binary, MemberOnly }
4274#include "clang/Basic/OperatorKinds.def"
4275 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004276
Douglas Gregor6cf08062008-11-10 13:38:07 +00004277 bool CanBeUnaryOperator = OperatorUses[Op][0];
4278 bool CanBeBinaryOperator = OperatorUses[Op][1];
4279 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004280
4281 // C++ [over.oper]p8:
4282 // [...] Operator functions cannot have more or fewer parameters
4283 // than the number required for the corresponding operator, as
4284 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004285 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004286 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004287 if (Op != OO_Call &&
4288 ((NumParams == 1 && !CanBeUnaryOperator) ||
4289 (NumParams == 2 && !CanBeBinaryOperator) ||
4290 (NumParams < 1) || (NumParams > 2))) {
4291 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004292 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004293 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004294 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004295 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004296 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004297 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004298 assert(CanBeBinaryOperator &&
4299 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004300 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004301 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004302
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004303 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004304 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004305 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004306
Douglas Gregord69246b2008-11-17 16:14:12 +00004307 // Overloaded operators other than operator() cannot be variadic.
4308 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004309 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004310 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004311 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004312 }
4313
4314 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004315 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4316 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004317 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004318 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004319 }
4320
4321 // C++ [over.inc]p1:
4322 // The user-defined function called operator++ implements the
4323 // prefix and postfix ++ operator. If this function is a member
4324 // function with no parameters, or a non-member function with one
4325 // parameter of class or enumeration type, it defines the prefix
4326 // increment operator ++ for objects of that type. If the function
4327 // is a member function with one parameter (which shall be of type
4328 // int) or a non-member function with two parameters (the second
4329 // of which shall be of type int), it defines the postfix
4330 // increment operator ++ for objects of that type.
4331 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4332 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4333 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004334 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004335 ParamIsInt = BT->getKind() == BuiltinType::Int;
4336
Chris Lattner2b786902008-11-21 07:50:02 +00004337 if (!ParamIsInt)
4338 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004339 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004340 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004341 }
4342
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004343 // Notify the class if it got an assignment operator.
4344 if (Op == OO_Equal) {
4345 // Would have returned earlier otherwise.
4346 assert(isa<CXXMethodDecl>(FnDecl) &&
4347 "Overloaded = not member, but not filtered.");
4348 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4349 Method->getParent()->addedAssignmentOperator(Context, Method);
4350 }
4351
Douglas Gregord69246b2008-11-17 16:14:12 +00004352 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004353}
Chris Lattner3b024a32008-12-17 07:09:26 +00004354
Douglas Gregor07665a62009-01-05 19:45:36 +00004355/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4356/// linkage specification, including the language and (if present)
4357/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4358/// the location of the language string literal, which is provided
4359/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4360/// the '{' brace. Otherwise, this linkage specification does not
4361/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004362Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4363 SourceLocation ExternLoc,
4364 SourceLocation LangLoc,
4365 const char *Lang,
4366 unsigned StrSize,
4367 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004368 LinkageSpecDecl::LanguageIDs Language;
4369 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4370 Language = LinkageSpecDecl::lang_c;
4371 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4372 Language = LinkageSpecDecl::lang_cxx;
4373 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004374 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004375 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004376 }
Mike Stump11289f42009-09-09 15:08:12 +00004377
Chris Lattner438e5012008-12-17 07:13:27 +00004378 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004379
Douglas Gregor07665a62009-01-05 19:45:36 +00004380 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004381 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004382 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004383 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004384 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004385 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004386}
4387
Douglas Gregor07665a62009-01-05 19:45:36 +00004388/// ActOnFinishLinkageSpecification - Completely the definition of
4389/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4390/// valid, it's the position of the closing '}' brace in a linkage
4391/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004392Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4393 DeclPtrTy LinkageSpec,
4394 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004395 if (LinkageSpec)
4396 PopDeclContext();
4397 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004398}
4399
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004400/// \brief Perform semantic analysis for the variable declaration that
4401/// occurs within a C++ catch clause, returning the newly-created
4402/// variable.
4403VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004404 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004405 IdentifierInfo *Name,
4406 SourceLocation Loc,
4407 SourceRange Range) {
4408 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004409
4410 // Arrays and functions decay.
4411 if (ExDeclType->isArrayType())
4412 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4413 else if (ExDeclType->isFunctionType())
4414 ExDeclType = Context.getPointerType(ExDeclType);
4415
4416 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4417 // The exception-declaration shall not denote a pointer or reference to an
4418 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004419 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004420 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004421 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004422 Invalid = true;
4423 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004424
Sebastian Redl54c04d42008-12-22 19:15:10 +00004425 QualType BaseType = ExDeclType;
4426 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004427 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004428 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004429 BaseType = Ptr->getPointeeType();
4430 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004431 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004432 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004433 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004434 BaseType = Ref->getPointeeType();
4435 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004436 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004437 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004438 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004439 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004440 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004441
Mike Stump11289f42009-09-09 15:08:12 +00004442 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004443 RequireNonAbstractType(Loc, ExDeclType,
4444 diag::err_abstract_type_in_decl,
4445 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004446 Invalid = true;
4447
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004448 // FIXME: Need to test for ability to copy-construct and destroy the
4449 // exception variable.
4450
Sebastian Redl9b244a82008-12-22 21:35:02 +00004451 // FIXME: Need to check for abstract classes.
4452
Mike Stump11289f42009-09-09 15:08:12 +00004453 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004454 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004455
4456 if (Invalid)
4457 ExDecl->setInvalidDecl();
4458
4459 return ExDecl;
4460}
4461
4462/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4463/// handler.
4464Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004465 DeclaratorInfo *DInfo = 0;
4466 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004467
4468 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004469 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004470 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004471 // The scope should be freshly made just for us. There is just no way
4472 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004473 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004474 if (PrevDecl->isTemplateParameter()) {
4475 // Maybe we will complain about the shadowed template parameter.
4476 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004477 }
4478 }
4479
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004480 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004481 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4482 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004483 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004484 }
4485
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004486 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004487 D.getIdentifier(),
4488 D.getIdentifierLoc(),
4489 D.getDeclSpec().getSourceRange());
4490
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004491 if (Invalid)
4492 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004493
Sebastian Redl54c04d42008-12-22 19:15:10 +00004494 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004495 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004496 PushOnScopeChains(ExDecl, S);
4497 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004498 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004499
Douglas Gregor758a8692009-06-17 21:51:59 +00004500 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004501 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004502}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004503
Mike Stump11289f42009-09-09 15:08:12 +00004504Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004505 ExprArg assertexpr,
4506 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004507 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004508 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004509 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4510
Anders Carlsson54b26982009-03-14 00:33:21 +00004511 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4512 llvm::APSInt Value(32);
4513 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4514 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4515 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004516 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004517 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004518
Anders Carlsson54b26982009-03-14 00:33:21 +00004519 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004520 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004521 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004522 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004523 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004524 }
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004527 assertexpr.release();
4528 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004529 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004530 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004531
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004532 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004533 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004534}
Sebastian Redlf769df52009-03-24 22:27:57 +00004535
John McCall11083da2009-09-16 22:47:08 +00004536/// Handle a friend type declaration. This works in tandem with
4537/// ActOnTag.
4538///
4539/// Notes on friend class templates:
4540///
4541/// We generally treat friend class declarations as if they were
4542/// declaring a class. So, for example, the elaborated type specifier
4543/// in a friend declaration is required to obey the restrictions of a
4544/// class-head (i.e. no typedefs in the scope chain), template
4545/// parameters are required to match up with simple template-ids, &c.
4546/// However, unlike when declaring a template specialization, it's
4547/// okay to refer to a template specialization without an empty
4548/// template parameter declaration, e.g.
4549/// friend class A<T>::B<unsigned>;
4550/// We permit this as a special case; if there are any template
4551/// parameters present at all, require proper matching, i.e.
4552/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004553Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004554 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004555 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004556
4557 assert(DS.isFriendSpecified());
4558 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4559
John McCall11083da2009-09-16 22:47:08 +00004560 // Try to convert the decl specifier to a type. This works for
4561 // friend templates because ActOnTag never produces a ClassTemplateDecl
4562 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004563 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004564 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4565 if (TheDeclarator.isInvalidType())
4566 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004567
John McCall11083da2009-09-16 22:47:08 +00004568 // This is definitely an error in C++98. It's probably meant to
4569 // be forbidden in C++0x, too, but the specification is just
4570 // poorly written.
4571 //
4572 // The problem is with declarations like the following:
4573 // template <T> friend A<T>::foo;
4574 // where deciding whether a class C is a friend or not now hinges
4575 // on whether there exists an instantiation of A that causes
4576 // 'foo' to equal C. There are restrictions on class-heads
4577 // (which we declare (by fiat) elaborated friend declarations to
4578 // be) that makes this tractable.
4579 //
4580 // FIXME: handle "template <> friend class A<T>;", which
4581 // is possibly well-formed? Who even knows?
4582 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4583 Diag(Loc, diag::err_tagless_friend_type_template)
4584 << DS.getSourceRange();
4585 return DeclPtrTy();
4586 }
4587
John McCallaa74a0c2009-08-28 07:59:38 +00004588 // C++ [class.friend]p2:
4589 // An elaborated-type-specifier shall be used in a friend declaration
4590 // for a class.*
4591 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004592 // This is one of the rare places in Clang where it's legitimate to
4593 // ask about the "spelling" of the type.
4594 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4595 // If we evaluated the type to a record type, suggest putting
4596 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004597 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004598 RecordDecl *RD = RT->getDecl();
4599
4600 std::string InsertionText = std::string(" ") + RD->getKindName();
4601
John McCallc3987482009-10-07 23:34:25 +00004602 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4603 << (unsigned) RD->getTagKind()
4604 << T
4605 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004606 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4607 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004608 return DeclPtrTy();
4609 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004610 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4611 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004612 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004613 }
4614 }
4615
John McCallc3987482009-10-07 23:34:25 +00004616 // Enum types cannot be friends.
4617 if (T->getAs<EnumType>()) {
4618 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4619 << SourceRange(DS.getFriendSpecLoc());
4620 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004621 }
John McCallaa74a0c2009-08-28 07:59:38 +00004622
John McCallaa74a0c2009-08-28 07:59:38 +00004623 // C++98 [class.friend]p1: A friend of a class is a function
4624 // or class that is not a member of the class . . .
4625 // But that's a silly restriction which nobody implements for
4626 // inner classes, and C++0x removes it anyway, so we only report
4627 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004628 if (!getLangOptions().CPlusPlus0x)
4629 if (const RecordType *RT = T->getAs<RecordType>())
4630 if (RT->getDecl()->getDeclContext() == CurContext)
4631 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004632
John McCall11083da2009-09-16 22:47:08 +00004633 Decl *D;
4634 if (TempParams.size())
4635 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4636 TempParams.size(),
4637 (TemplateParameterList**) TempParams.release(),
4638 T.getTypePtr(),
4639 DS.getFriendSpecLoc());
4640 else
4641 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4642 DS.getFriendSpecLoc());
4643 D->setAccess(AS_public);
4644 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004645
John McCall11083da2009-09-16 22:47:08 +00004646 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004647}
4648
John McCall2f212b32009-09-11 21:02:39 +00004649Sema::DeclPtrTy
4650Sema::ActOnFriendFunctionDecl(Scope *S,
4651 Declarator &D,
4652 bool IsDefinition,
4653 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004654 const DeclSpec &DS = D.getDeclSpec();
4655
4656 assert(DS.isFriendSpecified());
4657 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4658
4659 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004660 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004661 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004662
4663 // C++ [class.friend]p1
4664 // A friend of a class is a function or class....
4665 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004666 // It *doesn't* see through dependent types, which is correct
4667 // according to [temp.arg.type]p3:
4668 // If a declaration acquires a function type through a
4669 // type dependent on a template-parameter and this causes
4670 // a declaration that does not use the syntactic form of a
4671 // function declarator to have a function type, the program
4672 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004673 if (!T->isFunctionType()) {
4674 Diag(Loc, diag::err_unexpected_friend);
4675
4676 // It might be worthwhile to try to recover by creating an
4677 // appropriate declaration.
4678 return DeclPtrTy();
4679 }
4680
4681 // C++ [namespace.memdef]p3
4682 // - If a friend declaration in a non-local class first declares a
4683 // class or function, the friend class or function is a member
4684 // of the innermost enclosing namespace.
4685 // - The name of the friend is not found by simple name lookup
4686 // until a matching declaration is provided in that namespace
4687 // scope (either before or after the class declaration granting
4688 // friendship).
4689 // - If a friend function is called, its name may be found by the
4690 // name lookup that considers functions from namespaces and
4691 // classes associated with the types of the function arguments.
4692 // - When looking for a prior declaration of a class or a function
4693 // declared as a friend, scopes outside the innermost enclosing
4694 // namespace scope are not considered.
4695
John McCallaa74a0c2009-08-28 07:59:38 +00004696 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4697 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004698 assert(Name);
4699
John McCall07e91c02009-08-06 02:15:43 +00004700 // The context we found the declaration in, or in which we should
4701 // create the declaration.
4702 DeclContext *DC;
4703
4704 // FIXME: handle local classes
4705
4706 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00004707 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
4708 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00004709 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004710 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004711 DC = computeDeclContext(ScopeQual);
4712
4713 // FIXME: handle dependent contexts
4714 if (!DC) return DeclPtrTy();
4715
John McCall1f82f242009-11-18 22:49:29 +00004716 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004717
4718 // If searching in that context implicitly found a declaration in
4719 // a different context, treat it like it wasn't found at all.
4720 // TODO: better diagnostics for this case. Suggesting the right
4721 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00004722 // FIXME: getRepresentativeDecl() is not right here at all
4723 if (Previous.empty() ||
4724 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004725 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004726 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4727 return DeclPtrTy();
4728 }
4729
4730 // C++ [class.friend]p1: A friend of a class is a function or
4731 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004732 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004733 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4734
John McCall07e91c02009-08-06 02:15:43 +00004735 // Otherwise walk out to the nearest namespace scope looking for matches.
4736 } else {
4737 // TODO: handle local class contexts.
4738
4739 DC = CurContext;
4740 while (true) {
4741 // Skip class contexts. If someone can cite chapter and verse
4742 // for this behavior, that would be nice --- it's what GCC and
4743 // EDG do, and it seems like a reasonable intent, but the spec
4744 // really only says that checks for unqualified existing
4745 // declarations should stop at the nearest enclosing namespace,
4746 // not that they should only consider the nearest enclosing
4747 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004748 while (DC->isRecord())
4749 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004750
John McCall1f82f242009-11-18 22:49:29 +00004751 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00004752
4753 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00004754 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00004755 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004756
John McCall07e91c02009-08-06 02:15:43 +00004757 if (DC->isFileContext()) break;
4758 DC = DC->getParent();
4759 }
4760
4761 // C++ [class.friend]p1: A friend of a class is a function or
4762 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004763 // C++0x changes this for both friend types and functions.
4764 // Most C++ 98 compilers do seem to give an error here, so
4765 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00004766 if (!Previous.empty() && DC->Equals(CurContext)
4767 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004768 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4769 }
4770
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004771 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004772 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004773 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4774 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4775 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004776 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004777 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4778 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004779 return DeclPtrTy();
4780 }
John McCall07e91c02009-08-06 02:15:43 +00004781 }
4782
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004783 bool Redeclaration = false;
John McCall1f82f242009-11-18 22:49:29 +00004784 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004785 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004786 IsDefinition,
4787 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004788 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004789
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004790 assert(ND->getDeclContext() == DC);
4791 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004792
John McCall759e32b2009-08-31 22:39:49 +00004793 // Add the function declaration to the appropriate lookup tables,
4794 // adjusting the redeclarations list as necessary. We don't
4795 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004796 //
John McCall759e32b2009-08-31 22:39:49 +00004797 // Also update the scope-based lookup if the target context's
4798 // lookup context is in lexical scope.
4799 if (!CurContext->isDependentContext()) {
4800 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004801 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004802 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004803 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004804 }
John McCallaa74a0c2009-08-28 07:59:38 +00004805
4806 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004807 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004808 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004809 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004810 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004811
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004812 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004813}
4814
Chris Lattner83f095c2009-03-28 19:18:32 +00004815void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004816 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004817
Chris Lattner83f095c2009-03-28 19:18:32 +00004818 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004819 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4820 if (!Fn) {
4821 Diag(DelLoc, diag::err_deleted_non_function);
4822 return;
4823 }
4824 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4825 Diag(DelLoc, diag::err_deleted_decl_not_first);
4826 Diag(Prev->getLocation(), diag::note_previous_declaration);
4827 // If the declaration wasn't the first, we delete the function anyway for
4828 // recovery.
4829 }
4830 Fn->setDeleted();
4831}
Sebastian Redl4c018662009-04-27 21:33:24 +00004832
4833static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4834 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4835 ++CI) {
4836 Stmt *SubStmt = *CI;
4837 if (!SubStmt)
4838 continue;
4839 if (isa<ReturnStmt>(SubStmt))
4840 Self.Diag(SubStmt->getSourceRange().getBegin(),
4841 diag::err_return_in_constructor_handler);
4842 if (!isa<Expr>(SubStmt))
4843 SearchForReturnInStmt(Self, SubStmt);
4844 }
4845}
4846
4847void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4848 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4849 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4850 SearchForReturnInStmt(*this, Handler);
4851 }
4852}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004853
Mike Stump11289f42009-09-09 15:08:12 +00004854bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004855 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004856 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4857 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004858
4859 QualType CNewTy = Context.getCanonicalType(NewTy);
4860 QualType COldTy = Context.getCanonicalType(OldTy);
4861
Mike Stump11289f42009-09-09 15:08:12 +00004862 if (CNewTy == COldTy &&
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004863 CNewTy.getLocalCVRQualifiers() == COldTy.getLocalCVRQualifiers())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004864 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004865
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004866 // Check if the return types are covariant
4867 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004868
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004869 /// Both types must be pointers or references to classes.
4870 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4871 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4872 NewClassTy = NewPT->getPointeeType();
4873 OldClassTy = OldPT->getPointeeType();
4874 }
4875 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4876 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4877 NewClassTy = NewRT->getPointeeType();
4878 OldClassTy = OldRT->getPointeeType();
4879 }
4880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004882 // The return types aren't either both pointers or references to a class type.
4883 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004884 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004885 diag::err_different_return_type_for_overriding_virtual_function)
4886 << New->getDeclName() << NewTy << OldTy;
4887 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004888
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004889 return true;
4890 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004891
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004892 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004893 // Check if the new class derives from the old class.
4894 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4895 Diag(New->getLocation(),
4896 diag::err_covariant_return_not_derived)
4897 << New->getDeclName() << NewTy << OldTy;
4898 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4899 return true;
4900 }
Mike Stump11289f42009-09-09 15:08:12 +00004901
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004902 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004903 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004904 diag::err_covariant_return_inaccessible_base,
4905 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4906 // FIXME: Should this point to the return type?
4907 New->getLocation(), SourceRange(), New->getDeclName())) {
4908 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4909 return true;
4910 }
4911 }
Mike Stump11289f42009-09-09 15:08:12 +00004912
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004913 // The qualifiers of the return types must be the same.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004914 if (CNewTy.getLocalCVRQualifiers() != COldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004915 Diag(New->getLocation(),
4916 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004917 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004918 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4919 return true;
4920 };
Mike Stump11289f42009-09-09 15:08:12 +00004921
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004922
4923 // The new class type must have the same or less qualifiers as the old type.
4924 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4925 Diag(New->getLocation(),
4926 diag::err_covariant_return_type_class_type_more_qualified)
4927 << New->getDeclName() << NewTy << OldTy;
4928 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4929 return true;
4930 };
Mike Stump11289f42009-09-09 15:08:12 +00004931
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004932 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004933}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004934
Alexis Hunt96d5c762009-11-21 08:43:09 +00004935bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
4936 const CXXMethodDecl *Old)
4937{
4938 if (Old->hasAttr<FinalAttr>()) {
4939 Diag(New->getLocation(), diag::err_final_function_overridden)
4940 << New->getDeclName();
4941 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4942 return true;
4943 }
4944
4945 return false;
4946}
4947
Douglas Gregor21920e372009-12-01 17:24:26 +00004948/// \brief Mark the given method pure.
4949///
4950/// \param Method the method to be marked pure.
4951///
4952/// \param InitRange the source range that covers the "0" initializer.
4953bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
4954 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
4955 Method->setPure();
4956
4957 // A class is abstract if at least one function is pure virtual.
4958 Method->getParent()->setAbstract(true);
4959 return false;
4960 }
4961
4962 if (!Method->isInvalidDecl())
4963 Diag(Method->getLocation(), diag::err_non_virtual_pure)
4964 << Method->getDeclName() << InitRange;
4965 return true;
4966}
4967
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004968/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4969/// initializer for the declaration 'Dcl'.
4970/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4971/// static data member of class X, names should be looked up in the scope of
4972/// class X.
4973void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004974 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004975
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004976 Decl *D = Dcl.getAs<Decl>();
4977 // If there is no declaration, there was an error parsing it.
4978 if (D == 0)
4979 return;
4980
4981 // Check whether it is a declaration with a nested name specifier like
4982 // int foo::bar;
4983 if (!D->isOutOfLine())
4984 return;
Mike Stump11289f42009-09-09 15:08:12 +00004985
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004986 // C++ [basic.lookup.unqual]p13
4987 //
4988 // A name used in the definition of a static data member of class X
4989 // (after the qualified-id of the static member) is looked up as if the name
4990 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004991
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004992 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004993 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004994}
4995
4996/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4997/// initializer for the declaration 'Dcl'.
4998void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004999 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005000
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005001 Decl *D = Dcl.getAs<Decl>();
5002 // If there is no declaration, there was an error parsing it.
5003 if (D == 0)
5004 return;
5005
5006 // Check whether it is a declaration with a nested name specifier like
5007 // int foo::bar;
5008 if (!D->isOutOfLine())
5009 return;
5010
5011 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00005012 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005013}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005014
5015/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5016/// C++ if/switch/while/for statement.
5017/// e.g: "if (int x = f()) {...}"
5018Action::DeclResult
5019Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5020 // C++ 6.4p2:
5021 // The declarator shall not specify a function or an array.
5022 // The type-specifier-seq shall not contain typedef and shall not declare a
5023 // new class or enumeration.
5024 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5025 "Parser allowed 'typedef' as storage class of condition decl.");
5026
5027 DeclaratorInfo *DInfo = 0;
5028 TagDecl *OwnedTag = 0;
5029 QualType Ty = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
5030
5031 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5032 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5033 // would be created and CXXConditionDeclExpr wants a VarDecl.
5034 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5035 << D.getSourceRange();
5036 return DeclResult();
5037 } else if (OwnedTag && OwnedTag->isDefinition()) {
5038 // The type-specifier-seq shall not declare a new class or enumeration.
5039 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5040 }
5041
5042 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5043 if (!Dcl)
5044 return DeclResult();
5045
5046 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5047 VD->setDeclaredInCondition(true);
5048 return Dcl;
5049}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005050
5051void Sema::MaybeMarkVirtualImplicitMembersReferenced(SourceLocation Loc,
5052 CXXMethodDecl *MD) {
5053 // Ignore dependent types.
5054 if (MD->isDependentContext())
5055 return;
5056
5057 CXXRecordDecl *RD = MD->getParent();
5058 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5059 const CXXMethodDecl *KeyFunction = Layout.getKeyFunction();
5060
5061 if (!KeyFunction) {
5062 // This record does not have a key function, so we assume that the vtable
5063 // will be emitted when it's used by the constructor.
5064 if (!isa<CXXConstructorDecl>(MD))
5065 return;
5066 } else if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl()) {
5067 // We don't have the right key function.
5068 return;
5069 }
5070
5071 if (CXXDestructorDecl *Dtor = RD->getDestructor(Context)) {
5072 if (Dtor->isImplicit() && Dtor->isVirtual())
5073 MarkDeclarationReferenced(Loc, Dtor);
5074 }
5075
5076 // FIXME: Need to handle the virtual assignment operator here too.
5077}