blob: 41f8aec815bc82a3af71021ca068231b5343269c [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner58258242008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssond624e162009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar34fb6722008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner58258242008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregor29a92472008-10-22 17:49:05 +000027#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000028#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000029
30using namespace clang;
31
Chris Lattner58258242008-04-10 02:22:51 +000032//===----------------------------------------------------------------------===//
33// CheckDefaultArgumentVisitor
34//===----------------------------------------------------------------------===//
35
Chris Lattnerb0d38442008-04-12 23:52:44 +000036namespace {
37 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
38 /// the default argument of a parameter to determine whether it
39 /// contains any ill-formed subexpressions. For example, this will
40 /// diagnose the use of local variables or parameters within the
41 /// default argument expression.
Mike Stump11289f42009-09-09 15:08:12 +000042 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000043 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000044 Expr *DefaultArg;
45 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000046
Chris Lattnerb0d38442008-04-12 23:52:44 +000047 public:
Mike Stump11289f42009-09-09 15:08:12 +000048 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000049 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000050
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 bool VisitExpr(Expr *Node);
52 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000053 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 };
Chris Lattner58258242008-04-10 02:22:51 +000055
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 /// VisitExpr - Visit all of the children of this expression.
57 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
58 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000059 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000060 E = Node->child_end(); I != E; ++I)
61 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000063 }
64
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 /// VisitDeclRefExpr - Visit a reference to a declaration, to
66 /// determine whether this declaration can be used in the default
67 /// argument expression.
68 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000069 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
71 // C++ [dcl.fct.default]p9
72 // Default arguments are evaluated each time the function is
73 // called. The order of evaluation of function arguments is
74 // unspecified. Consequently, parameters of a function shall not
75 // be used in default argument expressions, even if they are not
76 // evaluated. Parameters of a function declared before a default
77 // argument expression are in scope and can hide namespace and
78 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000079 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000080 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000081 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000082 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000083 // C++ [dcl.fct.default]p7
84 // Local variables shall not be used in default argument
85 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000086 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000087 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000088 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000089 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 }
Chris Lattner58258242008-04-10 02:22:51 +000091
Douglas Gregor8e12c382008-11-04 13:41:56 +000092 return false;
93 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000094
Douglas Gregor97a9c812008-11-04 14:32:21 +000095 /// VisitCXXThisExpr - Visit a C++ "this" expression.
96 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
97 // C++ [dcl.fct.default]p8:
98 // The keyword this shall not be used in a default argument of a
99 // member function.
100 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000101 diag::err_param_default_argument_references_this)
102 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000103 }
Chris Lattner58258242008-04-10 02:22:51 +0000104}
105
Anders Carlssonc80a1272009-08-25 02:29:20 +0000106bool
107Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000108 SourceLocation EqualLoc) {
Anders Carlssonc80a1272009-08-25 02:29:20 +0000109 QualType ParamType = Param->getType();
110
Anders Carlsson114056f2009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssonc80a1272009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000118
Anders Carlssonc80a1272009-08-25 02:29:20 +0000119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
Mike Stump11289f42009-09-09 15:08:12 +0000125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssonc80a1272009-08-25 02:29:20 +0000126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000127 return true;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump11289f42009-09-09 15:08:12 +0000130
Anders Carlssonc80a1272009-08-25 02:29:20 +0000131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000133
Anders Carlssonc80a1272009-08-25 02:29:20 +0000134 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000135
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000137}
138
Chris Lattner58258242008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000142void
Mike Stump11289f42009-09-09 15:08:12 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
Mike Stump11289f42009-09-09 15:08:12 +0000147
Chris Lattner83f095c2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlssonf1c26952009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
Anders Carlssonc80a1272009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000170}
171
Douglas Gregor58354032008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000179 if (!param)
180 return;
Mike Stump11289f42009-09-09 15:08:12 +0000181
Chris Lattner83f095c2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000185
Anders Carlsson84613c42009-06-12 16:51:40 +0000186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000187}
188
Douglas Gregor4d87df52008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000192 if (!param)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Anders Carlsson84613c42009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000196
Anders Carlsson84613c42009-06-12 16:51:40 +0000197 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000198
Anders Carlsson84613c42009-06-12 16:51:40 +0000199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000200}
201
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner199abbc2008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner199abbc2008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000256 //
257 // C++ [dcl.fct.default]p6:
258 // Except for member functions of class templates, the default arguments
259 // in a member function definition that appears outside of the class
260 // definition are added to the set of default arguments provided by the
261 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000262 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
263 ParmVarDecl *OldParam = Old->getParamDecl(p);
264 ParmVarDecl *NewParam = New->getParamDecl(p);
265
Douglas Gregorc732aba2009-09-11 18:44:32 +0000266 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump11289f42009-09-09 15:08:12 +0000267 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000268 diag::err_param_default_argument_redefinition)
Douglas Gregorc732aba2009-09-11 18:44:32 +0000269 << NewParam->getDefaultArgRange();
270
271 // Look for the function declaration where the default argument was
272 // actually written, which may be a declaration prior to Old.
273 for (FunctionDecl *Older = Old->getPreviousDeclaration();
274 Older; Older = Older->getPreviousDeclaration()) {
275 if (!Older->getParamDecl(p)->hasDefaultArg())
276 break;
277
278 OldParam = Older->getParamDecl(p);
279 }
280
281 Diag(OldParam->getLocation(), diag::note_previous_definition)
282 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000283 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000284 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000285 // Merge the old default argument into the new parameter
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000286 if (OldParam->hasUninstantiatedDefaultArg())
287 NewParam->setUninstantiatedDefaultArg(
288 OldParam->getUninstantiatedDefaultArg());
289 else
290 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000291 } else if (NewParam->hasDefaultArg()) {
292 if (New->getDescribedFunctionTemplate()) {
293 // Paragraph 4, quoted above, only applies to non-template functions.
294 Diag(NewParam->getLocation(),
295 diag::err_param_default_argument_template_redecl)
296 << NewParam->getDefaultArgRange();
297 Diag(Old->getLocation(), diag::note_template_prev_declaration)
298 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000299 } else if (New->getTemplateSpecializationKind()
300 != TSK_ImplicitInstantiation &&
301 New->getTemplateSpecializationKind() != TSK_Undeclared) {
302 // C++ [temp.expr.spec]p21:
303 // Default function arguments shall not be specified in a declaration
304 // or a definition for one of the following explicit specializations:
305 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000306 // - the explicit specialization of a member function template;
307 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000308 // template where the class template specialization to which the
309 // member function specialization belongs is implicitly
310 // instantiated.
311 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
312 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
313 << New->getDeclName()
314 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000315 } else if (New->getDeclContext()->isDependentContext()) {
316 // C++ [dcl.fct.default]p6 (DR217):
317 // Default arguments for a member function of a class template shall
318 // be specified on the initial declaration of the member function
319 // within the class template.
320 //
321 // Reading the tea leaves a bit in DR217 and its reference to DR205
322 // leads me to the conclusion that one cannot add default function
323 // arguments for an out-of-line definition of a member function of a
324 // dependent type.
325 int WhichKind = 2;
326 if (CXXRecordDecl *Record
327 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
328 if (Record->getDescribedClassTemplate())
329 WhichKind = 0;
330 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
331 WhichKind = 1;
332 else
333 WhichKind = 2;
334 }
335
336 Diag(NewParam->getLocation(),
337 diag::err_param_default_argument_member_template_redecl)
338 << WhichKind
339 << NewParam->getDefaultArgRange();
340 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000341 }
342 }
343
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000344 if (CheckEquivalentExceptionSpec(
John McCall9dd450b2009-09-21 23:43:11 +0000345 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
346 New->getType()->getAs<FunctionProtoType>(), New->getLocation())) {
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000347 Invalid = true;
348 }
349
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000350 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000351}
352
353/// CheckCXXDefaultArguments - Verify that the default arguments for a
354/// function declaration are well-formed according to C++
355/// [dcl.fct.default].
356void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
357 unsigned NumParams = FD->getNumParams();
358 unsigned p;
359
360 // Find first parameter with a default argument
361 for (p = 0; p < NumParams; ++p) {
362 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000363 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000364 break;
365 }
366
367 // C++ [dcl.fct.default]p4:
368 // In a given function declaration, all parameters
369 // subsequent to a parameter with a default argument shall
370 // have default arguments supplied in this or previous
371 // declarations. A default argument shall not be redefined
372 // by a later declaration (not even to the same value).
373 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000374 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000376 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000377 if (Param->isInvalidDecl())
378 /* We already complained about this parameter. */;
379 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000380 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000381 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000382 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000383 else
Mike Stump11289f42009-09-09 15:08:12 +0000384 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000385 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000386
Chris Lattner199abbc2008-04-08 05:04:30 +0000387 LastMissingDefaultArg = p;
388 }
389 }
390
391 if (LastMissingDefaultArg > 0) {
392 // Some default arguments were missing. Clear out all of the
393 // default arguments up to (and including) the last missing
394 // default argument, so that we leave the function parameters
395 // in a semantically valid state.
396 for (p = 0; p <= LastMissingDefaultArg; ++p) {
397 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000398 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000399 if (!Param->hasUnparsedDefaultArg())
400 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 Param->setDefaultArg(0);
402 }
403 }
404 }
405}
Douglas Gregor556877c2008-04-13 21:30:24 +0000406
Douglas Gregor61956c42008-10-31 09:07:45 +0000407/// isCurrentClassName - Determine whether the identifier II is the
408/// name of the class type currently being defined. In the case of
409/// nested classes, this will only return true if II is the name of
410/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000411bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
412 const CXXScopeSpec *SS) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000413 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000414 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000415 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
417 } else
418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
419
420 if (CurDecl)
Douglas Gregor61956c42008-10-31 09:07:45 +0000421 return &II == CurDecl->getIdentifier();
422 else
423 return false;
424}
425
Mike Stump11289f42009-09-09 15:08:12 +0000426/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000427///
428/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
429/// and returns NULL otherwise.
430CXXBaseSpecifier *
431Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
432 SourceRange SpecifierRange,
433 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000434 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000435 SourceLocation BaseLoc) {
436 // C++ [class.union]p1:
437 // A union shall not have base classes.
438 if (Class->isUnion()) {
439 Diag(Class->getLocation(), diag::err_base_clause_on_union)
440 << SpecifierRange;
441 return 0;
442 }
443
444 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000445 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-03-03 04:44:36 +0000446 Class->getTagKind() == RecordDecl::TK_class,
447 Access, BaseType);
448
449 // Base specifiers must be record types.
450 if (!BaseType->isRecordType()) {
451 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
452 return 0;
453 }
454
455 // C++ [class.union]p1:
456 // A union shall not be used as a base class.
457 if (BaseType->isUnionType()) {
458 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
459 return 0;
460 }
461
462 // C++ [class.derived]p2:
463 // The class-name in a base-specifier shall not be an incompletely
464 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000465 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000466 PDiag(diag::err_incomplete_base_class)
467 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000468 return 0;
469
Eli Friedmanc96d4962009-08-15 21:55:26 +0000470 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000471 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000472 assert(BaseDecl && "Record type has no declaration");
473 BaseDecl = BaseDecl->getDefinition(Context);
474 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000475 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
476 assert(CXXBaseDecl && "Base type is not a C++ type");
477 if (!CXXBaseDecl->isEmpty())
478 Class->setEmpty(false);
479 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor463421d2009-03-03 04:44:36 +0000480 Class->setPolymorphic(true);
481
482 // C++ [dcl.init.aggr]p1:
483 // An aggregate is [...] a class with [...] no base classes [...].
484 Class->setAggregate(false);
485 Class->setPOD(false);
486
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000487 if (Virtual) {
488 // C++ [class.ctor]p5:
489 // A constructor is trivial if its class has no virtual base classes.
490 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000491
492 // C++ [class.copy]p6:
493 // A copy constructor is trivial if its class has no virtual base classes.
494 Class->setHasTrivialCopyConstructor(false);
495
496 // C++ [class.copy]p11:
497 // A copy assignment operator is trivial if its class has no virtual
498 // base classes.
499 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000500
501 // C++0x [meta.unary.prop] is_empty:
502 // T is a class type, but not a union type, with ... no virtual base
503 // classes
504 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000505 } else {
506 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000507 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000508 // class have trivial constructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000509 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
510 Class->setHasTrivialConstructor(false);
511
512 // C++ [class.copy]p6:
513 // A copy constructor is trivial if all the direct base classes of its
514 // class have trivial copy constructors.
515 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
516 Class->setHasTrivialCopyConstructor(false);
517
518 // C++ [class.copy]p11:
519 // A copy assignment operator is trivial if all the direct base classes
520 // of its class have trivial copy assignment operators.
521 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
522 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000523 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000524
525 // C++ [class.ctor]p3:
526 // A destructor is trivial if all the direct base classes of its class
527 // have trivial destructors.
Douglas Gregor8a273912009-07-22 18:25:24 +0000528 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
529 Class->setHasTrivialDestructor(false);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregor463421d2009-03-03 04:44:36 +0000531 // Create the base specifier.
532 // FIXME: Allocate via ASTContext?
Mike Stump11289f42009-09-09 15:08:12 +0000533 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
534 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000535 Access, BaseType);
536}
537
Douglas Gregor556877c2008-04-13 21:30:24 +0000538/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
539/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000540/// example:
541/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000542/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000543Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000544Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000545 bool Virtual, AccessSpecifier Access,
546 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000547 if (!classdecl)
548 return true;
549
Douglas Gregorc40290e2009-03-09 23:48:35 +0000550 AdjustDeclIfTemplate(classdecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000551 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000552 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000553 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
554 Virtual, Access,
555 BaseType, BaseLoc))
556 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000557
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000559}
Douglas Gregor556877c2008-04-13 21:30:24 +0000560
Douglas Gregor463421d2009-03-03 04:44:36 +0000561/// \brief Performs the actual work of attaching the given base class
562/// specifiers to a C++ class.
563bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
564 unsigned NumBases) {
565 if (NumBases == 0)
566 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000567
568 // Used to keep track of which base types we have already seen, so
569 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000570 // that the key is always the unqualified canonical type of the base
571 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000572 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
573
574 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000575 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000577 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000578 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000579 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000580 NewBaseType = NewBaseType.getUnqualifiedType();
581
Douglas Gregor29a92472008-10-22 17:49:05 +0000582 if (KnownBaseTypes[NewBaseType]) {
583 // C++ [class.mi]p3:
584 // A class shall not be specified as a direct base class of a
585 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000586 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000587 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000588 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000589 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000590
591 // Delete the duplicate base class specifier; we're going to
592 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000593 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000594
595 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000596 } else {
597 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000598 KnownBaseTypes[NewBaseType] = Bases[idx];
599 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000600 }
601 }
602
603 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9fa077c2009-07-02 18:26:15 +0000604 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000605
606 // Delete the remaining (good) base class specifiers, since their
607 // data has been copied into the CXXRecordDecl.
608 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000609 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000610
611 return Invalid;
612}
613
614/// ActOnBaseSpecifiers - Attach the given base specifiers to the
615/// class, after checking whether there are any duplicate base
616/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000617void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000618 unsigned NumBases) {
619 if (!ClassDecl || !Bases || !NumBases)
620 return;
621
622 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000623 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000625}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000626
Douglas Gregor36d1b142009-10-06 17:59:45 +0000627/// \brief Determine whether the type \p Derived is a C++ class that is
628/// derived from the type \p Base.
629bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
630 if (!getLangOptions().CPlusPlus)
631 return false;
632
633 const RecordType *DerivedRT = Derived->getAs<RecordType>();
634 if (!DerivedRT)
635 return false;
636
637 const RecordType *BaseRT = Base->getAs<RecordType>();
638 if (!BaseRT)
639 return false;
640
641 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
642 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
643 return DerivedRD->isDerivedFrom(BaseRD);
644}
645
646/// \brief Determine whether the type \p Derived is a C++ class that is
647/// derived from the type \p Base.
648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
649 if (!getLangOptions().CPlusPlus)
650 return false;
651
652 const RecordType *DerivedRT = Derived->getAs<RecordType>();
653 if (!DerivedRT)
654 return false;
655
656 const RecordType *BaseRT = Base->getAs<RecordType>();
657 if (!BaseRT)
658 return false;
659
660 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
661 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
662 return DerivedRD->isDerivedFrom(BaseRD, Paths);
663}
664
665/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
666/// conversion (where Derived and Base are class types) is
667/// well-formed, meaning that the conversion is unambiguous (and
668/// that all of the base classes are accessible). Returns true
669/// and emits a diagnostic if the code is ill-formed, returns false
670/// otherwise. Loc is the location where this routine should point to
671/// if there is an error, and Range is the source range to highlight
672/// if there is an error.
673bool
674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
675 unsigned InaccessibleBaseID,
676 unsigned AmbigiousBaseConvID,
677 SourceLocation Loc, SourceRange Range,
678 DeclarationName Name) {
679 // First, determine whether the path from Derived to Base is
680 // ambiguous. This is slightly more expensive than checking whether
681 // the Derived to Base conversion exists, because here we need to
682 // explore multiple paths to determine if there is an ambiguity.
683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
684 /*DetectVirtual=*/false);
685 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
686 assert(DerivationOkay &&
687 "Can only be used with a derived-to-base conversion");
688 (void)DerivationOkay;
689
690 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
691 // Check that the base class can be accessed.
692 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
693 Name);
694 }
695
696 // We know that the derived-to-base conversion is ambiguous, and
697 // we're going to produce a diagnostic. Perform the derived-to-base
698 // search just one more time to compute all of the possible paths so
699 // that we can print them out. This is more expensive than any of
700 // the previous derived-to-base checks we've done, but at this point
701 // performance isn't as much of an issue.
702 Paths.clear();
703 Paths.setRecordingPaths(true);
704 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
705 assert(StillOkay && "Can only be used with a derived-to-base conversion");
706 (void)StillOkay;
707
708 // Build up a textual representation of the ambiguous paths, e.g.,
709 // D -> B -> A, that will be used to illustrate the ambiguous
710 // conversions in the diagnostic. We only print one of the paths
711 // to each base class subobject.
712 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
713
714 Diag(Loc, AmbigiousBaseConvID)
715 << Derived << Base << PathDisplayStr << Range << Name;
716 return true;
717}
718
719bool
720Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
721 SourceLocation Loc, SourceRange Range) {
722 return CheckDerivedToBaseConversion(Derived, Base,
723 diag::err_conv_to_inaccessible_base,
724 diag::err_ambiguous_derived_to_base_conv,
725 Loc, Range, DeclarationName());
726}
727
728
729/// @brief Builds a string representing ambiguous paths from a
730/// specific derived class to different subobjects of the same base
731/// class.
732///
733/// This function builds a string that can be used in error messages
734/// to show the different paths that one can take through the
735/// inheritance hierarchy to go from the derived class to different
736/// subobjects of a base class. The result looks something like this:
737/// @code
738/// struct D -> struct B -> struct A
739/// struct D -> struct C -> struct A
740/// @endcode
741std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
742 std::string PathDisplayStr;
743 std::set<unsigned> DisplayedPaths;
744 for (CXXBasePaths::paths_iterator Path = Paths.begin();
745 Path != Paths.end(); ++Path) {
746 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
747 // We haven't displayed a path to this particular base
748 // class subobject yet.
749 PathDisplayStr += "\n ";
750 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
751 for (CXXBasePath::const_iterator Element = Path->begin();
752 Element != Path->end(); ++Element)
753 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
754 }
755 }
756
757 return PathDisplayStr;
758}
759
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000760//===----------------------------------------------------------------------===//
761// C++ class member Handling
762//===----------------------------------------------------------------------===//
763
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000764/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
765/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
766/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000767/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000768Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000769Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000770 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000771 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000772 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000773 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000774 Expr *BitWidth = static_cast<Expr*>(BW);
775 Expr *Init = static_cast<Expr*>(InitExpr);
776 SourceLocation Loc = D.getIdentifierLoc();
777
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000778 bool isFunc = D.isFunctionDeclarator();
779
John McCall07e91c02009-08-06 02:15:43 +0000780 assert(!DS.isFriendSpecified());
781
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000782 // C++ 9.2p6: A member shall not be declared to have automatic storage
783 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000784 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
785 // data members and cannot be applied to names declared const or static,
786 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000787 switch (DS.getStorageClassSpec()) {
788 case DeclSpec::SCS_unspecified:
789 case DeclSpec::SCS_typedef:
790 case DeclSpec::SCS_static:
791 // FALL THROUGH.
792 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000793 case DeclSpec::SCS_mutable:
794 if (isFunc) {
795 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000796 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000797 else
Chris Lattner3b054132008-11-19 05:08:23 +0000798 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000799
Sebastian Redl8071edb2008-11-17 23:24:37 +0000800 // FIXME: It would be nicer if the keyword was ignored only for this
801 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000802 D.getMutableDeclSpec().ClearStorageClassSpecs();
803 } else {
804 QualType T = GetTypeForDeclarator(D, S);
805 diag::kind err = static_cast<diag::kind>(0);
806 if (T->isReferenceType())
807 err = diag::err_mutable_reference;
808 else if (T.isConstQualified())
809 err = diag::err_mutable_const;
810 if (err != 0) {
811 if (DS.getStorageClassSpecLoc().isValid())
812 Diag(DS.getStorageClassSpecLoc(), err);
813 else
814 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000815 // FIXME: It would be nicer if the keyword was ignored only for this
816 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000817 D.getMutableDeclSpec().ClearStorageClassSpecs();
818 }
819 }
820 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000821 default:
822 if (DS.getStorageClassSpecLoc().isValid())
823 Diag(DS.getStorageClassSpecLoc(),
824 diag::err_storageclass_invalid_for_member);
825 else
826 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
827 D.getMutableDeclSpec().ClearStorageClassSpecs();
828 }
829
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000830 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000831 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000832 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000833 // Check also for this case:
834 //
835 // typedef int f();
836 // f a;
837 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000838 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000839 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000840 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000841
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000842 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
843 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000844 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000845
846 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000847 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000848 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000849 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
850 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000851 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000852 } else {
Douglas Gregor3447e762009-08-20 22:52:58 +0000853 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
854 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000855 if (!Member) {
856 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000857 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000858 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000859
860 // Non-instance-fields can't have a bitfield.
861 if (BitWidth) {
862 if (Member->isInvalidDecl()) {
863 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000864 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000865 // C++ 9.6p3: A bit-field shall not be a static member.
866 // "static member 'A' cannot be a bit-field"
867 Diag(Loc, diag::err_static_not_bitfield)
868 << Name << BitWidth->getSourceRange();
869 } else if (isa<TypedefDecl>(Member)) {
870 // "typedef member 'x' cannot be a bit-field"
871 Diag(Loc, diag::err_typedef_not_bitfield)
872 << Name << BitWidth->getSourceRange();
873 } else {
874 // A function typedef ("typedef int f(); f a;").
875 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
876 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000877 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000878 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000879 }
Mike Stump11289f42009-09-09 15:08:12 +0000880
Chris Lattnerd26760a2009-03-05 23:01:03 +0000881 DeleteExpr(BitWidth);
882 BitWidth = 0;
883 Member->setInvalidDecl();
884 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000885
886 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000887
Douglas Gregor3447e762009-08-20 22:52:58 +0000888 // If we have declared a member function template, set the access of the
889 // templated declaration as well.
890 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
891 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000892 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000893
Douglas Gregor92751d42008-11-17 22:58:34 +0000894 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000895
Douglas Gregor0c880302009-03-11 23:00:04 +0000896 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000897 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000898 if (Deleted) // FIXME: Source location is not very good.
899 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000900
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000902 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000903 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000904 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000905 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000906}
907
Douglas Gregore8381c02008-11-05 04:29:56 +0000908/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +0000909Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000910Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000911 Scope *S,
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000912 const CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000913 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000914 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000915 SourceLocation IdLoc,
916 SourceLocation LParenLoc,
917 ExprTy **Args, unsigned NumArgs,
918 SourceLocation *CommaLocs,
919 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000920 if (!ConstructorD)
921 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregorc8c277a2009-08-24 11:57:43 +0000923 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +0000924
925 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +0000926 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +0000927 if (!Constructor) {
928 // The user wrote a constructor initializer on a function that is
929 // not a C++ constructor. Ignore the error for now, because we may
930 // have more member initializers coming; we'll diagnose it just
931 // once in ActOnMemInitializers.
932 return true;
933 }
934
935 CXXRecordDecl *ClassDecl = Constructor->getParent();
936
937 // C++ [class.base.init]p2:
938 // Names in a mem-initializer-id are looked up in the scope of the
939 // constructor’s class and, if not found in that scope, are looked
940 // up in the scope containing the constructor’s
941 // definition. [Note: if the constructor’s class contains a member
942 // with the same name as a direct or virtual base class of the
943 // class, a mem-initializer-id naming the member or base class and
944 // composed of a single identifier refers to the class member. A
945 // mem-initializer-id for the hidden base class may be specified
946 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000947 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000948 // Look for a member, first.
949 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000950 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000951 = ClassDecl->lookup(MemberOrBase);
952 if (Result.first != Result.second)
953 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +0000954
Fariborz Jahanian302bb662009-06-30 23:26:25 +0000955 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +0000956
Eli Friedman8e1433b2009-07-29 19:44:27 +0000957 if (Member)
958 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
959 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +0000960 }
Douglas Gregore8381c02008-11-05 04:29:56 +0000961 // It didn't name a member, so see if it names a class.
Mike Stump11289f42009-09-09 15:08:12 +0000962 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +0000963 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregore8381c02008-11-05 04:29:56 +0000964 if (!BaseTy)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000965 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
966 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000967
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000968 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregore8381c02008-11-05 04:29:56 +0000969
Eli Friedman8e1433b2009-07-29 19:44:27 +0000970 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
971 RParenLoc, ClassDecl);
972}
973
John McCalle22a04a2009-11-04 23:02:40 +0000974/// Checks an initializer expression for use of uninitialized fields, such as
975/// containing the field that is being initialized. Returns true if there is an
976/// uninitialized field was used an updates the SourceLocation parameter; false
977/// otherwise.
978static bool InitExprContainsUninitializedFields(const Stmt* S,
979 const FieldDecl* LhsField,
980 SourceLocation* L) {
981 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
982 if (ME) {
983 const NamedDecl* RhsField = ME->getMemberDecl();
984 if (RhsField == LhsField) {
985 // Initializing a field with itself. Throw a warning.
986 // But wait; there are exceptions!
987 // Exception #1: The field may not belong to this record.
988 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
989 const Expr* base = ME->getBase();
990 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
991 // Even though the field matches, it does not belong to this record.
992 return false;
993 }
994 // None of the exceptions triggered; return true to indicate an
995 // uninitialized field was used.
996 *L = ME->getMemberLoc();
997 return true;
998 }
999 }
1000 bool found = false;
1001 for (Stmt::const_child_iterator it = S->child_begin();
1002 it != S->child_end() && found == false;
1003 ++it) {
1004 if (isa<CallExpr>(S)) {
1005 // Do not descend into function calls or constructors, as the use
1006 // of an uninitialized field may be valid. One would have to inspect
1007 // the contents of the function/ctor to determine if it is safe or not.
1008 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1009 // may be safe, depending on what the function/ctor does.
1010 continue;
1011 }
1012 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1013 }
1014 return found;
1015}
1016
Eli Friedman8e1433b2009-07-29 19:44:27 +00001017Sema::MemInitResult
1018Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1019 unsigned NumArgs, SourceLocation IdLoc,
1020 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001021 // Diagnose value-uses of fields to initialize themselves, e.g.
1022 // foo(foo)
1023 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001024 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001025 for (unsigned i = 0; i < NumArgs; ++i) {
1026 SourceLocation L;
1027 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1028 // FIXME: Return true in the case when other fields are used before being
1029 // uninitialized. For example, let this field be the i'th field. When
1030 // initializing the i'th field, throw a warning if any of the >= i'th
1031 // fields are used, as they are not yet initialized.
1032 // Right now we are only handling the case where the i'th field uses
1033 // itself in its initializer.
1034 Diag(L, diag::warn_field_is_uninit);
1035 }
1036 }
1037
Eli Friedman8e1433b2009-07-29 19:44:27 +00001038 bool HasDependentArg = false;
1039 for (unsigned i = 0; i < NumArgs; i++)
1040 HasDependentArg |= Args[i]->isTypeDependent();
1041
1042 CXXConstructorDecl *C = 0;
1043 QualType FieldType = Member->getType();
1044 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1045 FieldType = Array->getElementType();
1046 if (FieldType->isDependentType()) {
1047 // Can't check init for dependent type.
John McCallc90f6d72009-11-04 23:13:52 +00001048 } else if (FieldType->isRecordType()) {
1049 // Member is a record (struct/union/class), so pass the initializer
1050 // arguments down to the record's constructor.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001051 if (!HasDependentArg) {
1052 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1053
1054 C = PerformInitializationByConstructor(FieldType,
1055 MultiExprArg(*this,
1056 (void**)Args,
1057 NumArgs),
1058 IdLoc,
1059 SourceRange(IdLoc, RParenLoc),
1060 Member->getDeclName(), IK_Direct,
1061 ConstructorArgs);
1062
1063 if (C) {
1064 // Take over the constructor arguments as our own.
1065 NumArgs = ConstructorArgs.size();
1066 Args = (Expr **)ConstructorArgs.take();
1067 }
1068 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001069 } else if (NumArgs != 1 && NumArgs != 0) {
John McCallc90f6d72009-11-04 23:13:52 +00001070 // The member type is not a record type (or an array of record
1071 // types), so it can be only be default- or copy-initialized.
Mike Stump11289f42009-09-09 15:08:12 +00001072 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman8e1433b2009-07-29 19:44:27 +00001073 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
1074 } else if (!HasDependentArg) {
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001075 Expr *NewExp;
1076 if (NumArgs == 0) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001077 if (FieldType->isReferenceType()) {
1078 Diag(IdLoc, diag::err_null_intialized_reference_member)
1079 << Member->getDeclName();
1080 return Diag(Member->getLocation(), diag::note_declared_at);
1081 }
Fariborz Jahanianfc60ca82009-09-02 17:10:17 +00001082 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
1083 NumArgs = 1;
1084 }
1085 else
1086 NewExp = (Expr*)Args[0];
Eli Friedman8e1433b2009-07-29 19:44:27 +00001087 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
1088 return true;
1089 Args[0] = NewExp;
Douglas Gregore8381c02008-11-05 04:29:56 +00001090 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001091 // FIXME: Perform direct initialization of the member.
Mike Stump11289f42009-09-09 15:08:12 +00001092 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001093 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001094}
1095
1096Sema::MemInitResult
1097Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
1098 unsigned NumArgs, SourceLocation IdLoc,
1099 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
1100 bool HasDependentArg = false;
1101 for (unsigned i = 0; i < NumArgs; i++)
1102 HasDependentArg |= Args[i]->isTypeDependent();
1103
1104 if (!BaseType->isDependentType()) {
1105 if (!BaseType->isRecordType())
1106 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
1107 << BaseType << SourceRange(IdLoc, RParenLoc);
1108
1109 // C++ [class.base.init]p2:
1110 // [...] Unless the mem-initializer-id names a nonstatic data
1111 // member of the constructor’s class or a direct or virtual base
1112 // of that class, the mem-initializer is ill-formed. A
1113 // mem-initializer-list can initialize a base class using any
1114 // name that denotes that base class type.
Mike Stump11289f42009-09-09 15:08:12 +00001115
Eli Friedman8e1433b2009-07-29 19:44:27 +00001116 // First, check for a direct base class.
1117 const CXXBaseSpecifier *DirectBaseSpec = 0;
1118 for (CXXRecordDecl::base_class_const_iterator Base =
1119 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +00001120 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman8e1433b2009-07-29 19:44:27 +00001121 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
1122 // We found a direct base of this type. That's what we're
1123 // initializing.
1124 DirectBaseSpec = &*Base;
1125 break;
1126 }
1127 }
Mike Stump11289f42009-09-09 15:08:12 +00001128
Eli Friedman8e1433b2009-07-29 19:44:27 +00001129 // Check for a virtual base class.
1130 // FIXME: We might be able to short-circuit this if we know in advance that
1131 // there are no virtual bases.
1132 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1133 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1134 // We haven't found a base yet; search the class hierarchy for a
1135 // virtual base class.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1137 /*DetectVirtual=*/false);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001138 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001139 for (CXXBasePaths::paths_iterator Path = Paths.begin();
Eli Friedman8e1433b2009-07-29 19:44:27 +00001140 Path != Paths.end(); ++Path) {
1141 if (Path->back().Base->isVirtual()) {
1142 VirtualBaseSpec = Path->back().Base;
1143 break;
1144 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001145 }
1146 }
1147 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001148
1149 // C++ [base.class.init]p2:
1150 // If a mem-initializer-id is ambiguous because it designates both
1151 // a direct non-virtual base class and an inherited virtual base
1152 // class, the mem-initializer is ill-formed.
1153 if (DirectBaseSpec && VirtualBaseSpec)
1154 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
1155 << BaseType << SourceRange(IdLoc, RParenLoc);
1156 // C++ [base.class.init]p2:
1157 // Unless the mem-initializer-id names a nonstatic data membeer of the
1158 // constructor's class ot a direst or virtual base of that class, the
1159 // mem-initializer is ill-formed.
1160 if (!DirectBaseSpec && !VirtualBaseSpec)
1161 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
1162 << BaseType << ClassDecl->getNameAsCString()
1163 << SourceRange(IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001164 }
1165
Fariborz Jahanian0228bc12009-07-23 00:42:24 +00001166 CXXConstructorDecl *C = 0;
Eli Friedman8e1433b2009-07-29 19:44:27 +00001167 if (!BaseType->isDependentType() && !HasDependentArg) {
1168 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00001169 Context.getCanonicalType(BaseType).getUnqualifiedType());
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001170 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1171
1172 C = PerformInitializationByConstructor(BaseType,
1173 MultiExprArg(*this,
1174 (void**)Args, NumArgs),
Mike Stump11289f42009-09-09 15:08:12 +00001175 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00001176 Name, IK_Direct,
1177 ConstructorArgs);
1178 if (C) {
1179 // Take over the constructor arguments as our own.
1180 NumArgs = ConstructorArgs.size();
1181 Args = (Expr **)ConstructorArgs.take();
1182 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001183 }
1184
Mike Stump11289f42009-09-09 15:08:12 +00001185 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson1e172e02009-08-29 01:31:33 +00001186 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001187}
1188
Fariborz Jahanianca2f0852009-07-23 23:32:59 +00001189void
Anders Carlsson561f7932009-10-29 15:46:07 +00001190Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001191 CXXBaseOrMemberInitializer **Initializers,
1192 unsigned NumInitializers,
Eli Friedmand7686ef2009-11-09 01:05:47 +00001193 bool IsImplicitConstructor) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001194 // We need to build the initializer AST according to order of construction
1195 // and not what user specified in the Initializers list.
1196 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1197 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1198 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1199 bool HasDependentBaseInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001200
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001201 for (unsigned i = 0; i < NumInitializers; i++) {
1202 CXXBaseOrMemberInitializer *Member = Initializers[i];
1203 if (Member->isBaseInitializer()) {
1204 if (Member->getBaseClass()->isDependentType())
1205 HasDependentBaseInit = true;
1206 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1207 } else {
1208 AllBaseFields[Member->getMember()] = Member;
1209 }
1210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001212 if (HasDependentBaseInit) {
1213 // FIXME. This does not preserve the ordering of the initializers.
1214 // Try (with -Wreorder)
1215 // template<class X> struct A {};
Mike Stump11289f42009-09-09 15:08:12 +00001216 // template<class X> struct B : A<X> {
1217 // B() : x1(10), A<X>() {}
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001218 // int x1;
1219 // };
1220 // B<int> x;
1221 // On seeing one dependent type, we should essentially exit this routine
1222 // while preserving user-declared initializer list. When this routine is
1223 // called during instantiatiation process, this routine will rebuild the
John McCallc90f6d72009-11-04 23:13:52 +00001224 // ordered initializer list correctly.
Mike Stump11289f42009-09-09 15:08:12 +00001225
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001226 // If we have a dependent base initialization, we can't determine the
1227 // association between initializers and bases; just dump the known
1228 // initializers into the list, and don't try to deal with other bases.
1229 for (unsigned i = 0; i < NumInitializers; i++) {
1230 CXXBaseOrMemberInitializer *Member = Initializers[i];
1231 if (Member->isBaseInitializer())
1232 AllToInit.push_back(Member);
1233 }
1234 } else {
1235 // Push virtual bases before others.
1236 for (CXXRecordDecl::base_class_iterator VBase =
1237 ClassDecl->vbases_begin(),
1238 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1239 if (VBase->getType()->isDependentType())
1240 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001241 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001242 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001243 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001244 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001245 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001246 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1247 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001248 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001249 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001250 else {
Mike Stump11289f42009-09-09 15:08:12 +00001251 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001252 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001253 assert(VBaseDecl && "SetBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001254 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001255 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001256 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1257 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1258 << 0 << VBase->getType();
1259 Diag(VBaseDecl->getLocation(), diag::note_previous_class_decl)
1260 << Context.getTagDeclType(VBaseDecl);
Anders Carlsson561f7932009-10-29 15:46:07 +00001261 continue;
1262 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001263
Anders Carlsson561f7932009-10-29 15:46:07 +00001264 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1265 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1266 Constructor->getLocation(), CtorArgs))
1267 continue;
1268
1269 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1270
Mike Stump11289f42009-09-09 15:08:12 +00001271 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001272 new (Context) CXXBaseOrMemberInitializer(VBase->getType(),
1273 CtorArgs.takeAs<Expr>(),
1274 CtorArgs.size(), Ctor,
1275 SourceLocation(),
1276 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001277 AllToInit.push_back(Member);
1278 }
1279 }
Mike Stump11289f42009-09-09 15:08:12 +00001280
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001281 for (CXXRecordDecl::base_class_iterator Base =
1282 ClassDecl->bases_begin(),
1283 E = ClassDecl->bases_end(); Base != E; ++Base) {
1284 // Virtuals are in the virtual base list and already constructed.
1285 if (Base->isVirtual())
1286 continue;
1287 // Skip dependent types.
1288 if (Base->getType()->isDependentType())
1289 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001290 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001291 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump11289f42009-09-09 15:08:12 +00001292 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001293 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001294 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001295 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1296 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001297 AllToInit.push_back(Value);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001298 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001299 else {
Mike Stump11289f42009-09-09 15:08:12 +00001300 CXXRecordDecl *BaseDecl =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001301 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001302 assert(BaseDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001303 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
Anders Carlsson561f7932009-10-29 15:46:07 +00001304 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001305 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1306 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1307 << 0 << Base->getType();
1308 Diag(BaseDecl->getLocation(), diag::note_previous_class_decl)
1309 << Context.getTagDeclType(BaseDecl);
Anders Carlsson561f7932009-10-29 15:46:07 +00001310 continue;
1311 }
1312
1313 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1314 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1315 Constructor->getLocation(), CtorArgs))
1316 continue;
1317
1318 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001319
Mike Stump11289f42009-09-09 15:08:12 +00001320 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001321 new (Context) CXXBaseOrMemberInitializer(Base->getType(),
1322 CtorArgs.takeAs<Expr>(),
1323 CtorArgs.size(), Ctor,
1324 SourceLocation(),
1325 SourceLocation());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001326 AllToInit.push_back(Member);
1327 }
1328 }
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001331 // non-static data members.
1332 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1333 E = ClassDecl->field_end(); Field != E; ++Field) {
1334 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001335 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001336 Field->getType()->getAs<RecordType>()) {
1337 CXXRecordDecl *FieldClassDecl
1338 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001339 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001340 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1341 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1342 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1343 // set to the anonymous union data member used in the initializer
1344 // list.
1345 Value->setMember(*Field);
1346 Value->setAnonUnionMember(*FA);
1347 AllToInit.push_back(Value);
1348 break;
1349 }
1350 }
1351 }
1352 continue;
1353 }
1354 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001355 QualType FT = (*Field)->getType();
1356 if (const RecordType* RT = FT->getAs<RecordType>()) {
1357 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001358 assert(FieldRecDecl && "SetBaseOrMemberInitializers - BaseDecl null");
Mike Stump11289f42009-09-09 15:08:12 +00001359 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001360 FieldRecDecl->getDefaultConstructor(Context))
1361 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1362 }
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001363 AllToInit.push_back(Value);
1364 continue;
1365 }
Mike Stump11289f42009-09-09 15:08:12 +00001366
Eli Friedmand7686ef2009-11-09 01:05:47 +00001367 if ((*Field)->getType()->isDependentType())
Douglas Gregor2de8f412009-11-04 17:16:11 +00001368 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001369
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001370 QualType FT = Context.getBaseElementType((*Field)->getType());
1371 if (const RecordType* RT = FT->getAs<RecordType>()) {
1372 CXXConstructorDecl *Ctor =
1373 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
Douglas Gregor2de8f412009-11-04 17:16:11 +00001374 if (!Ctor) {
Eli Friedmand7686ef2009-11-09 01:05:47 +00001375 Diag(Constructor->getLocation(), diag::err_missing_default_ctor)
1376 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1377 << 1 << (*Field)->getDeclName();
1378 Diag(Field->getLocation(), diag::note_field_decl);
1379 Diag(RT->getDecl()->getLocation(), diag::note_previous_class_decl)
1380 << Context.getTagDeclType(RT->getDecl());
Anders Carlsson561f7932009-10-29 15:46:07 +00001381 continue;
1382 }
1383
1384 ASTOwningVector<&ActionBase::DeleteExpr> CtorArgs(*this);
1385 if (CompleteConstructorCall(Ctor, MultiExprArg(*this, 0, 0),
1386 Constructor->getLocation(), CtorArgs))
1387 continue;
1388
Mike Stump11289f42009-09-09 15:08:12 +00001389 CXXBaseOrMemberInitializer *Member =
Anders Carlsson561f7932009-10-29 15:46:07 +00001390 new (Context) CXXBaseOrMemberInitializer(*Field,CtorArgs.takeAs<Expr>(),
1391 CtorArgs.size(), Ctor,
1392 SourceLocation(),
1393 SourceLocation());
1394
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001395 AllToInit.push_back(Member);
Eli Friedmand7686ef2009-11-09 01:05:47 +00001396 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1397 if (FT.isConstQualified() && Ctor->isTrivial()) {
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001398 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001399 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1400 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001401 Diag((*Field)->getLocation(), diag::note_declared_at);
1402 }
1403 }
1404 else if (FT->isReferenceType()) {
1405 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001406 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1407 << 0 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001408 Diag((*Field)->getLocation(), diag::note_declared_at);
1409 }
1410 else if (FT.isConstQualified()) {
1411 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
Eli Friedmand7686ef2009-11-09 01:05:47 +00001412 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1413 << 1 << (*Field)->getDeclName();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001414 Diag((*Field)->getLocation(), diag::note_declared_at);
1415 }
1416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001418 NumInitializers = AllToInit.size();
1419 if (NumInitializers > 0) {
1420 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1421 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1422 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump11289f42009-09-09 15:08:12 +00001423
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001424 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1425 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1426 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1427 }
1428}
1429
Eli Friedman952c15d2009-07-21 19:28:10 +00001430static void *GetKeyForTopLevelField(FieldDecl *Field) {
1431 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001432 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001433 if (RT->getDecl()->isAnonymousStructOrUnion())
1434 return static_cast<void *>(RT->getDecl());
1435 }
1436 return static_cast<void *>(Field);
1437}
1438
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001439static void *GetKeyForBase(QualType BaseType) {
1440 if (const RecordType *RT = BaseType->getAs<RecordType>())
1441 return (void *)RT;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001443 assert(0 && "Unexpected base type!");
1444 return 0;
1445}
1446
Mike Stump11289f42009-09-09 15:08:12 +00001447static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001448 bool MemberMaybeAnon = false) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001449 // For fields injected into the class via declaration of an anonymous union,
1450 // use its anonymous union class declaration as the unique key.
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001451 if (Member->isMemberInitializer()) {
1452 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001453
Eli Friedmand7686ef2009-11-09 01:05:47 +00001454 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump11289f42009-09-09 15:08:12 +00001455 // data member of the class. Data member used in the initializer list is
Fariborz Jahanianb2197042009-08-11 18:49:54 +00001456 // in AnonUnionMember field.
1457 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1458 Field = Member->getAnonUnionMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00001459 if (Field->getDeclContext()->isRecord()) {
1460 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1461 if (RD->isAnonymousStructOrUnion())
1462 return static_cast<void *>(RD);
1463 }
1464 return static_cast<void *>(Field);
1465 }
Mike Stump11289f42009-09-09 15:08:12 +00001466
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001467 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman952c15d2009-07-21 19:28:10 +00001468}
1469
John McCallc90f6d72009-11-04 23:13:52 +00001470/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump11289f42009-09-09 15:08:12 +00001471void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001472 SourceLocation ColonLoc,
1473 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001474 if (!ConstructorDecl)
1475 return;
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001476
1477 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001478
1479 CXXConstructorDecl *Constructor
Douglas Gregor71a57182009-06-22 23:20:33 +00001480 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00001481
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001482 if (!Constructor) {
1483 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1484 return;
1485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001487 if (!Constructor->isDependentContext()) {
1488 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1489 bool err = false;
1490 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001491 CXXBaseOrMemberInitializer *Member =
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001492 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1493 void *KeyToMember = GetKeyForMember(Member);
1494 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1495 if (!PrevMember) {
1496 PrevMember = Member;
1497 continue;
1498 }
1499 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001500 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001501 diag::error_multiple_mem_initialization)
1502 << Field->getNameAsString();
1503 else {
1504 Type *BaseClass = Member->getBaseClass();
1505 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump11289f42009-09-09 15:08:12 +00001506 Diag(Member->getSourceLocation(),
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001507 diag::error_multiple_base_initialization)
John McCalla1925362009-09-29 23:03:30 +00001508 << QualType(BaseClass, 0);
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001509 }
1510 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1511 << 0;
1512 err = true;
1513 }
Mike Stump11289f42009-09-09 15:08:12 +00001514
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001515 if (err)
1516 return;
1517 }
Mike Stump11289f42009-09-09 15:08:12 +00001518
Eli Friedmand7686ef2009-11-09 01:05:47 +00001519 SetBaseOrMemberInitializers(Constructor,
Mike Stump11289f42009-09-09 15:08:12 +00001520 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Eli Friedmand7686ef2009-11-09 01:05:47 +00001521 NumMemInits, false);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001523 if (Constructor->isDependentContext())
1524 return;
Mike Stump11289f42009-09-09 15:08:12 +00001525
1526 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001527 Diagnostic::Ignored &&
Mike Stump11289f42009-09-09 15:08:12 +00001528 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlssone0eebb32009-08-27 05:45:01 +00001529 Diagnostic::Ignored)
1530 return;
Mike Stump11289f42009-09-09 15:08:12 +00001531
Anders Carlssone0eebb32009-08-27 05:45:01 +00001532 // Also issue warning if order of ctor-initializer list does not match order
1533 // of 1) base class declarations and 2) order of non-static data members.
1534 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump11289f42009-09-09 15:08:12 +00001535
Anders Carlssone0eebb32009-08-27 05:45:01 +00001536 CXXRecordDecl *ClassDecl
1537 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1538 // Push virtual bases before others.
1539 for (CXXRecordDecl::base_class_iterator VBase =
1540 ClassDecl->vbases_begin(),
1541 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001542 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001543
Anders Carlssone0eebb32009-08-27 05:45:01 +00001544 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1545 E = ClassDecl->bases_end(); Base != E; ++Base) {
1546 // Virtuals are alread in the virtual base list and are constructed
1547 // first.
1548 if (Base->isVirtual())
1549 continue;
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001550 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anders Carlssone0eebb32009-08-27 05:45:01 +00001553 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1554 E = ClassDecl->field_end(); Field != E; ++Field)
1555 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001556
Anders Carlssone0eebb32009-08-27 05:45:01 +00001557 int Last = AllBaseOrMembers.size();
1558 int curIndex = 0;
1559 CXXBaseOrMemberInitializer *PrevMember = 0;
1560 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump11289f42009-09-09 15:08:12 +00001561 CXXBaseOrMemberInitializer *Member =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001562 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1563 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman952c15d2009-07-21 19:28:10 +00001564
Anders Carlssone0eebb32009-08-27 05:45:01 +00001565 for (; curIndex < Last; curIndex++)
1566 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1567 break;
1568 if (curIndex == Last) {
1569 assert(PrevMember && "Member not in member list?!");
1570 // Initializer as specified in ctor-initializer list is out of order.
1571 // Issue a warning diagnostic.
1572 if (PrevMember->isBaseInitializer()) {
1573 // Diagnostics is for an initialized base class.
1574 Type *BaseClass = PrevMember->getBaseClass();
1575 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001576 diag::warn_base_initialized)
John McCalla1925362009-09-29 23:03:30 +00001577 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001578 } else {
1579 FieldDecl *Field = PrevMember->getMember();
1580 Diag(PrevMember->getSourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001581 diag::warn_field_initialized)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001582 << Field->getNameAsString();
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001583 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001584 // Also the note!
1585 if (FieldDecl *Field = Member->getMember())
Mike Stump11289f42009-09-09 15:08:12 +00001586 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001587 diag::note_fieldorbase_initialized_here) << 0
1588 << Field->getNameAsString();
1589 else {
1590 Type *BaseClass = Member->getBaseClass();
Mike Stump11289f42009-09-09 15:08:12 +00001591 Diag(Member->getSourceLocation(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001592 diag::note_fieldorbase_initialized_here) << 1
John McCalla1925362009-09-29 23:03:30 +00001593 << QualType(BaseClass, 0);
Anders Carlssone0eebb32009-08-27 05:45:01 +00001594 }
1595 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump11289f42009-09-09 15:08:12 +00001596 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001597 break;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001598 }
Anders Carlssone0eebb32009-08-27 05:45:01 +00001599 PrevMember = Member;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001600 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001601}
1602
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001603void
1604Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1605 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1606 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump11289f42009-09-09 15:08:12 +00001607
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001608 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1609 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1610 if (VBase->getType()->isDependentType())
1611 continue;
1612 // Skip over virtual bases which have trivial destructors.
1613 CXXRecordDecl *BaseClassDecl
1614 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1615 if (BaseClassDecl->hasTrivialDestructor())
1616 continue;
1617 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001618 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001619 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001620
1621 uintptr_t Member =
1622 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001623 | CXXDestructorDecl::VBASE;
1624 AllToDestruct.push_back(Member);
1625 }
1626 for (CXXRecordDecl::base_class_iterator Base =
1627 ClassDecl->bases_begin(),
1628 E = ClassDecl->bases_end(); Base != E; ++Base) {
1629 if (Base->isVirtual())
1630 continue;
1631 if (Base->getType()->isDependentType())
1632 continue;
1633 // Skip over virtual bases which have trivial destructors.
1634 CXXRecordDecl *BaseClassDecl
1635 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1636 if (BaseClassDecl->hasTrivialDestructor())
1637 continue;
1638 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001639 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001640 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump11289f42009-09-09 15:08:12 +00001641 uintptr_t Member =
1642 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001643 | CXXDestructorDecl::DRCTNONVBASE;
1644 AllToDestruct.push_back(Member);
1645 }
Mike Stump11289f42009-09-09 15:08:12 +00001646
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001647 // non-static data members.
1648 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1649 E = ClassDecl->field_end(); Field != E; ++Field) {
1650 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001651
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001652 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1653 // Skip over virtual bases which have trivial destructors.
1654 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1655 if (FieldClassDecl->hasTrivialDestructor())
1656 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001657 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001658 FieldClassDecl->getDestructor(Context))
Mike Stump11289f42009-09-09 15:08:12 +00001659 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001660 const_cast<CXXDestructorDecl*>(Dtor));
1661 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1662 AllToDestruct.push_back(Member);
1663 }
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001666 unsigned NumDestructions = AllToDestruct.size();
1667 if (NumDestructions > 0) {
1668 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump11289f42009-09-09 15:08:12 +00001669 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian37d06562009-09-03 23:18:17 +00001670 new (Context) uintptr_t [NumDestructions];
1671 // Insert in reverse order.
1672 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1673 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1674 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1675 }
1676}
1677
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00001678void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001679 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001680 return;
Mike Stump11289f42009-09-09 15:08:12 +00001681
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001682 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001683
1684 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00001685 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Eli Friedmand7686ef2009-11-09 01:05:47 +00001686 SetBaseOrMemberInitializers(Constructor, 0, 0, false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00001687}
1688
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001689namespace {
1690 /// PureVirtualMethodCollector - traverses a class and its superclasses
1691 /// and determines if it has any pure virtual methods.
1692 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1693 ASTContext &Context;
1694
Sebastian Redlb7d64912009-03-22 21:28:55 +00001695 public:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001696 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redlb7d64912009-03-22 21:28:55 +00001697
1698 private:
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001699 MethodList Methods;
Mike Stump11289f42009-09-09 15:08:12 +00001700
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001701 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump11289f42009-09-09 15:08:12 +00001702
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001703 public:
Mike Stump11289f42009-09-09 15:08:12 +00001704 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001705 : Context(Ctx) {
Mike Stump11289f42009-09-09 15:08:12 +00001706
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001707 MethodList List;
1708 Collect(RD, List);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001710 // Copy the temporary list to methods, and make sure to ignore any
1711 // null entries.
1712 for (size_t i = 0, e = List.size(); i != e; ++i) {
1713 if (List[i])
1714 Methods.push_back(List[i]);
Mike Stump11289f42009-09-09 15:08:12 +00001715 }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001718 bool empty() const { return Methods.empty(); }
Mike Stump11289f42009-09-09 15:08:12 +00001719
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001720 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1721 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001722 };
Mike Stump11289f42009-09-09 15:08:12 +00001723
1724 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001725 MethodList& Methods) {
1726 // First, collect the pure virtual methods for the base classes.
1727 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1728 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001729 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner85e2e142009-03-29 05:01:10 +00001730 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001731 if (BaseDecl && BaseDecl->isAbstract())
1732 Collect(BaseDecl, Methods);
1733 }
1734 }
Mike Stump11289f42009-09-09 15:08:12 +00001735
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001736 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson3c012712009-05-17 00:00:05 +00001737 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Anders Carlsson3c012712009-05-17 00:00:05 +00001739 MethodSetTy OverriddenMethods;
1740 size_t MethodsSize = Methods.size();
1741
Mike Stump11289f42009-09-09 15:08:12 +00001742 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson3c012712009-05-17 00:00:05 +00001743 i != e; ++i) {
1744 // Traverse the record, looking for methods.
1745 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl86be8542009-07-07 20:29:57 +00001746 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson700179432009-10-18 19:34:08 +00001747 if (MD->isPure())
Anders Carlsson3c012712009-05-17 00:00:05 +00001748 Methods.push_back(MD);
Mike Stump11289f42009-09-09 15:08:12 +00001749
Anders Carlsson700179432009-10-18 19:34:08 +00001750 // Record all the overridden methods in our set.
Anders Carlsson3c012712009-05-17 00:00:05 +00001751 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1752 E = MD->end_overridden_methods(); I != E; ++I) {
1753 // Keep track of the overridden methods.
1754 OverriddenMethods.insert(*I);
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001755 }
1756 }
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
1759 // Now go through the methods and zero out all the ones we know are
Anders Carlsson3c012712009-05-17 00:00:05 +00001760 // overridden.
1761 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1762 if (OverriddenMethods.count(Methods[i]))
1763 Methods[i] = 0;
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001766 }
1767}
Douglas Gregore8381c02008-11-05 04:29:56 +00001768
Anders Carlssoneabf7702009-08-27 00:13:57 +00001769
Mike Stump11289f42009-09-09 15:08:12 +00001770bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001771 unsigned DiagID, AbstractDiagSelID SelID,
1772 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00001773 if (SelID == -1)
1774 return RequireNonAbstractType(Loc, T,
1775 PDiag(DiagID), CurrentRD);
1776 else
1777 return RequireNonAbstractType(Loc, T,
1778 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001779}
1780
Anders Carlssoneabf7702009-08-27 00:13:57 +00001781bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1782 const PartialDiagnostic &PD,
1783 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001784 if (!getLangOptions().CPlusPlus)
1785 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001786
Anders Carlssoneb0c5322009-03-23 19:10:31 +00001787 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001788 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001789 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001791 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001792 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001793 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001794 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00001795
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001796 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00001797 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00001798 }
Mike Stump11289f42009-09-09 15:08:12 +00001799
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001800 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001801 if (!RT)
1802 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001803
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001804 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1805 if (!RD)
1806 return false;
1807
Anders Carlssonb57738b2009-03-24 17:23:42 +00001808 if (CurrentRD && CurrentRD != RD)
1809 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001810
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001811 if (!RD->isAbstract())
1812 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Anders Carlssoneabf7702009-08-27 00:13:57 +00001814 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00001815
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001816 // Check if we've already emitted the list of pure virtual functions for this
1817 // class.
1818 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1819 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001821 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001822
1823 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001824 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1825 const CXXMethodDecl *MD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001826
1827 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001828 MD->getDeclName();
1829 }
1830
1831 if (!PureVirtualClassDiagSet)
1832 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1833 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Anders Carlsson576cc6f2009-03-22 20:18:17 +00001835 return true;
1836}
1837
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001838namespace {
Mike Stump11289f42009-09-09 15:08:12 +00001839 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001840 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1841 Sema &SemaRef;
1842 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00001843
Anders Carlssonb57738b2009-03-24 17:23:42 +00001844 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001845 bool Invalid = false;
1846
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001847 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1848 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001849 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00001850
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001851 return Invalid;
1852 }
Mike Stump11289f42009-09-09 15:08:12 +00001853
Anders Carlssonb57738b2009-03-24 17:23:42 +00001854 public:
1855 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1856 : SemaRef(SemaRef), AbstractClass(ac) {
1857 Visit(SemaRef.Context.getTranslationUnitDecl());
1858 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001859
Anders Carlssonb57738b2009-03-24 17:23:42 +00001860 bool VisitFunctionDecl(const FunctionDecl *FD) {
1861 if (FD->isThisDeclarationADefinition()) {
1862 // No need to do the check if we're in a definition, because it requires
1863 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00001864 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00001865 return VisitDeclContext(FD);
1866 }
Mike Stump11289f42009-09-09 15:08:12 +00001867
Anders Carlssonb57738b2009-03-24 17:23:42 +00001868 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00001869 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00001870 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00001871 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1872 diag::err_abstract_type_in_decl,
1873 Sema::AbstractReturnType,
1874 AbstractClass);
1875
Mike Stump11289f42009-09-09 15:08:12 +00001876 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00001877 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001878 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00001879 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001880 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001881 VD->getOriginalType(),
1882 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00001883 Sema::AbstractParamType,
1884 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001885 }
1886
1887 return Invalid;
1888 }
Mike Stump11289f42009-09-09 15:08:12 +00001889
Anders Carlssonb57738b2009-03-24 17:23:42 +00001890 bool VisitDecl(const Decl* D) {
1891 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1892 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00001893
Anders Carlssonb57738b2009-03-24 17:23:42 +00001894 return false;
1895 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00001896 };
1897}
1898
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001899void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00001900 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001901 SourceLocation LBrac,
1902 SourceLocation RBrac) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001903 if (!TagDecl)
1904 return;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregorc9f9b862009-05-11 19:58:34 +00001906 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001907 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00001908 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar15619c72008-10-03 02:03:53 +00001909 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor463421d2009-03-03 04:44:36 +00001910
Chris Lattner83f095c2009-03-28 19:18:32 +00001911 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001912 if (!RD->isAbstract()) {
1913 // Collect all the pure virtual methods and see if this is an abstract
1914 // class after all.
1915 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001916 if (!Collector.empty())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001917 RD->setAbstract(true);
1918 }
Mike Stump11289f42009-09-09 15:08:12 +00001919
1920 if (RD->isAbstract())
Anders Carlssonb57738b2009-03-24 17:23:42 +00001921 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregor3c74d412009-10-14 20:14:33 +00001923 if (!RD->isDependentType() && !RD->isInvalidDecl())
Anders Carlsson7cbd8fb2009-03-22 01:52:17 +00001924 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001925}
1926
Douglas Gregor05379422008-11-03 17:51:48 +00001927/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1928/// special functions, such as the default constructor, copy
1929/// constructor, or destructor, to the given C++ class (C++
1930/// [special]p1). This routine can only be executed just before the
1931/// definition of the class is complete.
1932void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00001933 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00001934 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00001935
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001936 // FIXME: Implicit declarations have exception specifications, which are
1937 // the union of the specifications of the implicitly called functions.
1938
Douglas Gregor05379422008-11-03 17:51:48 +00001939 if (!ClassDecl->hasUserDeclaredConstructor()) {
1940 // C++ [class.ctor]p5:
1941 // A default constructor for a class X is a constructor of class X
1942 // that can be called without an argument. If there is no
1943 // user-declared constructor for class X, a default constructor is
1944 // implicitly declared. An implicitly-declared default constructor
1945 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00001946 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00001947 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00001948 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00001949 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00001950 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00001951 Context.getFunctionType(Context.VoidTy,
1952 0, 0, false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00001953 /*DInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00001954 /*isExplicit=*/false,
1955 /*isInline=*/true,
1956 /*isImplicitlyDeclared=*/true);
1957 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00001958 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00001959 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001960 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00001961 }
1962
1963 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1964 // C++ [class.copy]p4:
1965 // If the class definition does not explicitly declare a copy
1966 // constructor, one is declared implicitly.
1967
1968 // C++ [class.copy]p5:
1969 // The implicitly-declared copy constructor for a class X will
1970 // have the form
1971 //
1972 // X::X(const X&)
1973 //
1974 // if
1975 bool HasConstCopyConstructor = true;
1976
1977 // -- each direct or virtual base class B of X has a copy
1978 // constructor whose first parameter is of type const B& or
1979 // const volatile B&, and
1980 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1981 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1982 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001983 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001984 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00001985 = BaseClassDecl->hasConstCopyConstructor(Context);
1986 }
1987
1988 // -- for all the nonstatic data members of X that are of a
1989 // class type M (or array thereof), each such class type
1990 // has a copy constructor whose first parameter is of type
1991 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1993 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001994 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00001995 QualType FieldType = (*Field)->getType();
1996 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1997 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001998 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001999 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002000 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002001 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002002 = FieldClassDecl->hasConstCopyConstructor(Context);
2003 }
2004 }
2005
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002006 // Otherwise, the implicitly declared copy constructor will have
2007 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002008 //
2009 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002010 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002011 if (HasConstCopyConstructor)
2012 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002013 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002014
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002015 // An implicitly-declared copy constructor is an inline public
2016 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002017 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002018 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002019 CXXConstructorDecl *CopyConstructor
2020 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002021 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002022 Context.getFunctionType(Context.VoidTy,
2023 &ArgType, 1,
2024 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 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002030 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002031 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002032
2033 // Add the parameter to the constructor.
2034 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2035 ClassDecl->getLocation(),
2036 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002037 ArgType, /*DInfo=*/0,
2038 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002039 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002040 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002041 }
2042
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002043 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2044 // Note: The following rules are largely analoguous to the copy
2045 // constructor rules. Note that virtual bases are not taken into account
2046 // for determining the argument type of the operator. Note also that
2047 // operators taking an object instead of a reference are allowed.
2048 //
2049 // C++ [class.copy]p10:
2050 // If the class definition does not explicitly declare a copy
2051 // assignment operator, one is declared implicitly.
2052 // The implicitly-defined copy assignment operator for a class X
2053 // will have the form
2054 //
2055 // X& X::operator=(const X&)
2056 //
2057 // if
2058 bool HasConstCopyAssignment = true;
2059
2060 // -- each direct base class B of X has a copy assignment operator
2061 // whose parameter is of type const B&, const volatile B& or B,
2062 // and
2063 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2064 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002065 assert(!Base->getType()->isDependentType() &&
2066 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002067 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002068 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002069 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002070 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002071 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002072 }
2073
2074 // -- for all the nonstatic data members of X that are of a class
2075 // type M (or array thereof), each such class type has a copy
2076 // assignment operator whose parameter is of type const M&,
2077 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002078 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2079 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002080 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002081 QualType FieldType = (*Field)->getType();
2082 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2083 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002085 const CXXRecordDecl *FieldClassDecl
2086 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002087 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002088 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002089 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002090 }
2091 }
2092
2093 // Otherwise, the implicitly declared copy assignment operator will
2094 // have the form
2095 //
2096 // X& X::operator=(X&)
2097 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002098 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002099 if (HasConstCopyAssignment)
2100 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002101 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002102
2103 // An implicitly-declared copy assignment operator is an inline public
2104 // member of its class.
2105 DeclarationName Name =
2106 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2107 CXXMethodDecl *CopyAssignment =
2108 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2109 Context.getFunctionType(RetType, &ArgType, 1,
2110 false, 0),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002111 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002112 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002113 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002114 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002115 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002116
2117 // Add the parameter to the operator.
2118 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2119 ClassDecl->getLocation(),
2120 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002121 ArgType, /*DInfo=*/0,
2122 VarDecl::None, 0);
Ted Kremenek4ba36fc2009-01-14 00:42:25 +00002123 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002124
2125 // Don't call addedAssignmentOperator. There is no way to distinguish an
2126 // implicit from an explicit assignment operator.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002127 ClassDecl->addDecl(CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002128 }
2129
Douglas Gregor1349b452008-12-15 21:24:18 +00002130 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002131 // C++ [class.dtor]p2:
2132 // If a class has no user-declared destructor, a destructor is
2133 // declared implicitly. An implicitly-declared destructor is an
2134 // inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002135 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002136 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002137 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002138 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002139 ClassDecl->getLocation(), Name,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002140 Context.getFunctionType(Context.VoidTy,
2141 0, 0, false, 0),
2142 /*isInline=*/true,
2143 /*isImplicitlyDeclared=*/true);
2144 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002145 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002146 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002147 ClassDecl->addDecl(Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002148 }
Douglas Gregor05379422008-11-03 17:51:48 +00002149}
2150
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002151void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002152 Decl *D = TemplateD.getAs<Decl>();
2153 if (!D)
2154 return;
2155
2156 TemplateParameterList *Params = 0;
2157 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2158 Params = Template->getTemplateParameters();
2159 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2160 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2161 Params = PartialSpec->getTemplateParameters();
2162 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002163 return;
2164
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002165 for (TemplateParameterList::iterator Param = Params->begin(),
2166 ParamEnd = Params->end();
2167 Param != ParamEnd; ++Param) {
2168 NamedDecl *Named = cast<NamedDecl>(*Param);
2169 if (Named->getDeclName()) {
2170 S->AddDecl(DeclPtrTy::make(Named));
2171 IdResolver.AddDecl(Named);
2172 }
2173 }
2174}
2175
Douglas Gregor4d87df52008-12-16 21:30:33 +00002176/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2177/// parsing a top-level (non-nested) C++ class, and we are now
2178/// parsing those parts of the given Method declaration that could
2179/// not be parsed earlier (C++ [class.mem]p2), such as default
2180/// arguments. This action should enter the scope of the given
2181/// Method declaration as if we had just parsed the qualified method
2182/// name. However, it should not bring the parameters into scope;
2183/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002184void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002185 if (!MethodD)
2186 return;
Mike Stump11289f42009-09-09 15:08:12 +00002187
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002188 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002189
Douglas Gregor4d87df52008-12-16 21:30:33 +00002190 CXXScopeSpec SS;
Chris Lattner83f095c2009-03-28 19:18:32 +00002191 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +00002192 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002193 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2194 SS.setScopeRep(
2195 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002196 ActOnCXXEnterDeclaratorScope(S, SS);
2197}
2198
2199/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2200/// C++ method declaration. We're (re-)introducing the given
2201/// function parameter into scope for use in parsing later parts of
2202/// the method declaration. For example, we could see an
2203/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002204void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002205 if (!ParamD)
2206 return;
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattner83f095c2009-03-28 19:18:32 +00002208 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002209
2210 // If this parameter has an unparsed default argument, clear it out
2211 // to make way for the parsed default argument.
2212 if (Param->hasUnparsedDefaultArg())
2213 Param->setDefaultArg(0);
2214
Chris Lattner83f095c2009-03-28 19:18:32 +00002215 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002216 if (Param->getDeclName())
2217 IdResolver.AddDecl(Param);
2218}
2219
2220/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2221/// processing the delayed method declaration for Method. The method
2222/// declaration is now considered finished. There may be a separate
2223/// ActOnStartOfFunctionDef action later (not necessarily
2224/// immediately!) for this method, if it was also defined inside the
2225/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002226void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002227 if (!MethodD)
2228 return;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002230 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattner83f095c2009-03-28 19:18:32 +00002232 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002233 CXXScopeSpec SS;
Mike Stump11289f42009-09-09 15:08:12 +00002234 QualType ClassTy
Douglas Gregorf21eb492009-03-26 23:50:42 +00002235 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
2236 SS.setScopeRep(
2237 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002238 ActOnCXXExitDeclaratorScope(S, SS);
2239
2240 // Now that we have our default arguments, check the constructor
2241 // again. It could produce additional diagnostics or affect whether
2242 // the class has implicitly-declared destructors, among other
2243 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002244 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2245 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002246
2247 // Check the default arguments, which we may have added.
2248 if (!Method->isInvalidDecl())
2249 CheckCXXDefaultArguments(Method);
2250}
2251
Douglas Gregor831c93f2008-11-05 20:51:48 +00002252/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002253/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002254/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002255/// emit diagnostics and set the invalid bit to true. In any case, the type
2256/// will be updated to reflect a well-formed type for the constructor and
2257/// returned.
2258QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2259 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002260 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002261
2262 // C++ [class.ctor]p3:
2263 // A constructor shall not be virtual (10.3) or static (9.4). A
2264 // constructor can be invoked for a const, volatile or const
2265 // volatile object. A constructor shall not be declared const,
2266 // volatile, or const volatile (9.3.2).
2267 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002268 if (!D.isInvalidType())
2269 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2270 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2271 << SourceRange(D.getIdentifierLoc());
2272 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002273 }
2274 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002275 if (!D.isInvalidType())
2276 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2277 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2278 << SourceRange(D.getIdentifierLoc());
2279 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002280 SC = FunctionDecl::None;
2281 }
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattner38378bf2009-04-25 08:28:21 +00002283 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2284 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002285 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002286 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2287 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002288 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002289 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2290 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002291 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002292 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2293 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002294 }
Mike Stump11289f42009-09-09 15:08:12 +00002295
Douglas Gregor831c93f2008-11-05 20:51:48 +00002296 // Rebuild the function type "R" without any type qualifiers (in
2297 // case any of the errors above fired) and with "void" as the
2298 // return type, since constructors don't have return types. We
2299 // *always* have to do this, because GetTypeForDeclarator will
2300 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002301 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002302 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2303 Proto->getNumArgs(),
2304 Proto->isVariadic(), 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002305}
2306
Douglas Gregor4d87df52008-12-16 21:30:33 +00002307/// CheckConstructor - Checks a fully-formed constructor for
2308/// well-formedness, issuing any diagnostics required. Returns true if
2309/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002310void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002311 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002312 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2313 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002314 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002315
2316 // C++ [class.copy]p3:
2317 // A declaration of a constructor for a class X is ill-formed if
2318 // its first parameter is of type (optionally cv-qualified) X and
2319 // either there are no other parameters or else all other
2320 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002321 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002322 ((Constructor->getNumParams() == 1) ||
2323 (Constructor->getNumParams() > 1 &&
Anders Carlsson85446472009-06-06 04:14:07 +00002324 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002325 QualType ParamType = Constructor->getParamDecl(0)->getType();
2326 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2327 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002328 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2329 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor578dae52009-04-02 01:08:08 +00002330 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002331 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002332 }
2333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
Douglas Gregor4d87df52008-12-16 21:30:33 +00002335 // Notify the class that we've added a constructor.
2336 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002337}
2338
Mike Stump11289f42009-09-09 15:08:12 +00002339static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002340FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2341 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2342 FTI.ArgInfo[0].Param &&
2343 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2344}
2345
Douglas Gregor831c93f2008-11-05 20:51:48 +00002346/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2347/// the well-formednes of the destructor declarator @p D with type @p
2348/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002349/// emit diagnostics and set the declarator to invalid. Even if this happens,
2350/// will be updated to reflect a well-formed type for the destructor and
2351/// returned.
2352QualType Sema::CheckDestructorDeclarator(Declarator &D,
2353 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002354 // C++ [class.dtor]p1:
2355 // [...] A typedef-name that names a class is a class-name
2356 // (7.1.3); however, a typedef-name that names a class shall not
2357 // be used as the identifier in the declarator for a destructor
2358 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002359 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002360 if (isa<TypedefType>(DeclaratorType)) {
2361 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002362 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002363 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002364 }
2365
2366 // C++ [class.dtor]p2:
2367 // A destructor is used to destroy objects of its class type. A
2368 // destructor takes no parameters, and no return type can be
2369 // specified for it (not even void). The address of a destructor
2370 // shall not be taken. A destructor shall not be static. A
2371 // destructor can be invoked for a const, volatile or const
2372 // volatile object. A destructor shall not be declared const,
2373 // volatile or const volatile (9.3.2).
2374 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002375 if (!D.isInvalidType())
2376 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2377 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2378 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002379 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002380 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002381 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002382 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002383 // Destructors don't have return types, but the parser will
2384 // happily parse something like:
2385 //
2386 // class X {
2387 // float ~X();
2388 // };
2389 //
2390 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002391 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2392 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2393 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002394 }
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattner38378bf2009-04-25 08:28:21 +00002396 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2397 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002398 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002399 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2400 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002401 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002402 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2403 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002404 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002405 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2406 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002407 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002408 }
2409
2410 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002411 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002412 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2413
2414 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002415 FTI.freeArgs();
2416 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002417 }
2418
Mike Stump11289f42009-09-09 15:08:12 +00002419 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002420 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002421 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002422 D.setInvalidType();
2423 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002424
2425 // Rebuild the function type "R" without any type qualifiers or
2426 // parameters (in case any of the errors above fired) and with
2427 // "void" as the return type, since destructors don't have return
2428 // types. We *always* have to do this, because GetTypeForDeclarator
2429 // will put in a result type of "int" when none was specified.
Chris Lattner38378bf2009-04-25 08:28:21 +00002430 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002431}
2432
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002433/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2434/// well-formednes of the conversion function declarator @p D with
2435/// type @p R. If there are any errors in the declarator, this routine
2436/// will emit diagnostics and return true. Otherwise, it will return
2437/// false. Either way, the type @p R will be updated to reflect a
2438/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002439void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002440 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002441 // C++ [class.conv.fct]p1:
2442 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002443 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002444 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002445 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002446 if (!D.isInvalidType())
2447 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2448 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2449 << SourceRange(D.getIdentifierLoc());
2450 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002451 SC = FunctionDecl::None;
2452 }
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002453 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002454 // Conversion functions don't have return types, but the parser will
2455 // happily parse something like:
2456 //
2457 // class X {
2458 // float operator bool();
2459 // };
2460 //
2461 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00002462 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2463 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2464 << SourceRange(D.getIdentifierLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002465 }
2466
2467 // Make sure we don't have any parameters.
John McCall9dd450b2009-09-21 23:43:11 +00002468 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002469 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2470
2471 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00002472 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002473 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002474 }
2475
Mike Stump11289f42009-09-09 15:08:12 +00002476 // Make sure the conversion function isn't variadic.
John McCall9dd450b2009-09-21 23:43:11 +00002477 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002478 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002479 D.setInvalidType();
2480 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002481
2482 // C++ [class.conv.fct]p4:
2483 // The conversion-type-id shall not represent a function type nor
2484 // an array type.
Douglas Gregor7861a802009-11-03 01:35:08 +00002485 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002486 if (ConvType->isArrayType()) {
2487 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2488 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002489 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002490 } else if (ConvType->isFunctionType()) {
2491 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2492 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002493 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002494 }
2495
2496 // Rebuild the function type "R" without any parameters (in case any
2497 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00002498 // return type.
2499 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall9dd450b2009-09-21 23:43:11 +00002500 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002501
Douglas Gregor5fb53972009-01-14 15:45:31 +00002502 // C++0x explicit conversion operators.
2503 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00002504 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002505 diag::warn_explicit_conversion_functions)
2506 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002507}
2508
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002509/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2510/// the declaration of the given C++ conversion function. This routine
2511/// is responsible for recording the conversion function in the C++
2512/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00002513Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002514 assert(Conversion && "Expected to receive a conversion function declaration");
2515
Douglas Gregor4287b372008-12-12 08:25:50 +00002516 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002517
2518 // Make sure we aren't redeclaring the conversion function.
2519 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002520
2521 // C++ [class.conv.fct]p1:
2522 // [...] A conversion function is never used to convert a
2523 // (possibly cv-qualified) object to the (possibly cv-qualified)
2524 // same object type (or a reference to it), to a (possibly
2525 // cv-qualified) base class of that type (or a reference to it),
2526 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00002527 // FIXME: Suppress this warning if the conversion function ends up being a
2528 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00002529 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002530 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002531 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002532 ConvType = ConvTypeRef->getPointeeType();
2533 if (ConvType->isRecordType()) {
2534 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2535 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002536 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002537 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002538 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002539 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002540 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002541 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00002542 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002543 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002544 }
2545
Douglas Gregor1dc98262008-12-26 15:00:45 +00002546 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002547 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump11289f42009-09-09 15:08:12 +00002548 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002549 = Conversion->getDescribedFunctionTemplate())
2550 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor1dc98262008-12-26 15:00:45 +00002551 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00002552 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor1dc98262008-12-26 15:00:45 +00002553 Conv = Conversions->function_begin(),
2554 ConvEnd = Conversions->function_end();
2555 Conv != ConvEnd; ++Conv) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002556 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor1dc98262008-12-26 15:00:45 +00002557 *Conv = Conversion;
Chris Lattner83f095c2009-03-28 19:18:32 +00002558 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00002559 }
2560 }
2561 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00002562 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00002563 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002564 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00002565 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00002566 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002567
Chris Lattner83f095c2009-03-28 19:18:32 +00002568 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002569}
2570
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002571//===----------------------------------------------------------------------===//
2572// Namespace Handling
2573//===----------------------------------------------------------------------===//
2574
2575/// ActOnStartNamespaceDef - This is called at the start of a namespace
2576/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00002577Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2578 SourceLocation IdentLoc,
2579 IdentifierInfo *II,
2580 SourceLocation LBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002581 NamespaceDecl *Namespc =
2582 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2583 Namespc->setLBracLoc(LBrace);
2584
2585 Scope *DeclRegionScope = NamespcScope->getParent();
2586
2587 if (II) {
2588 // C++ [namespace.def]p2:
2589 // The identifier in an original-namespace-definition shall not have been
2590 // previously defined in the declarative region in which the
2591 // original-namespace-definition appears. The identifier in an
2592 // original-namespace-definition is the name of the namespace. Subsequently
2593 // in that declarative region, it is treated as an original-namespace-name.
2594
John McCall9f3059a2009-10-09 21:13:30 +00002595 NamedDecl *PrevDecl
2596 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName, true);
Mike Stump11289f42009-09-09 15:08:12 +00002597
Douglas Gregor91f84212008-12-11 16:49:14 +00002598 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2599 // This is an extended namespace definition.
2600 // Attach this namespace decl to the chain of extended namespace
2601 // definitions.
2602 OrigNS->setNextNamespace(Namespc);
2603 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002604
Mike Stump11289f42009-09-09 15:08:12 +00002605 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002606 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00002607 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00002608 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002609 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002610 } else if (PrevDecl) {
2611 // This is an invalid name redefinition.
2612 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2613 << Namespc->getDeclName();
2614 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2615 Namespc->setInvalidDecl();
2616 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00002617 } else if (II->isStr("std") &&
2618 CurContext->getLookupContext()->isTranslationUnit()) {
2619 // This is the first "real" definition of the namespace "std", so update
2620 // our cache of the "std" namespace to point at this definition.
2621 if (StdNamespace) {
2622 // We had already defined a dummy namespace "std". Link this new
2623 // namespace definition to the dummy namespace "std".
2624 StdNamespace->setNextNamespace(Namespc);
2625 StdNamespace->setLocation(IdentLoc);
2626 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2627 }
2628
2629 // Make our StdNamespace cache point at the first real definition of the
2630 // "std" namespace.
2631 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00002632 }
Douglas Gregor91f84212008-12-11 16:49:14 +00002633
2634 PushOnScopeChains(Namespc, DeclRegionScope);
2635 } else {
John McCall4fa53422009-10-01 00:25:31 +00002636 // Anonymous namespaces.
2637
2638 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2639 // behaves as if it were replaced by
2640 // namespace unique { /* empty body */ }
2641 // using namespace unique;
2642 // namespace unique { namespace-body }
2643 // where all occurrences of 'unique' in a translation unit are
2644 // replaced by the same identifier and this identifier differs
2645 // from all other identifiers in the entire program.
2646
2647 // We just create the namespace with an empty name and then add an
2648 // implicit using declaration, just like the standard suggests.
2649 //
2650 // CodeGen enforces the "universally unique" aspect by giving all
2651 // declarations semantically contained within an anonymous
2652 // namespace internal linkage.
2653
2654 assert(Namespc->isAnonymousNamespace());
2655 CurContext->addDecl(Namespc);
2656
2657 UsingDirectiveDecl* UD
2658 = UsingDirectiveDecl::Create(Context, CurContext,
2659 /* 'using' */ LBrace,
2660 /* 'namespace' */ SourceLocation(),
2661 /* qualifier */ SourceRange(),
2662 /* NNS */ NULL,
2663 /* identifier */ SourceLocation(),
2664 Namespc,
2665 /* Ancestor */ CurContext);
2666 UD->setImplicit();
2667 CurContext->addDecl(UD);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002668 }
2669
2670 // Although we could have an invalid decl (i.e. the namespace name is a
2671 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00002672 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2673 // for the namespace has the declarations that showed up in that particular
2674 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00002675 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002676 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002677}
2678
2679/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2680/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00002681void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2682 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002683 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2684 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2685 Namespc->setRBracLoc(RBrace);
2686 PopDeclContext();
2687}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002688
Chris Lattner83f095c2009-03-28 19:18:32 +00002689Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2690 SourceLocation UsingLoc,
2691 SourceLocation NamespcLoc,
2692 const CXXScopeSpec &SS,
2693 SourceLocation IdentLoc,
2694 IdentifierInfo *NamespcName,
2695 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00002696 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2697 assert(NamespcName && "Invalid NamespcName.");
2698 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002699 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00002700
Douglas Gregor889ceb72009-02-03 19:21:40 +00002701 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00002702
Douglas Gregor34074322009-01-14 22:20:51 +00002703 // Lookup namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002704 LookupResult R;
2705 LookupParsedName(R, S, &SS, NamespcName, LookupNamespaceName, false);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002706 if (R.isAmbiguous()) {
2707 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002708 return DeclPtrTy();
Douglas Gregor889ceb72009-02-03 19:21:40 +00002709 }
John McCall9f3059a2009-10-09 21:13:30 +00002710 if (!R.empty()) {
2711 NamedDecl *NS = R.getFoundDecl();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002712 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00002713 // C++ [namespace.udir]p1:
2714 // A using-directive specifies that the names in the nominated
2715 // namespace can be used in the scope in which the
2716 // using-directive appears after the using-directive. During
2717 // unqualified name lookup (3.4.1), the names appear as if they
2718 // were declared in the nearest enclosing namespace which
2719 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00002720 // namespace. [Note: in this context, "contains" means "contains
2721 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00002722
2723 // Find enclosing context containing both using-directive and
2724 // nominated namespace.
2725 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2726 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2727 CommonAncestor = CommonAncestor->getParent();
2728
Mike Stump11289f42009-09-09 15:08:12 +00002729 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002730 CurContext, UsingLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002731 NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00002732 SS.getRange(),
2733 (NestedNameSpecifier *)SS.getScopeRep(),
2734 IdentLoc,
Douglas Gregor889ceb72009-02-03 19:21:40 +00002735 cast<NamespaceDecl>(NS),
2736 CommonAncestor);
2737 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00002738 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00002739 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00002740 }
2741
Douglas Gregor889ceb72009-02-03 19:21:40 +00002742 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00002743 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00002744 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002745}
2746
2747void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2748 // If scope has associated entity, then using directive is at namespace
2749 // or translation unit scope. We add UsingDirectiveDecls, into
2750 // it's lookup structure.
2751 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002752 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00002753 else
2754 // Otherwise it is block-sope. using-directives will affect lookup
2755 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00002756 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00002757}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00002758
Douglas Gregorfec52632009-06-20 00:51:54 +00002759
2760Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00002761 AccessSpecifier AS,
Anders Carlsson59140b32009-08-28 03:16:11 +00002762 SourceLocation UsingLoc,
2763 const CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00002764 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00002765 AttributeList *AttrList,
2766 bool IsTypeName) {
Douglas Gregorfec52632009-06-20 00:51:54 +00002767 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00002768
Douglas Gregor220f4272009-11-04 16:30:06 +00002769 switch (Name.getKind()) {
2770 case UnqualifiedId::IK_Identifier:
2771 case UnqualifiedId::IK_OperatorFunctionId:
2772 case UnqualifiedId::IK_ConversionFunctionId:
2773 break;
2774
2775 case UnqualifiedId::IK_ConstructorName:
2776 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
2777 << SS.getRange();
2778 return DeclPtrTy();
2779
2780 case UnqualifiedId::IK_DestructorName:
2781 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
2782 << SS.getRange();
2783 return DeclPtrTy();
2784
2785 case UnqualifiedId::IK_TemplateId:
2786 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
2787 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
2788 return DeclPtrTy();
2789 }
2790
2791 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
2792 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS,
2793 Name.getSourceRange().getBegin(),
2794 TargetName, AttrList, IsTypeName);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002795 if (UD) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00002796 PushOnScopeChains(UD, S);
Anders Carlsson7b194b72009-08-29 19:54:19 +00002797 UD->setAccess(AS);
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Anders Carlsson696a3f12009-08-28 05:40:36 +00002800 return DeclPtrTy::make(UD);
2801}
2802
2803NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2804 const CXXScopeSpec &SS,
2805 SourceLocation IdentLoc,
2806 DeclarationName Name,
2807 AttributeList *AttrList,
2808 bool IsTypeName) {
2809 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2810 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00002811
Anders Carlssonf038fc22009-08-28 05:49:21 +00002812 // FIXME: We ignore attributes for now.
2813 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00002814
Anders Carlsson59140b32009-08-28 03:16:11 +00002815 if (SS.isEmpty()) {
2816 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002817 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
2820 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00002821 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2822
Anders Carlssonf038fc22009-08-28 05:49:21 +00002823 if (isUnknownSpecialization(SS)) {
2824 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2825 SS.getRange(), NNS,
2826 IdentLoc, Name, IsTypeName);
2827 }
Mike Stump11289f42009-09-09 15:08:12 +00002828
Anders Carlsson59140b32009-08-28 03:16:11 +00002829 DeclContext *LookupContext = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002830
Anders Carlsson59140b32009-08-28 03:16:11 +00002831 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2832 // C++0x N2914 [namespace.udecl]p3:
2833 // A using-declaration used as a member-declaration shall refer to a member
2834 // of a base class of the class being defined, shall refer to a member of an
2835 // anonymous union that is a member of a base class of the class being
Mike Stump11289f42009-09-09 15:08:12 +00002836 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlsson59140b32009-08-28 03:16:11 +00002837 // a member of a base class of the class being defined.
2838 const Type *Ty = NNS->getAsType();
2839 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2840 Diag(SS.getRange().getBegin(),
2841 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2842 << NNS << RD->getDeclName();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002843 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002844 }
Anders Carlsson4bd78752009-08-28 15:18:15 +00002845
2846 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2847 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlsson59140b32009-08-28 03:16:11 +00002848 } else {
2849 // C++0x N2914 [namespace.udecl]p8:
2850 // A using-declaration for a class member shall be a member-declaration.
2851 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002852 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlsson59140b32009-08-28 03:16:11 +00002853 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002854 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002855 }
Mike Stump11289f42009-09-09 15:08:12 +00002856
Anders Carlsson59140b32009-08-28 03:16:11 +00002857 // C++0x N2914 [namespace.udecl]p9:
2858 // In a using-declaration, a prefix :: refers to the global namespace.
2859 if (NNS->getKind() == NestedNameSpecifier::Global)
2860 LookupContext = Context.getTranslationUnitDecl();
2861 else
2862 LookupContext = NNS->getAsNamespace();
2863 }
2864
2865
Douglas Gregorfec52632009-06-20 00:51:54 +00002866 // Lookup target name.
John McCall9f3059a2009-10-09 21:13:30 +00002867 LookupResult R;
2868 LookupQualifiedName(R, LookupContext, Name, LookupOrdinaryName);
Mike Stump11289f42009-09-09 15:08:12 +00002869
John McCall9f3059a2009-10-09 21:13:30 +00002870 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00002871 Diag(IdentLoc, diag::err_no_member)
2872 << Name << LookupContext << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002873 return 0;
Douglas Gregorfec52632009-06-20 00:51:54 +00002874 }
2875
John McCall9f3059a2009-10-09 21:13:30 +00002876 // FIXME: handle ambiguity?
2877 NamedDecl *ND = R.getAsSingleDecl(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002878
Anders Carlsson59140b32009-08-28 03:16:11 +00002879 if (IsTypeName && !isa<TypeDecl>(ND)) {
2880 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlsson696a3f12009-08-28 05:40:36 +00002881 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00002882 }
2883
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002884 // C++0x N2914 [namespace.udecl]p6:
2885 // A using-declaration shall not name a namespace.
2886 if (isa<NamespaceDecl>(ND)) {
2887 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2888 << SS.getRange();
Anders Carlsson696a3f12009-08-28 05:40:36 +00002889 return 0;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00002890 }
Mike Stump11289f42009-09-09 15:08:12 +00002891
Anders Carlsson696a3f12009-08-28 05:40:36 +00002892 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2893 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregorfec52632009-06-20 00:51:54 +00002894}
2895
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002896/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2897/// is a namespace alias, returns the namespace it points to.
2898static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2899 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2900 return AD->getNamespace();
2901 return dyn_cast_or_null<NamespaceDecl>(D);
2902}
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002905 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002906 SourceLocation AliasLoc,
2907 IdentifierInfo *Alias,
2908 const CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00002909 SourceLocation IdentLoc,
2910 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00002911
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002912 // Lookup the namespace name.
John McCall9f3059a2009-10-09 21:13:30 +00002913 LookupResult R;
2914 LookupParsedName(R, S, &SS, Ident, LookupNamespaceName, false);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002915
Anders Carlssondca83c42009-03-28 06:23:46 +00002916 // Check if we have a previous declaration with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002917 if (NamedDecl *PrevDecl
2918 = LookupSingleName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002919 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00002920 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002921 // namespace, so don't create a new one.
John McCall9f3059a2009-10-09 21:13:30 +00002922 if (!R.isAmbiguous() && !R.empty() &&
2923 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00002924 return DeclPtrTy();
2925 }
Mike Stump11289f42009-09-09 15:08:12 +00002926
Anders Carlssondca83c42009-03-28 06:23:46 +00002927 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2928 diag::err_redefinition_different_kind;
2929 Diag(AliasLoc, DiagID) << Alias;
2930 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00002931 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00002932 }
2933
Anders Carlssonac2c9652009-03-28 06:42:02 +00002934 if (R.isAmbiguous()) {
Anders Carlsson47952ae2009-03-28 22:53:22 +00002935 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner83f095c2009-03-28 19:18:32 +00002936 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002937 }
Mike Stump11289f42009-09-09 15:08:12 +00002938
John McCall9f3059a2009-10-09 21:13:30 +00002939 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00002940 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00002941 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002944 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00002945 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2946 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00002947 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00002948 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002949
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002950 CurContext->addDecl(AliasDecl);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00002951 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00002952}
2953
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002954void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2955 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00002956 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2957 !Constructor->isUsed()) &&
2958 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00002959
Eli Friedmand7686ef2009-11-09 01:05:47 +00002960 SetBaseOrMemberInitializers(Constructor, 0, 0, true);
2961
2962 Constructor->setUsed();
2963 return;
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00002964}
2965
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002966void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00002967 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002968 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2969 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump11289f42009-09-09 15:08:12 +00002970
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002971 CXXRecordDecl *ClassDecl
2972 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2973 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2974 // C++ [class.dtor] p5
Mike Stump11289f42009-09-09 15:08:12 +00002975 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002976 // implicitly defined, all the implicitly-declared default destructors
2977 // for its base class and its non-static data members shall have been
2978 // implicitly defined.
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002979 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2980 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002981 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002982 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002983 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00002984 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002985 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2986 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2987 else
Mike Stump11289f42009-09-09 15:08:12 +00002988 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002989 "DefineImplicitDestructor - missing dtor in a base class");
2990 }
2991 }
Mike Stump11289f42009-09-09 15:08:12 +00002992
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00002993 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2994 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002995 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2996 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2997 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002998 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00002999 CXXRecordDecl *FieldClassDecl
3000 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3001 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump11289f42009-09-09 15:08:12 +00003002 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003003 const_cast<CXXDestructorDecl*>(
3004 FieldClassDecl->getDestructor(Context)))
3005 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3006 else
Mike Stump11289f42009-09-09 15:08:12 +00003007 assert(false &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003008 "DefineImplicitDestructor - missing dtor in class of a data member");
3009 }
3010 }
3011 }
3012 Destructor->setUsed();
3013}
3014
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003015void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3016 CXXMethodDecl *MethodDecl) {
3017 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3018 MethodDecl->getOverloadedOperator() == OO_Equal &&
3019 !MethodDecl->isUsed()) &&
3020 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump11289f42009-09-09 15:08:12 +00003021
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003022 CXXRecordDecl *ClassDecl
3023 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00003024
Fariborz Jahanianebe772e2009-06-26 16:08:57 +00003025 // C++[class.copy] p12
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003026 // Before the implicitly-declared copy assignment operator for a class is
3027 // implicitly defined, all implicitly-declared copy assignment operators
3028 // for its direct base classes and its nonstatic data members shall have
3029 // been implicitly defined.
3030 bool err = false;
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003031 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3032 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003033 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003034 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003035 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003036 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
3037 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3038 }
Fariborz Jahanian5f12b532009-06-30 16:36:53 +00003039 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3040 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003041 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3042 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3043 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003044 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003045 CXXRecordDecl *FieldClassDecl
3046 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003047 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003048 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
3049 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump12b8ce12009-08-04 21:02:39 +00003050 } else if (FieldType->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003051 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003052 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3053 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003054 Diag(CurrentLocation, diag::note_first_required_here);
3055 err = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00003056 } else if (FieldType.isConstQualified()) {
Mike Stump11289f42009-09-09 15:08:12 +00003057 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson17973e62009-07-09 17:47:25 +00003058 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3059 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003060 Diag(CurrentLocation, diag::note_first_required_here);
3061 err = true;
3062 }
3063 }
3064 if (!err)
Mike Stump11289f42009-09-09 15:08:12 +00003065 MethodDecl->setUsed();
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003066}
3067
3068CXXMethodDecl *
3069Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
3070 CXXRecordDecl *ClassDecl) {
3071 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3072 QualType RHSType(LHSType);
3073 // If class's assignment operator argument is const/volatile qualified,
Mike Stump11289f42009-09-09 15:08:12 +00003074 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003075 // operator = (B&).
John McCall8ccfcb52009-09-24 19:53:00 +00003076 RHSType = Context.getCVRQualifiedType(RHSType,
3077 ParmDecl->getType().getCVRQualifiers());
Mike Stump11289f42009-09-09 15:08:12 +00003078 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3079 LHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003080 SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +00003081 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3082 RHSType,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003083 SourceLocation()));
3084 Expr *Args[2] = { &*LHS, &*RHS };
3085 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003086 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003087 CandidateSet);
3088 OverloadCandidateSet::iterator Best;
Mike Stump11289f42009-09-09 15:08:12 +00003089 if (BestViableFunction(CandidateSet,
Fariborz Jahanian41f79272009-06-25 21:45:19 +00003090 ClassDecl->getLocation(), Best) == OR_Success)
3091 return cast<CXXMethodDecl>(Best->Function);
3092 assert(false &&
3093 "getAssignOperatorMethod - copy assignment operator method not found");
3094 return 0;
3095}
3096
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003097void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3098 CXXConstructorDecl *CopyConstructor,
3099 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00003100 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003101 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
3102 !CopyConstructor->isUsed()) &&
3103 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00003104
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003105 CXXRecordDecl *ClassDecl
3106 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3107 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003108 // C++ [class.copy] p209
Mike Stump11289f42009-09-09 15:08:12 +00003109 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003110 // implicitly defined, all the implicitly-declared copy constructors
3111 // for its base class and its non-static data members shall have been
3112 // implicitly defined.
3113 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3114 Base != ClassDecl->bases_end(); ++Base) {
3115 CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003116 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003117 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003118 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003119 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003120 }
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003121 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3122 FieldEnd = ClassDecl->field_end();
3123 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003124 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3125 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3126 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003127 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003128 CXXRecordDecl *FieldClassDecl
3129 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003130 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003131 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00003132 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian477d2422009-06-22 23:34:40 +00003133 }
3134 }
3135 CopyConstructor->setUsed();
3136}
3137
Anders Carlsson6eb55572009-08-25 05:12:04 +00003138Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003139Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00003140 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003141 MultiExprArg ExprArgs) {
Anders Carlsson250aada2009-08-16 05:13:48 +00003142 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00003143
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003144 // C++ [class.copy]p15:
3145 // Whenever a temporary class object is copied using a copy constructor, and
3146 // this object and the copy have the same cv-unqualified type, an
3147 // implementation is permitted to treat the original and the copy as two
3148 // different ways of referring to the same object and not perform a copy at
3149 // all, even if the class copy constructor or destructor have side effects.
Mike Stump11289f42009-09-09 15:08:12 +00003150
Anders Carlsson250aada2009-08-16 05:13:48 +00003151 // FIXME: Is this enough?
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003152 if (Constructor->isCopyConstructor(Context)) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003153 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson250aada2009-08-16 05:13:48 +00003154 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3155 E = BE->getSubExpr();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003156 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3157 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3158 E = ICE->getSubExpr();
3159
Anders Carlsson250aada2009-08-16 05:13:48 +00003160 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
3161 Elidable = true;
3162 }
Mike Stump11289f42009-09-09 15:08:12 +00003163
3164 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003165 Elidable, move(ExprArgs));
Anders Carlsson250aada2009-08-16 05:13:48 +00003166}
3167
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003168/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3169/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00003170Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00003171Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3172 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003173 MultiExprArg ExprArgs) {
3174 unsigned NumExprs = ExprArgs.size();
3175 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003176
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003177 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
3178 Elidable, Exprs, NumExprs));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003179}
3180
Anders Carlsson574315a2009-08-27 05:08:22 +00003181Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00003182Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3183 QualType Ty,
3184 SourceLocation TyBeginLoc,
Anders Carlsson574315a2009-08-27 05:08:22 +00003185 MultiExprArg Args,
3186 SourceLocation RParenLoc) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003187 unsigned NumExprs = Args.size();
3188 Expr **Exprs = (Expr **)Args.release();
Mike Stump11289f42009-09-09 15:08:12 +00003189
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003190 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3191 TyBeginLoc, Exprs,
3192 NumExprs, RParenLoc));
Anders Carlsson574315a2009-08-27 05:08:22 +00003193}
3194
3195
Mike Stump11289f42009-09-09 15:08:12 +00003196bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00003197 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003198 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00003199 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003200 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00003201 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003202 if (TempResult.isInvalid())
3203 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003204
Anders Carlsson6eb55572009-08-25 05:12:04 +00003205 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00003206 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniand460cb42009-08-05 18:17:32 +00003207 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00003208 VD->setInit(Context, Temp);
Mike Stump11289f42009-09-09 15:08:12 +00003209
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003210 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00003211}
3212
Mike Stump11289f42009-09-09 15:08:12 +00003213void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003214 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003215 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003216 if (!ClassDecl->hasTrivialDestructor())
Mike Stump11289f42009-09-09 15:08:12 +00003217 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003218 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahanian67828442009-08-03 19:13:25 +00003219 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00003220}
3221
Mike Stump11289f42009-09-09 15:08:12 +00003222/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003223/// ActOnDeclarator, when a C++ direct initializer is present.
3224/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00003225void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
3226 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003227 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003228 SourceLocation *CommaLocs,
3229 SourceLocation RParenLoc) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003230 unsigned NumExprs = Exprs.size();
3231 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00003232 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003233
3234 // If there is no declaration, there was an error parsing it. Just ignore
3235 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00003236 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003237 return;
Mike Stump11289f42009-09-09 15:08:12 +00003238
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003239 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3240 if (!VDecl) {
3241 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3242 RealDecl->setInvalidDecl();
3243 return;
3244 }
3245
Douglas Gregor402250f2009-08-26 21:14:46 +00003246 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003247 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003248 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3249 //
3250 // Clients that want to distinguish between the two forms, can check for
3251 // direct initializer using VarDecl::hasCXXDirectInitializer().
3252 // A major benefit is that clients that don't particularly care about which
3253 // exactly form was it (like the CodeGen) can handle both cases without
3254 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003255
Douglas Gregor402250f2009-08-26 21:14:46 +00003256 // If either the declaration has a dependent type or if any of the expressions
3257 // is type-dependent, we represent the initialization via a ParenListExpr for
3258 // later use during template instantiation.
3259 if (VDecl->getType()->isDependentType() ||
3260 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3261 // Let clients know that initialization was done with a direct initializer.
3262 VDecl->setCXXDirectInitializer(true);
Mike Stump11289f42009-09-09 15:08:12 +00003263
Douglas Gregor402250f2009-08-26 21:14:46 +00003264 // Store the initialization expressions as a ParenListExpr.
3265 unsigned NumExprs = Exprs.size();
Mike Stump11289f42009-09-09 15:08:12 +00003266 VDecl->setInit(Context,
Douglas Gregor402250f2009-08-26 21:14:46 +00003267 new (Context) ParenListExpr(Context, LParenLoc,
3268 (Expr **)Exprs.release(),
3269 NumExprs, RParenLoc));
3270 return;
3271 }
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregor402250f2009-08-26 21:14:46 +00003273
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003274 // C++ 8.5p11:
3275 // The form of initialization (using parentheses or '=') is generally
3276 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003277 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003278 QualType DeclInitType = VDecl->getType();
3279 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00003280 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003281
Douglas Gregor4044d992009-03-24 16:43:20 +00003282 // FIXME: This isn't the right place to complete the type.
3283 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3284 diag::err_typecheck_decl_incomplete_type)) {
3285 VDecl->setInvalidDecl();
3286 return;
3287 }
3288
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003289 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003290 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3291
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003292 CXXConstructorDecl *Constructor
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003293 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003294 move(Exprs),
Douglas Gregor6f543152008-11-05 15:29:30 +00003295 VDecl->getLocation(),
3296 SourceRange(VDecl->getLocation(),
3297 RParenLoc),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003298 VDecl->getDeclName(),
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003299 IK_Direct,
3300 ConstructorArgs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003301 if (!Constructor)
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003302 RealDecl->setInvalidDecl();
Anders Carlsson332ef552009-04-15 21:48:18 +00003303 else {
Anders Carlsson332ef552009-04-15 21:48:18 +00003304 VDecl->setCXXDirectInitializer(true);
Fariborz Jahanian57277c52009-10-28 18:41:06 +00003305 if (InitializeVarWithConstructor(VDecl, Constructor,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003306 move_arg(ConstructorArgs)))
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00003307 RealDecl->setInvalidDecl();
Fariborz Jahanian67828442009-08-03 19:13:25 +00003308 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson332ef552009-04-15 21:48:18 +00003309 }
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00003310 return;
3311 }
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003312
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003313 if (NumExprs > 1) {
Chris Lattnerf490e152008-11-19 05:27:50 +00003314 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3315 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003316 RealDecl->setInvalidDecl();
3317 return;
3318 }
3319
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003320 // Let clients know that initialization was done with a direct initializer.
3321 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00003322
3323 assert(NumExprs == 1 && "Expected 1 expression");
3324 // Set the init expression, handles conversions.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003325 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3326 /*DirectInit=*/true);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003327}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003328
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003329/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3330/// may occur as part of direct-initialization or copy-initialization.
3331///
3332/// \param ClassType the type of the object being initialized, which must have
3333/// class type.
3334///
3335/// \param ArgsPtr the arguments provided to initialize the object
3336///
3337/// \param Loc the source location where the initialization occurs
3338///
3339/// \param Range the source range that covers the entire initialization
3340///
3341/// \param InitEntity the name of the entity being initialized, if known
3342///
3343/// \param Kind the type of initialization being performed
3344///
3345/// \param ConvertedArgs a vector that will be filled in with the
3346/// appropriately-converted arguments to the constructor (if initialization
3347/// succeeded).
3348///
3349/// \returns the constructor used to initialize the object, if successful.
3350/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003351CXXConstructorDecl *
Douglas Gregor6f543152008-11-05 15:29:30 +00003352Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003353 MultiExprArg ArgsPtr,
Douglas Gregor6f543152008-11-05 15:29:30 +00003354 SourceLocation Loc, SourceRange Range,
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003355 DeclarationName InitEntity,
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003356 InitializationKind Kind,
3357 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003358 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003359 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003360 Expr **Args = (Expr **)ArgsPtr.get();
3361 unsigned NumArgs = ArgsPtr.size();
3362
Mike Stump11289f42009-09-09 15:08:12 +00003363 // C++ [dcl.init]p14:
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003364 // If the initialization is direct-initialization, or if it is
3365 // copy-initialization where the cv-unqualified version of the
3366 // source type is the same class as, or a derived class of, the
3367 // class of the destination, constructors are considered. The
3368 // applicable constructors are enumerated (13.3.1.3), and the
3369 // best one is chosen through overload resolution (13.3). The
3370 // constructor so selected is called to initialize the object,
3371 // with the initializer expression(s) as its argument(s). If no
3372 // constructor applies, or the overload resolution is ambiguous,
3373 // the initialization is ill-formed.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003374 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3375 OverloadCandidateSet CandidateSet;
Douglas Gregor6f543152008-11-05 15:29:30 +00003376
3377 // Add constructors to the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00003378 DeclarationName ConstructorName
Douglas Gregor1349b452008-12-15 21:24:18 +00003379 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor4100db62009-11-08 07:12:55 +00003380 Context.getCanonicalType(ClassType).getUnqualifiedType());
Douglas Gregor55297ac2008-12-23 00:26:44 +00003381 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003382 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00003383 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003384 // Find the constructor (which may be a template).
3385 CXXConstructorDecl *Constructor = 0;
3386 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3387 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003388 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003389 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3390 else
3391 Constructor = cast<CXXConstructorDecl>(*Con);
3392
Douglas Gregor6f543152008-11-05 15:29:30 +00003393 if ((Kind == IK_Direct) ||
Mike Stump11289f42009-09-09 15:08:12 +00003394 (Kind == IK_Copy &&
Anders Carlssond20e7952009-08-28 16:57:08 +00003395 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003396 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3397 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003398 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003399 Args, NumArgs, CandidateSet);
3400 else
3401 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3402 }
Douglas Gregor6f543152008-11-05 15:29:30 +00003403 }
3404
Douglas Gregor1349b452008-12-15 21:24:18 +00003405 // FIXME: When we decide not to synthesize the implicitly-declared
3406 // constructors, we'll need to make them appear here.
3407
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003408 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003409 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003410 case OR_Success:
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003411 // We found a constructor. Break out so that we can convert the arguments
3412 // appropriately.
3413 break;
Mike Stump11289f42009-09-09 15:08:12 +00003414
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003415 case OR_No_Viable_Function:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003416 if (InitEntity)
3417 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003418 << InitEntity << Range;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003419 else
3420 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner45d9d602009-02-17 07:29:20 +00003421 << ClassType << Range;
Sebastian Redl15b02d22008-11-22 13:44:36 +00003422 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003423 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003424
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003425 case OR_Ambiguous:
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00003426 if (InitEntity)
3427 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3428 else
3429 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003430 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3431 return 0;
Douglas Gregor171c45a2009-02-18 21:56:37 +00003432
3433 case OR_Deleted:
3434 if (InitEntity)
3435 Diag(Loc, diag::err_ovl_deleted_init)
3436 << Best->Function->isDeleted()
3437 << InitEntity << Range;
3438 else
3439 Diag(Loc, diag::err_ovl_deleted_init)
3440 << Best->Function->isDeleted()
3441 << InitEntity << Range;
3442 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3443 return 0;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003444 }
Mike Stump11289f42009-09-09 15:08:12 +00003445
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003446 // Convert the arguments, fill in default arguments, etc.
3447 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3448 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3449 return 0;
3450
3451 return Constructor;
3452}
3453
3454/// \brief Given a constructor and the set of arguments provided for the
3455/// constructor, convert the arguments and add any required default arguments
3456/// to form a proper call to this constructor.
3457///
3458/// \returns true if an error occurred, false otherwise.
3459bool
3460Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3461 MultiExprArg ArgsPtr,
3462 SourceLocation Loc,
3463 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3464 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3465 unsigned NumArgs = ArgsPtr.size();
3466 Expr **Args = (Expr **)ArgsPtr.get();
3467
3468 const FunctionProtoType *Proto
3469 = Constructor->getType()->getAs<FunctionProtoType>();
3470 assert(Proto && "Constructor without a prototype?");
3471 unsigned NumArgsInProto = Proto->getNumArgs();
3472 unsigned NumArgsToCheck = NumArgs;
3473
3474 // If too few arguments are available, we'll fill in the rest with defaults.
3475 if (NumArgs < NumArgsInProto) {
3476 NumArgsToCheck = NumArgsInProto;
3477 ConvertedArgs.reserve(NumArgsInProto);
3478 } else {
3479 ConvertedArgs.reserve(NumArgs);
3480 if (NumArgs > NumArgsInProto)
3481 NumArgsToCheck = NumArgsInProto;
3482 }
3483
3484 // Convert arguments
3485 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3486 QualType ProtoArgType = Proto->getArgType(i);
3487
3488 Expr *Arg;
3489 if (i < NumArgs) {
3490 Arg = Args[i];
Anders Carlssonc8bfc462009-09-15 21:14:33 +00003491
3492 // Pass the argument.
3493 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3494 return true;
3495
3496 Args[i] = 0;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003497 } else {
3498 ParmVarDecl *Param = Constructor->getParamDecl(i);
3499
3500 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3501 if (DefArg.isInvalid())
3502 return true;
3503
3504 Arg = DefArg.takeAs<Expr>();
3505 }
3506
3507 ConvertedArgs.push_back(Arg);
3508 }
3509
3510 // If this is a variadic call, handle args passed through "...".
3511 if (Proto->isVariadic()) {
3512 // Promote the arguments (C99 6.5.2.2p7).
3513 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3514 Expr *Arg = Args[i];
3515 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3516 return true;
3517
3518 ConvertedArgs.push_back(Arg);
3519 Args[i] = 0;
3520 }
3521 }
3522
3523 return false;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00003524}
3525
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003526/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3527/// determine whether they are reference-related,
3528/// reference-compatible, reference-compatible with added
3529/// qualification, or incompatible, for use in C++ initialization by
3530/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3531/// type, and the first type (T1) is the pointee type of the reference
3532/// type being initialized.
Mike Stump11289f42009-09-09 15:08:12 +00003533Sema::ReferenceCompareResult
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003534Sema::CompareReferenceRelationship(SourceLocation Loc,
3535 QualType OrigT1, QualType OrigT2,
Douglas Gregor786ab212008-10-29 02:00:59 +00003536 bool& DerivedToBase) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003537 assert(!OrigT1->isReferenceType() &&
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003538 "T1 must be the pointee type of the reference type");
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003539 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003540
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003541 QualType T1 = Context.getCanonicalType(OrigT1);
3542 QualType T2 = Context.getCanonicalType(OrigT2);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003543 QualType UnqualT1 = T1.getUnqualifiedType();
3544 QualType UnqualT2 = T2.getUnqualifiedType();
3545
3546 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003547 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump11289f42009-09-09 15:08:12 +00003548 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003549 // T1 is a base class of T2.
Douglas Gregor786ab212008-10-29 02:00:59 +00003550 if (UnqualT1 == UnqualT2)
3551 DerivedToBase = false;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003552 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
3553 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
3554 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor786ab212008-10-29 02:00:59 +00003555 DerivedToBase = true;
3556 else
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003557 return Ref_Incompatible;
3558
3559 // At this point, we know that T1 and T2 are reference-related (at
3560 // least).
3561
3562 // C++ [dcl.init.ref]p4:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003563 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003564 // reference-related to T2 and cv1 is the same cv-qualification
3565 // as, or greater cv-qualification than, cv2. For purposes of
3566 // overload resolution, cases for which cv1 is greater
3567 // cv-qualification than cv2 are identified as
3568 // reference-compatible with added qualification (see 13.3.3.2).
3569 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3570 return Ref_Compatible;
3571 else if (T1.isMoreQualifiedThan(T2))
3572 return Ref_Compatible_With_Added_Qualification;
3573 else
3574 return Ref_Related;
3575}
3576
3577/// CheckReferenceInit - Check the initialization of a reference
3578/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3579/// the initializer (either a simple initializer or an initializer
Douglas Gregor23a1f192008-10-29 23:31:03 +00003580/// list), and DeclType is the type of the declaration. When ICS is
3581/// non-null, this routine will compute the implicit conversion
3582/// sequence according to C++ [over.ics.ref] and will not produce any
3583/// diagnostics; when ICS is null, it will emit diagnostics when any
3584/// errors are found. Either way, a return value of true indicates
3585/// that there was a failure, a return value of false indicates that
3586/// the reference initialization succeeded.
Douglas Gregor2fe98832008-11-03 19:09:14 +00003587///
3588/// When @p SuppressUserConversions, user-defined conversions are
3589/// suppressed.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003590/// When @p AllowExplicit, we also permit explicit user-defined
3591/// conversion functions.
Sebastian Redl42e92c42009-04-12 17:16:29 +00003592/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump11289f42009-09-09 15:08:12 +00003593bool
Sebastian Redl1a99f442009-04-16 17:51:27 +00003594Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00003595 SourceLocation DeclLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003596 bool SuppressUserConversions,
Anders Carlsson271e3a42009-08-27 17:30:43 +00003597 bool AllowExplicit, bool ForceRValue,
3598 ImplicitConversionSequence *ICS) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003599 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3600
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003601 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003602 QualType T2 = Init->getType();
3603
Douglas Gregorcd695e52008-11-10 20:40:00 +00003604 // If the initializer is the address of an overloaded function, try
3605 // to resolve the overloaded function. If all goes well, T2 is the
3606 // type of the resulting function.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003607 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump11289f42009-09-09 15:08:12 +00003608 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00003609 ICS != 0);
3610 if (Fn) {
3611 // Since we're performing this reference-initialization for
3612 // real, update the initializer with the resulting function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003613 if (!ICS) {
Douglas Gregorc809cc22009-09-23 23:04:10 +00003614 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003615 return true;
3616
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00003617 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor171c45a2009-02-18 21:56:37 +00003618 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00003619
3620 T2 = Fn->getType();
3621 }
3622 }
3623
Douglas Gregor786ab212008-10-29 02:00:59 +00003624 // Compute some basic properties of the types and the initializer.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003625 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor786ab212008-10-29 02:00:59 +00003626 bool DerivedToBase = false;
Sebastian Redl42e92c42009-04-12 17:16:29 +00003627 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3628 Init->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003629 ReferenceCompareResult RefRelationship
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003630 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor786ab212008-10-29 02:00:59 +00003631
3632 // Most paths end in a failed conversion.
3633 if (ICS)
3634 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003635
3636 // C++ [dcl.init.ref]p5:
Eli Friedman44b83ee2009-08-05 19:21:58 +00003637 // A reference to type "cv1 T1" is initialized by an expression
3638 // of type "cv2 T2" as follows:
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003639
3640 // -- If the initializer expression
3641
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003642 // Rvalue references cannot bind to lvalues (N2812).
3643 // There is absolutely no situation where they can. In particular, note that
3644 // this is ill-formed, even if B has a user-defined conversion to A&&:
3645 // B b;
3646 // A&& r = b;
3647 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3648 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003649 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003650 << Init->getSourceRange();
3651 return true;
3652 }
3653
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003654 bool BindsDirectly = false;
Eli Friedman44b83ee2009-08-05 19:21:58 +00003655 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3656 // reference-compatible with "cv2 T2," or
Douglas Gregor786ab212008-10-29 02:00:59 +00003657 //
3658 // Note that the bit-field check is skipped if we are just computing
3659 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor71235ec2009-05-02 02:18:30 +00003660 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003661 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003662 BindsDirectly = true;
3663
Douglas Gregor786ab212008-10-29 02:00:59 +00003664 if (ICS) {
3665 // C++ [over.ics.ref]p1:
3666 // When a parameter of reference type binds directly (8.5.3)
3667 // to an argument expression, the implicit conversion sequence
3668 // is the identity conversion, unless the argument expression
3669 // has a type that is a derived class of the parameter type,
3670 // in which case the implicit conversion sequence is a
3671 // derived-to-base Conversion (13.3.3.1).
3672 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3673 ICS->Standard.First = ICK_Identity;
3674 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3675 ICS->Standard.Third = ICK_Identity;
3676 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3677 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003678 ICS->Standard.ReferenceBinding = true;
3679 ICS->Standard.DirectBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003680 ICS->Standard.RRefBinding = false;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003681 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003682
3683 // Nothing more to do: the inaccessibility/ambiguity check for
3684 // derived-to-base conversions is suppressed when we're
3685 // computing the implicit conversion sequence (C++
3686 // [over.best.ics]p2).
3687 return false;
3688 } else {
3689 // Perform the conversion.
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003690 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3691 if (DerivedToBase)
3692 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003693 else if(CheckExceptionSpecCompatibility(Init, T1))
3694 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003695 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003696 }
3697 }
3698
3699 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman44b83ee2009-08-05 19:21:58 +00003700 // implicitly converted to an lvalue of type "cv3 T3,"
3701 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003702 // 92) (this conversion is selected by enumerating the
3703 // applicable conversion functions (13.3.1.6) and choosing
3704 // the best one through overload resolution (13.3)),
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003705 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003706 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump11289f42009-09-09 15:08:12 +00003707 CXXRecordDecl *T2RecordDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003708 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003709
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003710 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00003711 OverloadedFunctionDecl *Conversions
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003712 = T2RecordDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003713 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003714 = Conversions->function_begin();
3715 Func != Conversions->function_end(); ++Func) {
Mike Stump11289f42009-09-09 15:08:12 +00003716 FunctionTemplateDecl *ConvTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003717 = dyn_cast<FunctionTemplateDecl>(*Func);
3718 CXXConversionDecl *Conv;
3719 if (ConvTemplate)
3720 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3721 else
3722 Conv = cast<CXXConversionDecl>(*Func);
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003723
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003724 // If the conversion function doesn't return a reference type,
3725 // it can't be considered for this conversion.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003726 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor05155d82009-08-21 23:19:43 +00003727 (AllowExplicit || !Conv->isExplicit())) {
3728 if (ConvTemplate)
Mike Stump11289f42009-09-09 15:08:12 +00003729 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003730 CandidateSet);
3731 else
3732 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3733 }
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003734 }
3735
3736 OverloadCandidateSet::iterator Best;
Douglas Gregorc809cc22009-09-23 23:04:10 +00003737 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003738 case OR_Success:
3739 // This is a direct binding.
3740 BindsDirectly = true;
3741
3742 if (ICS) {
3743 // C++ [over.ics.ref]p1:
3744 //
3745 // [...] If the parameter binds directly to the result of
3746 // applying a conversion function to the argument
3747 // expression, the implicit conversion sequence is a
3748 // user-defined conversion sequence (13.3.3.1.2), with the
3749 // second standard conversion sequence either an identity
3750 // conversion or, if the conversion function returns an
3751 // entity of a type that is a derived class of the parameter
3752 // type, a derived-to-base Conversion.
3753 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3754 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3755 ICS->UserDefined.After = Best->FinalConversion;
3756 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003757 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003758 assert(ICS->UserDefined.After.ReferenceBinding &&
3759 ICS->UserDefined.After.DirectBinding &&
3760 "Expected a direct reference binding!");
3761 return false;
3762 } else {
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003763 OwningExprResult InitConversion =
Douglas Gregorc809cc22009-09-23 23:04:10 +00003764 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003765 CastExpr::CK_UserDefinedConversion,
3766 cast<CXXMethodDecl>(Best->Function),
3767 Owned(Init));
3768 Init = InitConversion.takeAs<Expr>();
Sebastian Redl5d431642009-10-10 12:04:10 +00003769
3770 if (CheckExceptionSpecCompatibility(Init, T1))
3771 return true;
Fariborz Jahanian9ce90d12009-09-23 22:34:00 +00003772 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3773 /*isLvalue=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003774 }
3775 break;
3776
3777 case OR_Ambiguous:
Fariborz Jahanian31481d82009-10-14 00:52:43 +00003778 if (ICS) {
3779 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3780 Cand != CandidateSet.end(); ++Cand)
3781 if (Cand->Viable)
3782 ICS->ConversionFunctionSet.push_back(Cand->Function);
3783 break;
3784 }
3785 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
3786 << Init->getSourceRange();
3787 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003788 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003789
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003790 case OR_No_Viable_Function:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003791 case OR_Deleted:
3792 // There was no suitable conversion, or we found a deleted
3793 // conversion; continue with other checks.
Douglas Gregorf52cdd02008-11-10 16:14:15 +00003794 break;
3795 }
3796 }
Mike Stump11289f42009-09-09 15:08:12 +00003797
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003798 if (BindsDirectly) {
3799 // C++ [dcl.init.ref]p4:
3800 // [...] In all cases where the reference-related or
3801 // reference-compatible relationship of two types is used to
3802 // establish the validity of a reference binding, and T1 is a
3803 // base class of T2, a program that necessitates such a binding
3804 // is ill-formed if T1 is an inaccessible (clause 11) or
3805 // ambiguous (10.2) base class of T2.
3806 //
3807 // Note that we only check this condition when we're allowed to
3808 // complain about errors, because we should not be checking for
3809 // ambiguity (or inaccessibility) unless the reference binding
3810 // actually happens.
Mike Stump11289f42009-09-09 15:08:12 +00003811 if (DerivedToBase)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003812 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Douglas Gregor786ab212008-10-29 02:00:59 +00003813 Init->getSourceRange());
3814 else
3815 return false;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003816 }
3817
3818 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003819 // type (i.e., cv1 shall be const), or the reference shall be an
3820 // rvalue reference and the initializer expression shall be an rvalue.
John McCall8ccfcb52009-09-24 19:53:00 +00003821 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor786ab212008-10-29 02:00:59 +00003822 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003823 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003824 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3825 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003826 return true;
3827 }
3828
3829 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman44b83ee2009-08-05 19:21:58 +00003830 // class type, and "cv1 T1" is reference-compatible with
3831 // "cv2 T2," the reference is bound in one of the
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003832 // following ways (the choice is implementation-defined):
3833 //
3834 // -- The reference is bound to the object represented by
3835 // the rvalue (see 3.10) or to a sub-object within that
3836 // object.
3837 //
Eli Friedman44b83ee2009-08-05 19:21:58 +00003838 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003839 // a constructor is called to copy the entire rvalue
3840 // object into the temporary. The reference is bound to
3841 // the temporary or to a sub-object within the
3842 // temporary.
3843 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003844 // The constructor that would be used to make the copy
3845 // shall be callable whether or not the copy is actually
3846 // done.
3847 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003848 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003849 // freedom, so we will always take the first option and never build
3850 // a temporary in this case. FIXME: We will, however, have to check
3851 // for the presence of a copy constructor in C++98/03 mode.
3852 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor786ab212008-10-29 02:00:59 +00003853 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3854 if (ICS) {
3855 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3856 ICS->Standard.First = ICK_Identity;
3857 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3858 ICS->Standard.Third = ICK_Identity;
3859 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3860 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003861 ICS->Standard.ReferenceBinding = true;
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003862 ICS->Standard.DirectBinding = false;
3863 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00003864 ICS->Standard.CopyConstructor = 0;
Douglas Gregor786ab212008-10-29 02:00:59 +00003865 } else {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003866 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3867 if (DerivedToBase)
3868 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl5d431642009-10-10 12:04:10 +00003869 else if(CheckExceptionSpecCompatibility(Init, T1))
3870 return true;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00003871 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003872 }
3873 return false;
3874 }
3875
Eli Friedman44b83ee2009-08-05 19:21:58 +00003876 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003877 // initialized from the initializer expression using the
3878 // rules for a non-reference copy initialization (8.5). The
3879 // reference is then bound to the temporary. If T1 is
3880 // reference-related to T2, cv1 must be the same
3881 // cv-qualification as, or greater cv-qualification than,
3882 // cv2; otherwise, the program is ill-formed.
3883 if (RefRelationship == Ref_Related) {
3884 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3885 // we would be reference-compatible or reference-compatible with
3886 // added qualification. But that wasn't the case, so the reference
3887 // initialization fails.
Douglas Gregor786ab212008-10-29 02:00:59 +00003888 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003889 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003890 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3891 << T2 << Init->getSourceRange();
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003892 return true;
3893 }
3894
Douglas Gregor576e98c2009-01-30 23:27:23 +00003895 // If at least one of the types is a class type, the types are not
3896 // related, and we aren't allowed any user conversions, the
3897 // reference binding fails. This case is important for breaking
3898 // recursion, since TryImplicitConversion below will attempt to
3899 // create a temporary through the use of a copy constructor.
3900 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3901 (T1->isRecordType() || T2->isRecordType())) {
3902 if (!ICS)
Douglas Gregorc809cc22009-09-23 23:04:10 +00003903 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor576e98c2009-01-30 23:27:23 +00003904 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3905 return true;
3906 }
3907
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003908 // Actually try to convert the initializer to T1.
Douglas Gregor786ab212008-10-29 02:00:59 +00003909 if (ICS) {
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003910 // C++ [over.ics.ref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003911 //
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003912 // When a parameter of reference type is not bound directly to
3913 // an argument expression, the conversion sequence is the one
3914 // required to convert the argument expression to the
3915 // underlying type of the reference according to
3916 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3917 // to copy-initializing a temporary of the underlying type with
3918 // the argument expression. Any difference in top-level
3919 // cv-qualification is subsumed by the initialization itself
3920 // and does not constitute a conversion.
Anders Carlssonef4c7212009-08-27 17:24:15 +00003921 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3922 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00003923 /*ForceRValue=*/false,
3924 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003925
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003926 // Of course, that's still a reference binding.
3927 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3928 ICS->Standard.ReferenceBinding = true;
3929 ICS->Standard.RRefBinding = isRValRef;
Mike Stump11289f42009-09-09 15:08:12 +00003930 } else if (ICS->ConversionKind ==
Sebastian Redl4c0cd852009-03-29 15:27:50 +00003931 ImplicitConversionSequence::UserDefinedConversion) {
3932 ICS->UserDefined.After.ReferenceBinding = true;
3933 ICS->UserDefined.After.RRefBinding = isRValRef;
3934 }
Douglas Gregor786ab212008-10-29 02:00:59 +00003935 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3936 } else {
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003937 ImplicitConversionSequence Conversions;
3938 bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3939 false, false,
3940 Conversions);
3941 if (badConversion) {
3942 if ((Conversions.ConversionKind ==
3943 ImplicitConversionSequence::BadConversion)
Fariborz Jahanian9021fc72009-09-28 22:03:07 +00003944 && !Conversions.ConversionFunctionSet.empty()) {
Fariborz Jahanian20327b02009-09-24 00:42:43 +00003945 Diag(DeclLoc,
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003946 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3947 for (int j = Conversions.ConversionFunctionSet.size()-1;
3948 j >= 0; j--) {
3949 FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3950 Diag(Func->getLocation(), diag::err_ovl_candidate);
3951 }
3952 }
Fariborz Jahaniandb823082009-09-30 21:23:30 +00003953 else {
3954 if (isRValRef)
3955 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3956 << Init->getSourceRange();
3957 else
3958 Diag(DeclLoc, diag::err_invalid_initialization)
3959 << DeclType << Init->getType() << Init->getSourceRange();
3960 }
Fariborz Jahanianaf0262d2009-09-23 20:55:32 +00003961 }
3962 return badConversion;
Douglas Gregor786ab212008-10-29 02:00:59 +00003963 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003964}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003965
3966/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3967/// of this overloaded operator is well-formed. If so, returns false;
3968/// otherwise, emits appropriate diagnostics and returns true.
3969bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00003970 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003971 "Expected an overloaded operator declaration");
3972
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003973 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3974
Mike Stump11289f42009-09-09 15:08:12 +00003975 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003976 // The allocation and deallocation functions, operator new,
3977 // operator new[], operator delete and operator delete[], are
3978 // described completely in 3.7.3. The attributes and restrictions
3979 // found in the rest of this subclause do not apply to them unless
3980 // explicitly stated in 3.7.3.
Mike Stump87c57ac2009-05-16 07:39:55 +00003981 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003982 if (Op == OO_New || Op == OO_Array_New ||
3983 Op == OO_Delete || Op == OO_Array_Delete)
3984 return false;
3985
3986 // C++ [over.oper]p6:
3987 // An operator function shall either be a non-static member
3988 // function or be a non-member function and have at least one
3989 // parameter whose type is a class, a reference to a class, an
3990 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00003991 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3992 if (MethodDecl->isStatic())
3993 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003994 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003995 } else {
3996 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00003997 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3998 ParamEnd = FnDecl->param_end();
3999 Param != ParamEnd; ++Param) {
4000 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004001 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4002 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004003 ClassOrEnumParam = true;
4004 break;
4005 }
4006 }
4007
Douglas Gregord69246b2008-11-17 16:14:12 +00004008 if (!ClassOrEnumParam)
4009 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004010 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004011 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004012 }
4013
4014 // C++ [over.oper]p8:
4015 // An operator function cannot have default arguments (8.3.6),
4016 // except where explicitly stated below.
4017 //
Mike Stump11289f42009-09-09 15:08:12 +00004018 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004019 // (C++ [over.call]p1).
4020 if (Op != OO_Call) {
4021 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4022 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor58354032008-12-24 00:01:03 +00004023 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004024 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004025 diag::err_operator_overload_default_arg)
4026 << FnDecl->getDeclName();
4027 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregord69246b2008-11-17 16:14:12 +00004028 return Diag((*Param)->getLocation(),
Chris Lattner29e812b2008-11-20 06:06:08 +00004029 diag::err_operator_overload_default_arg)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004030 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004031 }
4032 }
4033
Douglas Gregor6cf08062008-11-10 13:38:07 +00004034 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4035 { false, false, false }
4036#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4037 , { Unary, Binary, MemberOnly }
4038#include "clang/Basic/OperatorKinds.def"
4039 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004040
Douglas Gregor6cf08062008-11-10 13:38:07 +00004041 bool CanBeUnaryOperator = OperatorUses[Op][0];
4042 bool CanBeBinaryOperator = OperatorUses[Op][1];
4043 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004044
4045 // C++ [over.oper]p8:
4046 // [...] Operator functions cannot have more or fewer parameters
4047 // than the number required for the corresponding operator, as
4048 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00004049 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00004050 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004051 if (Op != OO_Call &&
4052 ((NumParams == 1 && !CanBeUnaryOperator) ||
4053 (NumParams == 2 && !CanBeBinaryOperator) ||
4054 (NumParams < 1) || (NumParams > 2))) {
4055 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004056 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00004057 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004058 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00004059 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004060 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004061 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00004062 assert(CanBeBinaryOperator &&
4063 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004064 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00004065 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004066
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00004067 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004068 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004069 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004070
Douglas Gregord69246b2008-11-17 16:14:12 +00004071 // Overloaded operators other than operator() cannot be variadic.
4072 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00004073 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00004074 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004075 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004076 }
4077
4078 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00004079 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4080 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004081 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004082 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004083 }
4084
4085 // C++ [over.inc]p1:
4086 // The user-defined function called operator++ implements the
4087 // prefix and postfix ++ operator. If this function is a member
4088 // function with no parameters, or a non-member function with one
4089 // parameter of class or enumeration type, it defines the prefix
4090 // increment operator ++ for objects of that type. If the function
4091 // is a member function with one parameter (which shall be of type
4092 // int) or a non-member function with two parameters (the second
4093 // of which shall be of type int), it defines the postfix
4094 // increment operator ++ for objects of that type.
4095 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4096 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4097 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00004098 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004099 ParamIsInt = BT->getKind() == BuiltinType::Int;
4100
Chris Lattner2b786902008-11-21 07:50:02 +00004101 if (!ParamIsInt)
4102 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004103 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004104 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004105 }
4106
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004107 // Notify the class if it got an assignment operator.
4108 if (Op == OO_Equal) {
4109 // Would have returned earlier otherwise.
4110 assert(isa<CXXMethodDecl>(FnDecl) &&
4111 "Overloaded = not member, but not filtered.");
4112 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4113 Method->getParent()->addedAssignmentOperator(Context, Method);
4114 }
4115
Douglas Gregord69246b2008-11-17 16:14:12 +00004116 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004117}
Chris Lattner3b024a32008-12-17 07:09:26 +00004118
Douglas Gregor07665a62009-01-05 19:45:36 +00004119/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4120/// linkage specification, including the language and (if present)
4121/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4122/// the location of the language string literal, which is provided
4123/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4124/// the '{' brace. Otherwise, this linkage specification does not
4125/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004126Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4127 SourceLocation ExternLoc,
4128 SourceLocation LangLoc,
4129 const char *Lang,
4130 unsigned StrSize,
4131 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00004132 LinkageSpecDecl::LanguageIDs Language;
4133 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4134 Language = LinkageSpecDecl::lang_c;
4135 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4136 Language = LinkageSpecDecl::lang_cxx;
4137 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00004138 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00004139 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00004140 }
Mike Stump11289f42009-09-09 15:08:12 +00004141
Chris Lattner438e5012008-12-17 07:13:27 +00004142 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00004143
Douglas Gregor07665a62009-01-05 19:45:36 +00004144 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00004145 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00004146 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004147 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00004148 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004149 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00004150}
4151
Douglas Gregor07665a62009-01-05 19:45:36 +00004152/// ActOnFinishLinkageSpecification - Completely the definition of
4153/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4154/// valid, it's the position of the closing '}' brace in a linkage
4155/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00004156Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4157 DeclPtrTy LinkageSpec,
4158 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00004159 if (LinkageSpec)
4160 PopDeclContext();
4161 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00004162}
4163
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004164/// \brief Perform semantic analysis for the variable declaration that
4165/// occurs within a C++ catch clause, returning the newly-created
4166/// variable.
4167VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004168 DeclaratorInfo *DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004169 IdentifierInfo *Name,
4170 SourceLocation Loc,
4171 SourceRange Range) {
4172 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004173
4174 // Arrays and functions decay.
4175 if (ExDeclType->isArrayType())
4176 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4177 else if (ExDeclType->isFunctionType())
4178 ExDeclType = Context.getPointerType(ExDeclType);
4179
4180 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4181 // The exception-declaration shall not denote a pointer or reference to an
4182 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00004183 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00004184 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004185 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00004186 Invalid = true;
4187 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004188
Sebastian Redl54c04d42008-12-22 19:15:10 +00004189 QualType BaseType = ExDeclType;
4190 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00004191 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004192 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004193 BaseType = Ptr->getPointeeType();
4194 Mode = 1;
Douglas Gregordd430f72009-01-19 19:26:10 +00004195 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00004196 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00004197 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004198 BaseType = Ref->getPointeeType();
4199 Mode = 2;
Douglas Gregordd430f72009-01-19 19:26:10 +00004200 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004201 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00004202 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004203 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00004204 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004205
Mike Stump11289f42009-09-09 15:08:12 +00004206 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004207 RequireNonAbstractType(Loc, ExDeclType,
4208 diag::err_abstract_type_in_decl,
4209 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00004210 Invalid = true;
4211
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004212 // FIXME: Need to test for ability to copy-construct and destroy the
4213 // exception variable.
4214
Sebastian Redl9b244a82008-12-22 21:35:02 +00004215 // FIXME: Need to check for abstract classes.
4216
Mike Stump11289f42009-09-09 15:08:12 +00004217 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00004218 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004219
4220 if (Invalid)
4221 ExDecl->setInvalidDecl();
4222
4223 return ExDecl;
4224}
4225
4226/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4227/// handler.
4228Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004229 DeclaratorInfo *DInfo = 0;
4230 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004231
4232 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00004233 IdentifierInfo *II = D.getIdentifier();
John McCall9f3059a2009-10-09 21:13:30 +00004234 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004235 // The scope should be freshly made just for us. There is just no way
4236 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00004237 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00004238 if (PrevDecl->isTemplateParameter()) {
4239 // Maybe we will complain about the shadowed template parameter.
4240 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004241 }
4242 }
4243
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004244 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00004245 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4246 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004247 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00004248 }
4249
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004250 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004251 D.getIdentifier(),
4252 D.getIdentifierLoc(),
4253 D.getDeclSpec().getSourceRange());
4254
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004255 if (Invalid)
4256 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004257
Sebastian Redl54c04d42008-12-22 19:15:10 +00004258 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00004259 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00004260 PushOnScopeChains(ExDecl, S);
4261 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004262 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004263
Douglas Gregor758a8692009-06-17 21:51:59 +00004264 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00004265 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00004266}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004267
Mike Stump11289f42009-09-09 15:08:12 +00004268Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004269 ExprArg assertexpr,
4270 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004271 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00004272 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004273 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4274
Anders Carlsson54b26982009-03-14 00:33:21 +00004275 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4276 llvm::APSInt Value(32);
4277 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4278 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4279 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004280 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00004281 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004282
Anders Carlsson54b26982009-03-14 00:33:21 +00004283 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00004284 std::string str(AssertMessage->getStrData(),
Anders Carlsson54b26982009-03-14 00:33:21 +00004285 AssertMessage->getByteLength());
Mike Stump11289f42009-09-09 15:08:12 +00004286 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson27de6a52009-03-15 18:44:04 +00004287 << str << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00004288 }
4289 }
Mike Stump11289f42009-09-09 15:08:12 +00004290
Anders Carlsson78e2bc02009-03-15 17:35:16 +00004291 assertexpr.release();
4292 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00004293 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004294 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00004295
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004296 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00004297 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00004298}
Sebastian Redlf769df52009-03-24 22:27:57 +00004299
John McCall11083da2009-09-16 22:47:08 +00004300/// Handle a friend type declaration. This works in tandem with
4301/// ActOnTag.
4302///
4303/// Notes on friend class templates:
4304///
4305/// We generally treat friend class declarations as if they were
4306/// declaring a class. So, for example, the elaborated type specifier
4307/// in a friend declaration is required to obey the restrictions of a
4308/// class-head (i.e. no typedefs in the scope chain), template
4309/// parameters are required to match up with simple template-ids, &c.
4310/// However, unlike when declaring a template specialization, it's
4311/// okay to refer to a template specialization without an empty
4312/// template parameter declaration, e.g.
4313/// friend class A<T>::B<unsigned>;
4314/// We permit this as a special case; if there are any template
4315/// parameters present at all, require proper matching, i.e.
4316/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00004317Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00004318 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004319 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00004320
4321 assert(DS.isFriendSpecified());
4322 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4323
John McCall11083da2009-09-16 22:47:08 +00004324 // Try to convert the decl specifier to a type. This works for
4325 // friend templates because ActOnTag never produces a ClassTemplateDecl
4326 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00004327 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattner1fb66f42009-10-25 17:47:27 +00004328 QualType T = GetTypeForDeclarator(TheDeclarator, S);
4329 if (TheDeclarator.isInvalidType())
4330 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00004331
John McCall11083da2009-09-16 22:47:08 +00004332 // This is definitely an error in C++98. It's probably meant to
4333 // be forbidden in C++0x, too, but the specification is just
4334 // poorly written.
4335 //
4336 // The problem is with declarations like the following:
4337 // template <T> friend A<T>::foo;
4338 // where deciding whether a class C is a friend or not now hinges
4339 // on whether there exists an instantiation of A that causes
4340 // 'foo' to equal C. There are restrictions on class-heads
4341 // (which we declare (by fiat) elaborated friend declarations to
4342 // be) that makes this tractable.
4343 //
4344 // FIXME: handle "template <> friend class A<T>;", which
4345 // is possibly well-formed? Who even knows?
4346 if (TempParams.size() && !isa<ElaboratedType>(T)) {
4347 Diag(Loc, diag::err_tagless_friend_type_template)
4348 << DS.getSourceRange();
4349 return DeclPtrTy();
4350 }
4351
John McCallaa74a0c2009-08-28 07:59:38 +00004352 // C++ [class.friend]p2:
4353 // An elaborated-type-specifier shall be used in a friend declaration
4354 // for a class.*
4355 // * The class-key of the elaborated-type-specifier is required.
John McCalld8fe9af2009-09-08 17:47:29 +00004356 // This is one of the rare places in Clang where it's legitimate to
4357 // ask about the "spelling" of the type.
4358 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4359 // If we evaluated the type to a record type, suggest putting
4360 // a tag in front.
John McCallaa74a0c2009-08-28 07:59:38 +00004361 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCalld8fe9af2009-09-08 17:47:29 +00004362 RecordDecl *RD = RT->getDecl();
4363
4364 std::string InsertionText = std::string(" ") + RD->getKindName();
4365
John McCallc3987482009-10-07 23:34:25 +00004366 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
4367 << (unsigned) RD->getTagKind()
4368 << T
4369 << SourceRange(DS.getFriendSpecLoc())
John McCalld8fe9af2009-09-08 17:47:29 +00004370 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4371 InsertionText);
John McCallaa74a0c2009-08-28 07:59:38 +00004372 return DeclPtrTy();
4373 }else {
John McCalld8fe9af2009-09-08 17:47:29 +00004374 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4375 << DS.getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004376 return DeclPtrTy();
John McCallaa74a0c2009-08-28 07:59:38 +00004377 }
4378 }
4379
John McCallc3987482009-10-07 23:34:25 +00004380 // Enum types cannot be friends.
4381 if (T->getAs<EnumType>()) {
4382 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
4383 << SourceRange(DS.getFriendSpecLoc());
4384 return DeclPtrTy();
John McCalld8fe9af2009-09-08 17:47:29 +00004385 }
John McCallaa74a0c2009-08-28 07:59:38 +00004386
John McCallaa74a0c2009-08-28 07:59:38 +00004387 // C++98 [class.friend]p1: A friend of a class is a function
4388 // or class that is not a member of the class . . .
4389 // But that's a silly restriction which nobody implements for
4390 // inner classes, and C++0x removes it anyway, so we only report
4391 // this (as a warning) if we're being pedantic.
John McCalld8fe9af2009-09-08 17:47:29 +00004392 if (!getLangOptions().CPlusPlus0x)
4393 if (const RecordType *RT = T->getAs<RecordType>())
4394 if (RT->getDecl()->getDeclContext() == CurContext)
4395 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCallaa74a0c2009-08-28 07:59:38 +00004396
John McCall11083da2009-09-16 22:47:08 +00004397 Decl *D;
4398 if (TempParams.size())
4399 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4400 TempParams.size(),
4401 (TemplateParameterList**) TempParams.release(),
4402 T.getTypePtr(),
4403 DS.getFriendSpecLoc());
4404 else
4405 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4406 DS.getFriendSpecLoc());
4407 D->setAccess(AS_public);
4408 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004409
John McCall11083da2009-09-16 22:47:08 +00004410 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00004411}
4412
John McCall2f212b32009-09-11 21:02:39 +00004413Sema::DeclPtrTy
4414Sema::ActOnFriendFunctionDecl(Scope *S,
4415 Declarator &D,
4416 bool IsDefinition,
4417 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00004418 const DeclSpec &DS = D.getDeclSpec();
4419
4420 assert(DS.isFriendSpecified());
4421 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4422
4423 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004424 DeclaratorInfo *DInfo = 0;
John McCallaa74a0c2009-08-28 07:59:38 +00004425 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall07e91c02009-08-06 02:15:43 +00004426
4427 // C++ [class.friend]p1
4428 // A friend of a class is a function or class....
4429 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00004430 // It *doesn't* see through dependent types, which is correct
4431 // according to [temp.arg.type]p3:
4432 // If a declaration acquires a function type through a
4433 // type dependent on a template-parameter and this causes
4434 // a declaration that does not use the syntactic form of a
4435 // function declarator to have a function type, the program
4436 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00004437 if (!T->isFunctionType()) {
4438 Diag(Loc, diag::err_unexpected_friend);
4439
4440 // It might be worthwhile to try to recover by creating an
4441 // appropriate declaration.
4442 return DeclPtrTy();
4443 }
4444
4445 // C++ [namespace.memdef]p3
4446 // - If a friend declaration in a non-local class first declares a
4447 // class or function, the friend class or function is a member
4448 // of the innermost enclosing namespace.
4449 // - The name of the friend is not found by simple name lookup
4450 // until a matching declaration is provided in that namespace
4451 // scope (either before or after the class declaration granting
4452 // friendship).
4453 // - If a friend function is called, its name may be found by the
4454 // name lookup that considers functions from namespaces and
4455 // classes associated with the types of the function arguments.
4456 // - When looking for a prior declaration of a class or a function
4457 // declared as a friend, scopes outside the innermost enclosing
4458 // namespace scope are not considered.
4459
John McCallaa74a0c2009-08-28 07:59:38 +00004460 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4461 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00004462 assert(Name);
4463
John McCall07e91c02009-08-06 02:15:43 +00004464 // The context we found the declaration in, or in which we should
4465 // create the declaration.
4466 DeclContext *DC;
4467
4468 // FIXME: handle local classes
4469
4470 // Recover from invalid scope qualifiers as if they just weren't there.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004471 NamedDecl *PrevDecl = 0;
John McCall07e91c02009-08-06 02:15:43 +00004472 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004473 // FIXME: RequireCompleteDeclContext
John McCall07e91c02009-08-06 02:15:43 +00004474 DC = computeDeclContext(ScopeQual);
4475
4476 // FIXME: handle dependent contexts
4477 if (!DC) return DeclPtrTy();
4478
John McCall9f3059a2009-10-09 21:13:30 +00004479 LookupResult R;
4480 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4481 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004482
4483 // If searching in that context implicitly found a declaration in
4484 // a different context, treat it like it wasn't found at all.
4485 // TODO: better diagnostics for this case. Suggesting the right
4486 // qualified scope would be nice...
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004487 if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00004488 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00004489 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4490 return DeclPtrTy();
4491 }
4492
4493 // C++ [class.friend]p1: A friend of a class is a function or
4494 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004495 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00004496 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4497
John McCall07e91c02009-08-06 02:15:43 +00004498 // Otherwise walk out to the nearest namespace scope looking for matches.
4499 } else {
4500 // TODO: handle local class contexts.
4501
4502 DC = CurContext;
4503 while (true) {
4504 // Skip class contexts. If someone can cite chapter and verse
4505 // for this behavior, that would be nice --- it's what GCC and
4506 // EDG do, and it seems like a reasonable intent, but the spec
4507 // really only says that checks for unqualified existing
4508 // declarations should stop at the nearest enclosing namespace,
4509 // not that they should only consider the nearest enclosing
4510 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004511 while (DC->isRecord())
4512 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00004513
John McCall9f3059a2009-10-09 21:13:30 +00004514 LookupResult R;
4515 LookupQualifiedName(R, DC, Name, LookupOrdinaryName, true);
4516 PrevDecl = R.getAsSingleDecl(Context);
John McCall07e91c02009-08-06 02:15:43 +00004517
4518 // TODO: decide what we think about using declarations.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004519 if (PrevDecl)
John McCall07e91c02009-08-06 02:15:43 +00004520 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004521
John McCall07e91c02009-08-06 02:15:43 +00004522 if (DC->isFileContext()) break;
4523 DC = DC->getParent();
4524 }
4525
4526 // C++ [class.friend]p1: A friend of a class is a function or
4527 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00004528 // C++0x changes this for both friend types and functions.
4529 // Most C++ 98 compilers do seem to give an error here, so
4530 // we do, too.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004531 if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00004532 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4533 }
4534
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004535 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00004536 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00004537 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
4538 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
4539 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00004540 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00004541 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
4542 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00004543 return DeclPtrTy();
4544 }
John McCall07e91c02009-08-06 02:15:43 +00004545 }
4546
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004547 bool Redeclaration = false;
4548 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00004549 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00004550 IsDefinition,
4551 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00004552 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00004553
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004554 assert(ND->getDeclContext() == DC);
4555 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00004556
John McCall759e32b2009-08-31 22:39:49 +00004557 // Add the function declaration to the appropriate lookup tables,
4558 // adjusting the redeclarations list as necessary. We don't
4559 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00004560 //
John McCall759e32b2009-08-31 22:39:49 +00004561 // Also update the scope-based lookup if the target context's
4562 // lookup context is in lexical scope.
4563 if (!CurContext->isDependentContext()) {
4564 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004565 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004566 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004567 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00004568 }
John McCallaa74a0c2009-08-28 07:59:38 +00004569
4570 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004571 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00004572 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00004573 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00004574 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00004575
Douglas Gregora29a3ff2009-09-28 00:08:27 +00004576 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00004577}
4578
Chris Lattner83f095c2009-03-28 19:18:32 +00004579void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004580 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004581
Chris Lattner83f095c2009-03-28 19:18:32 +00004582 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00004583 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4584 if (!Fn) {
4585 Diag(DelLoc, diag::err_deleted_non_function);
4586 return;
4587 }
4588 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4589 Diag(DelLoc, diag::err_deleted_decl_not_first);
4590 Diag(Prev->getLocation(), diag::note_previous_declaration);
4591 // If the declaration wasn't the first, we delete the function anyway for
4592 // recovery.
4593 }
4594 Fn->setDeleted();
4595}
Sebastian Redl4c018662009-04-27 21:33:24 +00004596
4597static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4598 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4599 ++CI) {
4600 Stmt *SubStmt = *CI;
4601 if (!SubStmt)
4602 continue;
4603 if (isa<ReturnStmt>(SubStmt))
4604 Self.Diag(SubStmt->getSourceRange().getBegin(),
4605 diag::err_return_in_constructor_handler);
4606 if (!isa<Expr>(SubStmt))
4607 SearchForReturnInStmt(Self, SubStmt);
4608 }
4609}
4610
4611void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4612 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4613 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4614 SearchForReturnInStmt(*this, Handler);
4615 }
4616}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004617
Mike Stump11289f42009-09-09 15:08:12 +00004618bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004619 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00004620 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4621 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004622
4623 QualType CNewTy = Context.getCanonicalType(NewTy);
4624 QualType COldTy = Context.getCanonicalType(OldTy);
4625
Mike Stump11289f42009-09-09 15:08:12 +00004626 if (CNewTy == COldTy &&
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004627 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4628 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004629
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004630 // Check if the return types are covariant
4631 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00004632
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004633 /// Both types must be pointers or references to classes.
4634 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4635 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4636 NewClassTy = NewPT->getPointeeType();
4637 OldClassTy = OldPT->getPointeeType();
4638 }
4639 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4640 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4641 NewClassTy = NewRT->getPointeeType();
4642 OldClassTy = OldRT->getPointeeType();
4643 }
4644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004646 // The return types aren't either both pointers or references to a class type.
4647 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00004648 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004649 diag::err_different_return_type_for_overriding_virtual_function)
4650 << New->getDeclName() << NewTy << OldTy;
4651 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00004652
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004653 return true;
4654 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004655
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004656 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4657 // Check if the new class derives from the old class.
4658 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4659 Diag(New->getLocation(),
4660 diag::err_covariant_return_not_derived)
4661 << New->getDeclName() << NewTy << OldTy;
4662 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4663 return true;
4664 }
Mike Stump11289f42009-09-09 15:08:12 +00004665
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004666 // Check if we the conversion from derived to base is valid.
Mike Stump11289f42009-09-09 15:08:12 +00004667 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004668 diag::err_covariant_return_inaccessible_base,
4669 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4670 // FIXME: Should this point to the return type?
4671 New->getLocation(), SourceRange(), New->getDeclName())) {
4672 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4673 return true;
4674 }
4675 }
Mike Stump11289f42009-09-09 15:08:12 +00004676
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004677 // The qualifiers of the return types must be the same.
4678 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4679 Diag(New->getLocation(),
4680 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004681 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004682 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4683 return true;
4684 };
Mike Stump11289f42009-09-09 15:08:12 +00004685
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004686
4687 // The new class type must have the same or less qualifiers as the old type.
4688 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4689 Diag(New->getLocation(),
4690 diag::err_covariant_return_type_class_type_more_qualified)
4691 << New->getDeclName() << NewTy << OldTy;
4692 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4693 return true;
4694 };
Mike Stump11289f42009-09-09 15:08:12 +00004695
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00004696 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00004697}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004698
4699/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4700/// initializer for the declaration 'Dcl'.
4701/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4702/// static data member of class X, names should be looked up in the scope of
4703/// class X.
4704void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004705 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004706
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004707 Decl *D = Dcl.getAs<Decl>();
4708 // If there is no declaration, there was an error parsing it.
4709 if (D == 0)
4710 return;
4711
4712 // Check whether it is a declaration with a nested name specifier like
4713 // int foo::bar;
4714 if (!D->isOutOfLine())
4715 return;
Mike Stump11289f42009-09-09 15:08:12 +00004716
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004717 // C++ [basic.lookup.unqual]p13
4718 //
4719 // A name used in the definition of a static data member of class X
4720 // (after the qualified-id of the static member) is looked up as if the name
4721 // was used in a member function of X.
Mike Stump11289f42009-09-09 15:08:12 +00004722
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004723 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004724 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004725}
4726
4727/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4728/// initializer for the declaration 'Dcl'.
4729void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00004730 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00004731
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004732 Decl *D = Dcl.getAs<Decl>();
4733 // If there is no declaration, there was an error parsing it.
4734 if (D == 0)
4735 return;
4736
4737 // Check whether it is a declaration with a nested name specifier like
4738 // int foo::bar;
4739 if (!D->isOutOfLine())
4740 return;
4741
4742 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +00004743 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00004744}