blob: f23f702d0545b0b024788461ec96b814d9f4ef09 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000359 if (CheckEquivalentExceptionSpec(
John McCall183700f2009-09-21 23:43:11 +0000360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
436 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump1eb44332009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000450 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451 SourceLocation BaseLoc) {
452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000462 Class->getTagKind() == RecordDecl::TK_class,
463 Access, BaseType);
464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000484 return 0;
485
Eli Friedman1d954f62009-08-15 21:55:26 +0000486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Record type has no declaration");
489 BaseDecl = BaseDecl->getDefinition(Context);
490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000493
Sean Huntbbd37c62009-11-21 08:43:09 +0000494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000499 return 0;
500 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000501
Eli Friedmand0137332009-12-05 23:03:49 +0000502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000503
504 // Create the base specifier.
505 // FIXME: Allocate via ASTContext?
506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 Class->getTagKind() == RecordDecl::TK_class,
508 Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 const CXXRecordDecl *BaseClass,
513 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000514 // A class with a non-empty base class is not empty.
515 // FIXME: Standard ref?
516 if (!BaseClass->isEmpty())
517 Class->setEmpty(false);
518
519 // C++ [class.virtual]p1:
520 // A class that [...] inherits a virtual function is called a polymorphic
521 // class.
522 if (BaseClass->isPolymorphic())
523 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000524
Douglas Gregor2943aed2009-03-03 04:44:36 +0000525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is [...] a class with [...] no base classes [...].
527 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531 Class->setPOD(false);
532
Anders Carlsson51f94042009-12-03 17:49:57 +0000533 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000534 // C++ [class.ctor]p5:
535 // A constructor is trivial if its class has no virtual base classes.
536 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000537
538 // C++ [class.copy]p6:
539 // A copy constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialCopyConstructor(false);
541
542 // C++ [class.copy]p11:
543 // A copy assignment operator is trivial if its class has no virtual
544 // base classes.
545 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000546
547 // C++0x [meta.unary.prop] is_empty:
548 // T is a class type, but not a union type, with ... no virtual base
549 // classes
550 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000551 } else {
552 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000554 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000556 Class->setHasTrivialConstructor(false);
557
558 // C++ [class.copy]p6:
559 // A copy constructor is trivial if all the direct base classes of its
560 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000562 Class->setHasTrivialCopyConstructor(false);
563
564 // C++ [class.copy]p11:
565 // A copy assignment operator is trivial if all the direct base classes
566 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000567 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000568 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000569 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000570
571 // C++ [class.ctor]p3:
572 // A destructor is trivial if all the direct base classes of its class
573 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000575 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576}
577
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000580/// example:
581/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000582/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000583Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000587 if (!classdecl)
588 return true;
589
Douglas Gregor40808ce2009-03-09 23:48:35 +0000590 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000591 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000592 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000593 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594 Virtual, Access,
595 BaseType, BaseLoc))
596 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregor2943aed2009-03-03 04:44:36 +0000598 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000599}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601/// \brief Performs the actual work of attaching the given base class
602/// specifiers to a C++ class.
603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604 unsigned NumBases) {
605 if (NumBases == 0)
606 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000607
608 // Used to keep track of which base types we have already seen, so
609 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000610 // that the key is always the unqualified canonical type of the base
611 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000612 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613
614 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000616 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000618 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000619 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000620 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000621
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000622 if (KnownBaseTypes[NewBaseType]) {
623 // C++ [class.mi]p3:
624 // A class shall not be specified as a direct base class of a
625 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000627 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000628 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000630
631 // Delete the duplicate base class specifier; we're going to
632 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000633 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000634
635 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000636 } else {
637 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000638 KnownBaseTypes[NewBaseType] = Bases[idx];
639 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000640 }
641 }
642
643 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000644 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000645
646 // Delete the remaining (good) base class specifiers, since their
647 // data has been copied into the CXXRecordDecl.
648 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000649 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000650
651 return Invalid;
652}
653
654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
655/// class, after checking whether there are any duplicate base
656/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000658 unsigned NumBases) {
659 if (!ClassDecl || !Bases || !NumBases)
660 return;
661
662 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000664 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000665}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000666
Douglas Gregora8f32e02009-10-06 17:59:45 +0000667/// \brief Determine whether the type \p Derived is a C++ class that is
668/// derived from the type \p Base.
669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
670 if (!getLangOptions().CPlusPlus)
671 return false;
672
673 const RecordType *DerivedRT = Derived->getAs<RecordType>();
674 if (!DerivedRT)
675 return false;
676
677 const RecordType *BaseRT = Base->getAs<RecordType>();
678 if (!BaseRT)
679 return false;
680
681 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
683 return DerivedRD->isDerivedFrom(BaseRD);
684}
685
686/// \brief Determine whether the type \p Derived is a C++ class that is
687/// derived from the type \p Base.
688bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
689 if (!getLangOptions().CPlusPlus)
690 return false;
691
692 const RecordType *DerivedRT = Derived->getAs<RecordType>();
693 if (!DerivedRT)
694 return false;
695
696 const RecordType *BaseRT = Base->getAs<RecordType>();
697 if (!BaseRT)
698 return false;
699
700 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
701 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
702 return DerivedRD->isDerivedFrom(BaseRD, Paths);
703}
704
705/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
706/// conversion (where Derived and Base are class types) is
707/// well-formed, meaning that the conversion is unambiguous (and
708/// that all of the base classes are accessible). Returns true
709/// and emits a diagnostic if the code is ill-formed, returns false
710/// otherwise. Loc is the location where this routine should point to
711/// if there is an error, and Range is the source range to highlight
712/// if there is an error.
713bool
714Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
715 unsigned InaccessibleBaseID,
716 unsigned AmbigiousBaseConvID,
717 SourceLocation Loc, SourceRange Range,
718 DeclarationName Name) {
719 // First, determine whether the path from Derived to Base is
720 // ambiguous. This is slightly more expensive than checking whether
721 // the Derived to Base conversion exists, because here we need to
722 // explore multiple paths to determine if there is an ambiguity.
723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
724 /*DetectVirtual=*/false);
725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
726 assert(DerivationOkay &&
727 "Can only be used with a derived-to-base conversion");
728 (void)DerivationOkay;
729
730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000731 if (InaccessibleBaseID == 0)
732 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 // Check that the base class can be accessed.
734 return CheckBaseClassAccess(Derived, Base, InaccessibleBaseID, Paths, Loc,
735 Name);
736 }
737
738 // We know that the derived-to-base conversion is ambiguous, and
739 // we're going to produce a diagnostic. Perform the derived-to-base
740 // search just one more time to compute all of the possible paths so
741 // that we can print them out. This is more expensive than any of
742 // the previous derived-to-base checks we've done, but at this point
743 // performance isn't as much of an issue.
744 Paths.clear();
745 Paths.setRecordingPaths(true);
746 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
747 assert(StillOkay && "Can only be used with a derived-to-base conversion");
748 (void)StillOkay;
749
750 // Build up a textual representation of the ambiguous paths, e.g.,
751 // D -> B -> A, that will be used to illustrate the ambiguous
752 // conversions in the diagnostic. We only print one of the paths
753 // to each base class subobject.
754 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
755
756 Diag(Loc, AmbigiousBaseConvID)
757 << Derived << Base << PathDisplayStr << Range << Name;
758 return true;
759}
760
761bool
762Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000763 SourceLocation Loc, SourceRange Range,
764 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000765 return CheckDerivedToBaseConversion(Derived, Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000766 IgnoreAccess ? 0 :
767 diag::err_conv_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000768 diag::err_ambiguous_derived_to_base_conv,
769 Loc, Range, DeclarationName());
770}
771
772
773/// @brief Builds a string representing ambiguous paths from a
774/// specific derived class to different subobjects of the same base
775/// class.
776///
777/// This function builds a string that can be used in error messages
778/// to show the different paths that one can take through the
779/// inheritance hierarchy to go from the derived class to different
780/// subobjects of a base class. The result looks something like this:
781/// @code
782/// struct D -> struct B -> struct A
783/// struct D -> struct C -> struct A
784/// @endcode
785std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
786 std::string PathDisplayStr;
787 std::set<unsigned> DisplayedPaths;
788 for (CXXBasePaths::paths_iterator Path = Paths.begin();
789 Path != Paths.end(); ++Path) {
790 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
791 // We haven't displayed a path to this particular base
792 // class subobject yet.
793 PathDisplayStr += "\n ";
794 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
795 for (CXXBasePath::const_iterator Element = Path->begin();
796 Element != Path->end(); ++Element)
797 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
798 }
799 }
800
801 return PathDisplayStr;
802}
803
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000804//===----------------------------------------------------------------------===//
805// C++ class member Handling
806//===----------------------------------------------------------------------===//
807
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000808/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
809/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
810/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000811/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000812Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000813Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000814 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000815 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
816 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000817 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000818 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000819 Expr *BitWidth = static_cast<Expr*>(BW);
820 Expr *Init = static_cast<Expr*>(InitExpr);
821 SourceLocation Loc = D.getIdentifierLoc();
822
Sebastian Redl669d5d72008-11-14 23:42:31 +0000823 bool isFunc = D.isFunctionDeclarator();
824
John McCall67d1a672009-08-06 02:15:43 +0000825 assert(!DS.isFriendSpecified());
826
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000827 // C++ 9.2p6: A member shall not be declared to have automatic storage
828 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000829 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
830 // data members and cannot be applied to names declared const or static,
831 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000832 switch (DS.getStorageClassSpec()) {
833 case DeclSpec::SCS_unspecified:
834 case DeclSpec::SCS_typedef:
835 case DeclSpec::SCS_static:
836 // FALL THROUGH.
837 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000838 case DeclSpec::SCS_mutable:
839 if (isFunc) {
840 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000842 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000843 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Sebastian Redla11f42f2008-11-17 23:24:37 +0000845 // FIXME: It would be nicer if the keyword was ignored only for this
846 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000847 D.getMutableDeclSpec().ClearStorageClassSpecs();
848 } else {
849 QualType T = GetTypeForDeclarator(D, S);
850 diag::kind err = static_cast<diag::kind>(0);
851 if (T->isReferenceType())
852 err = diag::err_mutable_reference;
853 else if (T.isConstQualified())
854 err = diag::err_mutable_const;
855 if (err != 0) {
856 if (DS.getStorageClassSpecLoc().isValid())
857 Diag(DS.getStorageClassSpecLoc(), err);
858 else
859 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000860 // FIXME: It would be nicer if the keyword was ignored only for this
861 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000862 D.getMutableDeclSpec().ClearStorageClassSpecs();
863 }
864 }
865 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000866 default:
867 if (DS.getStorageClassSpecLoc().isValid())
868 Diag(DS.getStorageClassSpecLoc(),
869 diag::err_storageclass_invalid_for_member);
870 else
871 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
872 D.getMutableDeclSpec().ClearStorageClassSpecs();
873 }
874
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000875 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000876 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000877 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000878 // Check also for this case:
879 //
880 // typedef int f();
881 // f a;
882 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000883 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000884 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000885 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000886
Sebastian Redl669d5d72008-11-14 23:42:31 +0000887 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
888 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000889 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000890
891 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000892 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000893 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000894 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
895 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000896 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000897 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000898 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000899 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000900 if (!Member) {
901 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000902 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000903 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000904
905 // Non-instance-fields can't have a bitfield.
906 if (BitWidth) {
907 if (Member->isInvalidDecl()) {
908 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000909 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000910 // C++ 9.6p3: A bit-field shall not be a static member.
911 // "static member 'A' cannot be a bit-field"
912 Diag(Loc, diag::err_static_not_bitfield)
913 << Name << BitWidth->getSourceRange();
914 } else if (isa<TypedefDecl>(Member)) {
915 // "typedef member 'x' cannot be a bit-field"
916 Diag(Loc, diag::err_typedef_not_bitfield)
917 << Name << BitWidth->getSourceRange();
918 } else {
919 // A function typedef ("typedef int f(); f a;").
920 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
921 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000922 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000923 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner8b963ef2009-03-05 23:01:03 +0000926 DeleteExpr(BitWidth);
927 BitWidth = 0;
928 Member->setInvalidDecl();
929 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000930
931 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregor37b372b2009-08-20 22:52:58 +0000933 // If we have declared a member function template, set the access of the
934 // templated declaration as well.
935 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
936 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000937 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000938
Douglas Gregor10bd3682008-11-17 22:58:34 +0000939 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000940
Douglas Gregor021c3b32009-03-11 23:00:04 +0000941 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000942 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000943 if (Deleted) // FIXME: Source location is not very good.
944 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000945
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000946 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000947 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000948 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000949 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000950 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000951}
952
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000953/// \brief Find the direct and/or virtual base specifiers that
954/// correspond to the given base type, for use in base initialization
955/// within a constructor.
956static bool FindBaseInitializer(Sema &SemaRef,
957 CXXRecordDecl *ClassDecl,
958 QualType BaseType,
959 const CXXBaseSpecifier *&DirectBaseSpec,
960 const CXXBaseSpecifier *&VirtualBaseSpec) {
961 // First, check for a direct base class.
962 DirectBaseSpec = 0;
963 for (CXXRecordDecl::base_class_const_iterator Base
964 = ClassDecl->bases_begin();
965 Base != ClassDecl->bases_end(); ++Base) {
966 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
967 // We found a direct base of this type. That's what we're
968 // initializing.
969 DirectBaseSpec = &*Base;
970 break;
971 }
972 }
973
974 // Check for a virtual base class.
975 // FIXME: We might be able to short-circuit this if we know in advance that
976 // there are no virtual bases.
977 VirtualBaseSpec = 0;
978 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
979 // We haven't found a base yet; search the class hierarchy for a
980 // virtual base class.
981 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
982 /*DetectVirtual=*/false);
983 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
984 BaseType, Paths)) {
985 for (CXXBasePaths::paths_iterator Path = Paths.begin();
986 Path != Paths.end(); ++Path) {
987 if (Path->back().Base->isVirtual()) {
988 VirtualBaseSpec = Path->back().Base;
989 break;
990 }
991 }
992 }
993 }
994
995 return DirectBaseSpec || VirtualBaseSpec;
996}
997
Douglas Gregor7ad83902008-11-05 04:29:56 +0000998/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000999Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001000Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001001 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001002 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001003 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001004 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001005 SourceLocation IdLoc,
1006 SourceLocation LParenLoc,
1007 ExprTy **Args, unsigned NumArgs,
1008 SourceLocation *CommaLocs,
1009 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001010 if (!ConstructorD)
1011 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001013 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001014
1015 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001016 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001017 if (!Constructor) {
1018 // The user wrote a constructor initializer on a function that is
1019 // not a C++ constructor. Ignore the error for now, because we may
1020 // have more member initializers coming; we'll diagnose it just
1021 // once in ActOnMemInitializers.
1022 return true;
1023 }
1024
1025 CXXRecordDecl *ClassDecl = Constructor->getParent();
1026
1027 // C++ [class.base.init]p2:
1028 // Names in a mem-initializer-id are looked up in the scope of the
1029 // constructor’s class and, if not found in that scope, are looked
1030 // up in the scope containing the constructor’s
1031 // definition. [Note: if the constructor’s class contains a member
1032 // with the same name as a direct or virtual base class of the
1033 // class, a mem-initializer-id naming the member or base class and
1034 // composed of a single identifier refers to the class member. A
1035 // mem-initializer-id for the hidden base class may be specified
1036 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001037 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001038 // Look for a member, first.
1039 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001040 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001041 = ClassDecl->lookup(MemberOrBase);
1042 if (Result.first != Result.second)
1043 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001044
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001045 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001046
Eli Friedman59c04372009-07-29 19:44:27 +00001047 if (Member)
1048 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001049 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001050 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001051 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001052 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001053 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001054
1055 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001056 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001057 } else {
1058 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1059 LookupParsedName(R, S, &SS);
1060
1061 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1062 if (!TyD) {
1063 if (R.isAmbiguous()) return true;
1064
Douglas Gregor7a886e12010-01-19 06:46:48 +00001065 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1066 bool NotUnknownSpecialization = false;
1067 DeclContext *DC = computeDeclContext(SS, false);
1068 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1069 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1070
1071 if (!NotUnknownSpecialization) {
1072 // When the scope specifier can refer to a member of an unknown
1073 // specialization, we take it as a type name.
1074 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1075 *MemberOrBase, SS.getRange());
1076 R.clear();
1077 }
1078 }
1079
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001080 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001081 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001082 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1083 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1084 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1085 // We have found a non-static data member with a similar
1086 // name to what was typed; complain and initialize that
1087 // member.
1088 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1089 << MemberOrBase << true << R.getLookupName()
1090 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1091 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001092 Diag(Member->getLocation(), diag::note_previous_decl)
1093 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001094
1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1096 LParenLoc, RParenLoc);
1097 }
1098 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1099 const CXXBaseSpecifier *DirectBaseSpec;
1100 const CXXBaseSpecifier *VirtualBaseSpec;
1101 if (FindBaseInitializer(*this, ClassDecl,
1102 Context.getTypeDeclType(Type),
1103 DirectBaseSpec, VirtualBaseSpec)) {
1104 // We have found a direct or virtual base class with a
1105 // similar name to what was typed; complain and initialize
1106 // that base class.
1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108 << MemberOrBase << false << R.getLookupName()
1109 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1110 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001111
1112 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1113 : VirtualBaseSpec;
1114 Diag(BaseSpec->getSourceRange().getBegin(),
1115 diag::note_base_class_specified_here)
1116 << BaseSpec->getType()
1117 << BaseSpec->getSourceRange();
1118
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001119 TyD = Type;
1120 }
1121 }
1122 }
1123
Douglas Gregor7a886e12010-01-19 06:46:48 +00001124 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001125 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1126 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1127 return true;
1128 }
John McCall2b194412009-12-21 10:41:20 +00001129 }
1130
Douglas Gregor7a886e12010-01-19 06:46:48 +00001131 if (BaseType.isNull()) {
1132 BaseType = Context.getTypeDeclType(TyD);
1133 if (SS.isSet()) {
1134 NestedNameSpecifier *Qualifier =
1135 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001136
Douglas Gregor7a886e12010-01-19 06:46:48 +00001137 // FIXME: preserve source range information
1138 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1139 }
John McCall2b194412009-12-21 10:41:20 +00001140 }
1141 }
Mike Stump1eb44332009-09-09 15:08:12 +00001142
John McCalla93c9342009-12-07 02:54:59 +00001143 if (!TInfo)
1144 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001145
John McCalla93c9342009-12-07 02:54:59 +00001146 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001147 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001148}
1149
John McCallb4190042009-11-04 23:02:40 +00001150/// Checks an initializer expression for use of uninitialized fields, such as
1151/// containing the field that is being initialized. Returns true if there is an
1152/// uninitialized field was used an updates the SourceLocation parameter; false
1153/// otherwise.
1154static bool InitExprContainsUninitializedFields(const Stmt* S,
1155 const FieldDecl* LhsField,
1156 SourceLocation* L) {
1157 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1158 if (ME) {
1159 const NamedDecl* RhsField = ME->getMemberDecl();
1160 if (RhsField == LhsField) {
1161 // Initializing a field with itself. Throw a warning.
1162 // But wait; there are exceptions!
1163 // Exception #1: The field may not belong to this record.
1164 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1165 const Expr* base = ME->getBase();
1166 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1167 // Even though the field matches, it does not belong to this record.
1168 return false;
1169 }
1170 // None of the exceptions triggered; return true to indicate an
1171 // uninitialized field was used.
1172 *L = ME->getMemberLoc();
1173 return true;
1174 }
1175 }
1176 bool found = false;
1177 for (Stmt::const_child_iterator it = S->child_begin();
1178 it != S->child_end() && found == false;
1179 ++it) {
1180 if (isa<CallExpr>(S)) {
1181 // Do not descend into function calls or constructors, as the use
1182 // of an uninitialized field may be valid. One would have to inspect
1183 // the contents of the function/ctor to determine if it is safe or not.
1184 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1185 // may be safe, depending on what the function/ctor does.
1186 continue;
1187 }
1188 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1189 }
1190 return found;
1191}
1192
Eli Friedman59c04372009-07-29 19:44:27 +00001193Sema::MemInitResult
1194Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1195 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001196 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001197 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001198 // Diagnose value-uses of fields to initialize themselves, e.g.
1199 // foo(foo)
1200 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001201 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001202 for (unsigned i = 0; i < NumArgs; ++i) {
1203 SourceLocation L;
1204 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1205 // FIXME: Return true in the case when other fields are used before being
1206 // uninitialized. For example, let this field be the i'th field. When
1207 // initializing the i'th field, throw a warning if any of the >= i'th
1208 // fields are used, as they are not yet initialized.
1209 // Right now we are only handling the case where the i'th field uses
1210 // itself in its initializer.
1211 Diag(L, diag::warn_field_is_uninit);
1212 }
1213 }
1214
Eli Friedman59c04372009-07-29 19:44:27 +00001215 bool HasDependentArg = false;
1216 for (unsigned i = 0; i < NumArgs; i++)
1217 HasDependentArg |= Args[i]->isTypeDependent();
1218
Eli Friedman59c04372009-07-29 19:44:27 +00001219 QualType FieldType = Member->getType();
1220 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1221 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001222 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001223 if (FieldType->isDependentType() || HasDependentArg) {
1224 // Can't check initialization for a member of dependent type or when
1225 // any of the arguments are type-dependent expressions.
1226 OwningExprResult Init
1227 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1228 RParenLoc));
1229
1230 // Erase any temporaries within this evaluation context; we're not
1231 // going to track them in the AST, since we'll be rebuilding the
1232 // ASTs during template instantiation.
1233 ExprTemporaries.erase(
1234 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1235 ExprTemporaries.end());
1236
1237 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1238 LParenLoc,
1239 Init.takeAs<Expr>(),
1240 RParenLoc);
1241
Douglas Gregor7ad83902008-11-05 04:29:56 +00001242 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001243
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001244 if (Member->isInvalidDecl())
1245 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001246
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001247 // Initialize the member.
1248 InitializedEntity MemberEntity =
1249 InitializedEntity::InitializeMember(Member, 0);
1250 InitializationKind Kind =
1251 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1252
1253 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1254
1255 OwningExprResult MemberInit =
1256 InitSeq.Perform(*this, MemberEntity, Kind,
1257 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1258 if (MemberInit.isInvalid())
1259 return true;
1260
1261 // C++0x [class.base.init]p7:
1262 // The initialization of each base and member constitutes a
1263 // full-expression.
1264 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1265 if (MemberInit.isInvalid())
1266 return true;
1267
1268 // If we are in a dependent context, template instantiation will
1269 // perform this type-checking again. Just save the arguments that we
1270 // received in a ParenListExpr.
1271 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1272 // of the information that we have about the member
1273 // initializer. However, deconstructing the ASTs is a dicey process,
1274 // and this approach is far more likely to get the corner cases right.
1275 if (CurContext->isDependentContext()) {
1276 // Bump the reference count of all of the arguments.
1277 for (unsigned I = 0; I != NumArgs; ++I)
1278 Args[I]->Retain();
1279
1280 OwningExprResult Init
1281 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1282 RParenLoc));
1283 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1284 LParenLoc,
1285 Init.takeAs<Expr>(),
1286 RParenLoc);
1287 }
1288
Douglas Gregor802ab452009-12-02 22:36:29 +00001289 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001290 LParenLoc,
1291 MemberInit.takeAs<Expr>(),
1292 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001293}
1294
1295Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001296Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001297 Expr **Args, unsigned NumArgs,
1298 SourceLocation LParenLoc, SourceLocation RParenLoc,
1299 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001300 bool HasDependentArg = false;
1301 for (unsigned i = 0; i < NumArgs; i++)
1302 HasDependentArg |= Args[i]->isTypeDependent();
1303
John McCalla93c9342009-12-07 02:54:59 +00001304 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001305 if (BaseType->isDependentType() || HasDependentArg) {
1306 // Can't check initialization for a base of dependent type or when
1307 // any of the arguments are type-dependent expressions.
1308 OwningExprResult BaseInit
1309 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1310 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 // Erase any temporaries within this evaluation context; we're not
1313 // going to track them in the AST, since we'll be rebuilding the
1314 // ASTs during template instantiation.
1315 ExprTemporaries.erase(
1316 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1317 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001319 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1320 LParenLoc,
1321 BaseInit.takeAs<Expr>(),
1322 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001323 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001324
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001325 if (!BaseType->isRecordType())
1326 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1327 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1328
1329 // C++ [class.base.init]p2:
1330 // [...] Unless the mem-initializer-id names a nonstatic data
1331 // member of the constructor’s class or a direct or virtual base
1332 // of that class, the mem-initializer is ill-formed. A
1333 // mem-initializer-list can initialize a base class using any
1334 // name that denotes that base class type.
1335
1336 // Check for direct and virtual base classes.
1337 const CXXBaseSpecifier *DirectBaseSpec = 0;
1338 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1339 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1340 VirtualBaseSpec);
1341
1342 // C++ [base.class.init]p2:
1343 // If a mem-initializer-id is ambiguous because it designates both
1344 // a direct non-virtual base class and an inherited virtual base
1345 // class, the mem-initializer is ill-formed.
1346 if (DirectBaseSpec && VirtualBaseSpec)
1347 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1348 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1349 // C++ [base.class.init]p2:
1350 // Unless the mem-initializer-id names a nonstatic data membeer of the
1351 // constructor's class ot a direst or virtual base of that class, the
1352 // mem-initializer is ill-formed.
1353 if (!DirectBaseSpec && !VirtualBaseSpec)
1354 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1355 << BaseType << ClassDecl->getNameAsCString()
1356 << BaseTInfo->getTypeLoc().getSourceRange();
1357
1358 CXXBaseSpecifier *BaseSpec
1359 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1360 if (!BaseSpec)
1361 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1362
1363 // Initialize the base.
1364 InitializedEntity BaseEntity =
1365 InitializedEntity::InitializeBase(Context, BaseSpec);
1366 InitializationKind Kind =
1367 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1368
1369 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1370
1371 OwningExprResult BaseInit =
1372 InitSeq.Perform(*this, BaseEntity, Kind,
1373 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1374 if (BaseInit.isInvalid())
1375 return true;
1376
1377 // C++0x [class.base.init]p7:
1378 // The initialization of each base and member constitutes a
1379 // full-expression.
1380 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1381 if (BaseInit.isInvalid())
1382 return true;
1383
1384 // If we are in a dependent context, template instantiation will
1385 // perform this type-checking again. Just save the arguments that we
1386 // received in a ParenListExpr.
1387 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1388 // of the information that we have about the base
1389 // initializer. However, deconstructing the ASTs is a dicey process,
1390 // and this approach is far more likely to get the corner cases right.
1391 if (CurContext->isDependentContext()) {
1392 // Bump the reference count of all of the arguments.
1393 for (unsigned I = 0; I != NumArgs; ++I)
1394 Args[I]->Retain();
1395
1396 OwningExprResult Init
1397 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1398 RParenLoc));
1399 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1400 LParenLoc,
1401 Init.takeAs<Expr>(),
1402 RParenLoc);
1403 }
1404
1405 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1406 LParenLoc,
1407 BaseInit.takeAs<Expr>(),
1408 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001409}
1410
Eli Friedman80c30da2009-11-09 19:20:36 +00001411bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001412Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001413 CXXBaseOrMemberInitializer **Initializers,
1414 unsigned NumInitializers,
1415 bool IsImplicitConstructor,
1416 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001417 // We need to build the initializer AST according to order of construction
1418 // and not what user specified in the Initializers list.
1419 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1420 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1421 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1422 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001423 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001425 for (unsigned i = 0; i < NumInitializers; i++) {
1426 CXXBaseOrMemberInitializer *Member = Initializers[i];
1427 if (Member->isBaseInitializer()) {
1428 if (Member->getBaseClass()->isDependentType())
1429 HasDependentBaseInit = true;
1430 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1431 } else {
1432 AllBaseFields[Member->getMember()] = Member;
1433 }
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001436 if (HasDependentBaseInit) {
1437 // FIXME. This does not preserve the ordering of the initializers.
1438 // Try (with -Wreorder)
1439 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001440 // template<class X> struct B : A<X> {
1441 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001442 // int x1;
1443 // };
1444 // B<int> x;
1445 // On seeing one dependent type, we should essentially exit this routine
1446 // while preserving user-declared initializer list. When this routine is
1447 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001448 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001450 // If we have a dependent base initialization, we can't determine the
1451 // association between initializers and bases; just dump the known
1452 // initializers into the list, and don't try to deal with other bases.
1453 for (unsigned i = 0; i < NumInitializers; i++) {
1454 CXXBaseOrMemberInitializer *Member = Initializers[i];
1455 if (Member->isBaseInitializer())
1456 AllToInit.push_back(Member);
1457 }
1458 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001459 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1460
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001461 // Push virtual bases before others.
1462 for (CXXRecordDecl::base_class_iterator VBase =
1463 ClassDecl->vbases_begin(),
1464 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1465 if (VBase->getType()->isDependentType())
1466 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001467 if (CXXBaseOrMemberInitializer *Value
1468 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001469 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001470 } else if (!AnyErrors) {
1471 InitializedEntity InitEntity
1472 = InitializedEntity::InitializeBase(Context, VBase);
1473 InitializationKind InitKind
1474 = InitializationKind::CreateDefault(Constructor->getLocation());
1475 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1476 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1477 MultiExprArg(*this, 0, 0));
1478 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1479 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001480 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001481 continue;
1482 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001483
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001484 // Don't attach synthesized base initializers in a dependent
1485 // context; they'll be checked again at template instantiation
1486 // time.
1487 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001488 continue;
1489
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001490 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001491 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001492 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001493 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001494 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001495 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001496 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001497 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001498 }
1499 }
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001501 for (CXXRecordDecl::base_class_iterator Base =
1502 ClassDecl->bases_begin(),
1503 E = ClassDecl->bases_end(); Base != E; ++Base) {
1504 // Virtuals are in the virtual base list and already constructed.
1505 if (Base->isVirtual())
1506 continue;
1507 // Skip dependent types.
1508 if (Base->getType()->isDependentType())
1509 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001510 if (CXXBaseOrMemberInitializer *Value
1511 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001512 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001513 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001514 else if (!AnyErrors) {
1515 InitializedEntity InitEntity
1516 = InitializedEntity::InitializeBase(Context, Base);
1517 InitializationKind InitKind
1518 = InitializationKind::CreateDefault(Constructor->getLocation());
1519 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1520 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1521 MultiExprArg(*this, 0, 0));
1522 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1523 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001524 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001525 continue;
1526 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001527
1528 // Don't attach synthesized base initializers in a dependent
1529 // context; they'll be regenerated at template instantiation
1530 // time.
1531 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001532 continue;
1533
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001534 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001535 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001536 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001537 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001538 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001539 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001540 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001541 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001542 }
1543 }
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001546 // non-static data members.
1547 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1548 E = ClassDecl->field_end(); Field != E; ++Field) {
1549 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001550 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001551 Field->getType()->getAs<RecordType>()) {
1552 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001553 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001554 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001555 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1556 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1557 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1558 // set to the anonymous union data member used in the initializer
1559 // list.
1560 Value->setMember(*Field);
1561 Value->setAnonUnionMember(*FA);
1562 AllToInit.push_back(Value);
1563 break;
1564 }
1565 }
1566 }
1567 continue;
1568 }
1569 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1570 AllToInit.push_back(Value);
1571 continue;
1572 }
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001574 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001575 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001576
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001577 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001578 if (FT->getAs<RecordType>()) {
1579 InitializedEntity InitEntity
1580 = InitializedEntity::InitializeMember(*Field);
1581 InitializationKind InitKind
1582 = InitializationKind::CreateDefault(Constructor->getLocation());
1583
1584 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1585 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1586 MultiExprArg(*this, 0, 0));
1587 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1588 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001589 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001590 continue;
1591 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001592
1593 // Don't attach synthesized member initializers in a dependent
1594 // context; they'll be regenerated a template instantiation
1595 // time.
1596 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001597 continue;
1598
Mike Stump1eb44332009-09-09 15:08:12 +00001599 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001600 new (Context) CXXBaseOrMemberInitializer(Context,
1601 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001602 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001603 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001604 SourceLocation());
1605
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001606 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001607 }
1608 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001609 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001610 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1611 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001612 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001613 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001614 }
1615 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001616 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001617 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1618 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001619 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001620 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001621 }
1622 }
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001624 NumInitializers = AllToInit.size();
1625 if (NumInitializers > 0) {
1626 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1627 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1628 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001630 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1631 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1632 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1633 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001634
1635 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001636}
1637
Eli Friedman6347f422009-07-21 19:28:10 +00001638static void *GetKeyForTopLevelField(FieldDecl *Field) {
1639 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001640 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001641 if (RT->getDecl()->isAnonymousStructOrUnion())
1642 return static_cast<void *>(RT->getDecl());
1643 }
1644 return static_cast<void *>(Field);
1645}
1646
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001647static void *GetKeyForBase(QualType BaseType) {
1648 if (const RecordType *RT = BaseType->getAs<RecordType>())
1649 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001651 assert(0 && "Unexpected base type!");
1652 return 0;
1653}
1654
Mike Stump1eb44332009-09-09 15:08:12 +00001655static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001656 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001657 // For fields injected into the class via declaration of an anonymous union,
1658 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001659 if (Member->isMemberInitializer()) {
1660 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Eli Friedman49c16da2009-11-09 01:05:47 +00001662 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001663 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001664 // in AnonUnionMember field.
1665 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1666 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001667 if (Field->getDeclContext()->isRecord()) {
1668 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1669 if (RD->isAnonymousStructOrUnion())
1670 return static_cast<void *>(RD);
1671 }
1672 return static_cast<void *>(Field);
1673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001675 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001676}
1677
John McCall6aee6212009-11-04 23:13:52 +00001678/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001679void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001680 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001681 MemInitTy **MemInits, unsigned NumMemInits,
1682 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001683 if (!ConstructorDecl)
1684 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001685
1686 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
1688 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001689 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Anders Carlssona7b35212009-03-25 02:58:17 +00001691 if (!Constructor) {
1692 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1693 return;
1694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001696 if (!Constructor->isDependentContext()) {
1697 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1698 bool err = false;
1699 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001700 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001701 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1702 void *KeyToMember = GetKeyForMember(Member);
1703 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1704 if (!PrevMember) {
1705 PrevMember = Member;
1706 continue;
1707 }
1708 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001709 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001710 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001711 << Field->getNameAsString()
1712 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001713 else {
1714 Type *BaseClass = Member->getBaseClass();
1715 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001716 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001717 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001718 << QualType(BaseClass, 0)
1719 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001720 }
1721 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1722 << 0;
1723 err = true;
1724 }
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001726 if (err)
1727 return;
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Eli Friedman49c16da2009-11-09 01:05:47 +00001730 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001731 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001732 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001734 if (Constructor->isDependentContext())
1735 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001736
1737 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001738 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001739 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001740 Diagnostic::Ignored)
1741 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001743 // Also issue warning if order of ctor-initializer list does not match order
1744 // of 1) base class declarations and 2) order of non-static data members.
1745 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001747 CXXRecordDecl *ClassDecl
1748 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1749 // Push virtual bases before others.
1750 for (CXXRecordDecl::base_class_iterator VBase =
1751 ClassDecl->vbases_begin(),
1752 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001753 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001755 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1756 E = ClassDecl->bases_end(); Base != E; ++Base) {
1757 // Virtuals are alread in the virtual base list and are constructed
1758 // first.
1759 if (Base->isVirtual())
1760 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001761 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001764 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1765 E = ClassDecl->field_end(); Field != E; ++Field)
1766 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001768 int Last = AllBaseOrMembers.size();
1769 int curIndex = 0;
1770 CXXBaseOrMemberInitializer *PrevMember = 0;
1771 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001772 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001773 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1774 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001775
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001776 for (; curIndex < Last; curIndex++)
1777 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1778 break;
1779 if (curIndex == Last) {
1780 assert(PrevMember && "Member not in member list?!");
1781 // Initializer as specified in ctor-initializer list is out of order.
1782 // Issue a warning diagnostic.
1783 if (PrevMember->isBaseInitializer()) {
1784 // Diagnostics is for an initialized base class.
1785 Type *BaseClass = PrevMember->getBaseClass();
1786 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001787 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001788 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001789 } else {
1790 FieldDecl *Field = PrevMember->getMember();
1791 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001792 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001793 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001794 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001795 // Also the note!
1796 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001797 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001798 diag::note_fieldorbase_initialized_here) << 0
1799 << Field->getNameAsString();
1800 else {
1801 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001802 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001803 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001804 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 }
1806 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001807 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001808 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001809 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001810 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001811 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001812}
1813
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001814void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001815Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1816 // Ignore dependent destructors.
1817 if (Destructor->isDependentContext())
1818 return;
1819
1820 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Anders Carlsson9f853df2009-11-17 04:44:12 +00001822 // Non-static data members.
1823 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1824 E = ClassDecl->field_end(); I != E; ++I) {
1825 FieldDecl *Field = *I;
1826
1827 QualType FieldType = Context.getBaseElementType(Field->getType());
1828
1829 const RecordType* RT = FieldType->getAs<RecordType>();
1830 if (!RT)
1831 continue;
1832
1833 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1834 if (FieldClassDecl->hasTrivialDestructor())
1835 continue;
1836
1837 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1838 MarkDeclarationReferenced(Destructor->getLocation(),
1839 const_cast<CXXDestructorDecl*>(Dtor));
1840 }
1841
1842 // Bases.
1843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1844 E = ClassDecl->bases_end(); Base != E; ++Base) {
1845 // Ignore virtual bases.
1846 if (Base->isVirtual())
1847 continue;
1848
1849 // Ignore trivial destructors.
1850 CXXRecordDecl *BaseClassDecl
1851 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1852 if (BaseClassDecl->hasTrivialDestructor())
1853 continue;
1854
1855 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1856 MarkDeclarationReferenced(Destructor->getLocation(),
1857 const_cast<CXXDestructorDecl*>(Dtor));
1858 }
1859
1860 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001861 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1862 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001863 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001864 CXXRecordDecl *BaseClassDecl
1865 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1866 if (BaseClassDecl->hasTrivialDestructor())
1867 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001868
1869 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1870 MarkDeclarationReferenced(Destructor->getLocation(),
1871 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001872 }
1873}
1874
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001875void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001876 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001877 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001879 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001880
1881 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001882 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001883 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001884}
1885
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001886namespace {
1887 /// PureVirtualMethodCollector - traverses a class and its superclasses
1888 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001889 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001890 ASTContext &Context;
1891
Sebastian Redldfe292d2009-03-22 21:28:55 +00001892 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001893 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001894
1895 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001896 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001898 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001900 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001901 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001902 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001904 MethodList List;
1905 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001907 // Copy the temporary list to methods, and make sure to ignore any
1908 // null entries.
1909 for (size_t i = 0, e = List.size(); i != e; ++i) {
1910 if (List[i])
1911 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001912 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001913 }
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001915 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001917 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1918 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001919 };
Mike Stump1eb44332009-09-09 15:08:12 +00001920
1921 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001922 MethodList& Methods) {
1923 // First, collect the pure virtual methods for the base classes.
1924 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1925 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001926 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001927 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 if (BaseDecl && BaseDecl->isAbstract())
1929 Collect(BaseDecl, Methods);
1930 }
1931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001933 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001934 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001936 MethodSetTy OverriddenMethods;
1937 size_t MethodsSize = Methods.size();
1938
Mike Stump1eb44332009-09-09 15:08:12 +00001939 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001940 i != e; ++i) {
1941 // Traverse the record, looking for methods.
1942 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001943 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001944 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001945 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Anders Carlsson27823022009-10-18 19:34:08 +00001947 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001948 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1949 E = MD->end_overridden_methods(); I != E; ++I) {
1950 // Keep track of the overridden methods.
1951 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001952 }
1953 }
1954 }
Mike Stump1eb44332009-09-09 15:08:12 +00001955
1956 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001957 // overridden.
1958 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1959 if (OverriddenMethods.count(Methods[i]))
1960 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001963 }
1964}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001965
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001966
Mike Stump1eb44332009-09-09 15:08:12 +00001967bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001968 unsigned DiagID, AbstractDiagSelID SelID,
1969 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001970 if (SelID == -1)
1971 return RequireNonAbstractType(Loc, T,
1972 PDiag(DiagID), CurrentRD);
1973 else
1974 return RequireNonAbstractType(Loc, T,
1975 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001976}
1977
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001978bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1979 const PartialDiagnostic &PD,
1980 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001981 if (!getLangOptions().CPlusPlus)
1982 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Anders Carlsson11f21a02009-03-23 19:10:31 +00001984 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001985 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001986 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenek6217b802009-07-29 21:53:49 +00001988 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001989 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001990 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001991 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001993 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001994 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001995 }
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenek6217b802009-07-29 21:53:49 +00001997 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001998 if (!RT)
1999 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002001 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2002 if (!RD)
2003 return false;
2004
Anders Carlssone65a3c82009-03-24 17:23:42 +00002005 if (CurrentRD && CurrentRD != RD)
2006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002008 if (!RD->isAbstract())
2009 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002011 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002013 // Check if we've already emitted the list of pure virtual functions for this
2014 // class.
2015 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2016 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002018 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
2020 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002021 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2022 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002023
2024 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002025 MD->getDeclName();
2026 }
2027
2028 if (!PureVirtualClassDiagSet)
2029 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2030 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002032 return true;
2033}
2034
Anders Carlsson8211eff2009-03-24 01:19:16 +00002035namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002036 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002037 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2038 Sema &SemaRef;
2039 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Anders Carlssone65a3c82009-03-24 17:23:42 +00002041 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002042 bool Invalid = false;
2043
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002044 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2045 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002046 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002047
Anders Carlsson8211eff2009-03-24 01:19:16 +00002048 return Invalid;
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Anders Carlssone65a3c82009-03-24 17:23:42 +00002051 public:
2052 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2053 : SemaRef(SemaRef), AbstractClass(ac) {
2054 Visit(SemaRef.Context.getTranslationUnitDecl());
2055 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002056
Anders Carlssone65a3c82009-03-24 17:23:42 +00002057 bool VisitFunctionDecl(const FunctionDecl *FD) {
2058 if (FD->isThisDeclarationADefinition()) {
2059 // No need to do the check if we're in a definition, because it requires
2060 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002062 return VisitDeclContext(FD);
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Anders Carlssone65a3c82009-03-24 17:23:42 +00002065 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002066 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002067 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002068 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2069 diag::err_abstract_type_in_decl,
2070 Sema::AbstractReturnType,
2071 AbstractClass);
2072
Mike Stump1eb44332009-09-09 15:08:12 +00002073 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002074 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002075 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002076 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002077 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002078 VD->getOriginalType(),
2079 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002080 Sema::AbstractParamType,
2081 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002082 }
2083
2084 return Invalid;
2085 }
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Anders Carlssone65a3c82009-03-24 17:23:42 +00002087 bool VisitDecl(const Decl* D) {
2088 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2089 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 return false;
2092 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002093 };
2094}
2095
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002096/// \brief Perform semantic checks on a class definition that has been
2097/// completing, introducing implicitly-declared members, checking for
2098/// abstract types, etc.
2099void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2100 if (!Record || Record->isInvalidDecl())
2101 return;
2102
Eli Friedmanff2d8782009-12-16 20:00:27 +00002103 if (!Record->isDependentType())
2104 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002105
Eli Friedmanff2d8782009-12-16 20:00:27 +00002106 if (Record->isInvalidDecl())
2107 return;
2108
John McCall233a6412010-01-28 07:38:46 +00002109 // Set access bits correctly on the directly-declared conversions.
2110 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2111 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2112 Convs->setAccess(I, (*I)->getAccess());
2113
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002114 if (!Record->isAbstract()) {
2115 // Collect all the pure virtual methods and see if this is an abstract
2116 // class after all.
2117 PureVirtualMethodCollector Collector(Context, Record);
2118 if (!Collector.empty())
2119 Record->setAbstract(true);
2120 }
2121
2122 if (Record->isAbstract())
2123 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002124}
2125
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002126void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002127 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002128 SourceLocation LBrac,
2129 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002130 if (!TagDecl)
2131 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor42af25f2009-05-11 19:58:34 +00002133 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002134
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002135 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002136 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002137 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002138
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002139 CheckCompletedCXXClass(
2140 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002141}
2142
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002143/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2144/// special functions, such as the default constructor, copy
2145/// constructor, or destructor, to the given C++ class (C++
2146/// [special]p1). This routine can only be executed just before the
2147/// definition of the class is complete.
2148void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002149 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002151
Sebastian Redl465226e2009-05-27 22:11:52 +00002152 // FIXME: Implicit declarations have exception specifications, which are
2153 // the union of the specifications of the implicitly called functions.
2154
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002155 if (!ClassDecl->hasUserDeclaredConstructor()) {
2156 // C++ [class.ctor]p5:
2157 // A default constructor for a class X is a constructor of class X
2158 // that can be called without an argument. If there is no
2159 // user-declared constructor for class X, a default constructor is
2160 // implicitly declared. An implicitly-declared default constructor
2161 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002162 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002163 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002164 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002165 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002166 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002167 Context.getFunctionType(Context.VoidTy,
2168 0, 0, false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002169 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002170 /*isExplicit=*/false,
2171 /*isInline=*/true,
2172 /*isImplicitlyDeclared=*/true);
2173 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002174 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002175 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002176 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177 }
2178
2179 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2180 // C++ [class.copy]p4:
2181 // If the class definition does not explicitly declare a copy
2182 // constructor, one is declared implicitly.
2183
2184 // C++ [class.copy]p5:
2185 // The implicitly-declared copy constructor for a class X will
2186 // have the form
2187 //
2188 // X::X(const X&)
2189 //
2190 // if
2191 bool HasConstCopyConstructor = true;
2192
2193 // -- each direct or virtual base class B of X has a copy
2194 // constructor whose first parameter is of type const B& or
2195 // const volatile B&, and
2196 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2197 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2198 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002200 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002201 = BaseClassDecl->hasConstCopyConstructor(Context);
2202 }
2203
2204 // -- for all the nonstatic data members of X that are of a
2205 // class type M (or array thereof), each such class type
2206 // has a copy constructor whose first parameter is of type
2207 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002208 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2209 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002210 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002211 QualType FieldType = (*Field)->getType();
2212 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2213 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002214 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002215 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002216 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002217 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002218 = FieldClassDecl->hasConstCopyConstructor(Context);
2219 }
2220 }
2221
Sebastian Redl64b45f72009-01-05 20:52:13 +00002222 // Otherwise, the implicitly declared copy constructor will have
2223 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002224 //
2225 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002226 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002227 if (HasConstCopyConstructor)
2228 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002229 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002230
Sebastian Redl64b45f72009-01-05 20:52:13 +00002231 // An implicitly-declared copy constructor is an inline public
2232 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002233 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002234 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002235 CXXConstructorDecl *CopyConstructor
2236 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002237 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002238 Context.getFunctionType(Context.VoidTy,
2239 &ArgType, 1,
2240 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002241 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002242 /*isExplicit=*/false,
2243 /*isInline=*/true,
2244 /*isImplicitlyDeclared=*/true);
2245 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002246 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002247 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002248
2249 // Add the parameter to the constructor.
2250 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2251 ClassDecl->getLocation(),
2252 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002253 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002254 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002255 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002256 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002257 }
2258
Sebastian Redl64b45f72009-01-05 20:52:13 +00002259 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2260 // Note: The following rules are largely analoguous to the copy
2261 // constructor rules. Note that virtual bases are not taken into account
2262 // for determining the argument type of the operator. Note also that
2263 // operators taking an object instead of a reference are allowed.
2264 //
2265 // C++ [class.copy]p10:
2266 // If the class definition does not explicitly declare a copy
2267 // assignment operator, one is declared implicitly.
2268 // The implicitly-defined copy assignment operator for a class X
2269 // will have the form
2270 //
2271 // X& X::operator=(const X&)
2272 //
2273 // if
2274 bool HasConstCopyAssignment = true;
2275
2276 // -- each direct base class B of X has a copy assignment operator
2277 // whose parameter is of type const B&, const volatile B& or B,
2278 // and
2279 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2280 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002281 assert(!Base->getType()->isDependentType() &&
2282 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002283 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002285 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002286 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002287 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002288 }
2289
2290 // -- for all the nonstatic data members of X that are of a class
2291 // type M (or array thereof), each such class type has a copy
2292 // assignment operator whose parameter is of type const M&,
2293 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002294 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2295 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002296 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002297 QualType FieldType = (*Field)->getType();
2298 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2299 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002300 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002301 const CXXRecordDecl *FieldClassDecl
2302 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002303 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002304 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002305 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002306 }
2307 }
2308
2309 // Otherwise, the implicitly declared copy assignment operator will
2310 // have the form
2311 //
2312 // X& X::operator=(X&)
2313 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002314 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002315 if (HasConstCopyAssignment)
2316 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002317 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002318
2319 // An implicitly-declared copy assignment operator is an inline public
2320 // member of its class.
2321 DeclarationName Name =
2322 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2323 CXXMethodDecl *CopyAssignment =
2324 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2325 Context.getFunctionType(RetType, &ArgType, 1,
2326 false, 0),
John McCalla93c9342009-12-07 02:54:59 +00002327 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002328 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002329 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002330 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002331 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002332
2333 // Add the parameter to the operator.
2334 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2335 ClassDecl->getLocation(),
2336 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002337 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002338 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00002339 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002340
2341 // Don't call addedAssignmentOperator. There is no way to distinguish an
2342 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002343 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002344 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002345 }
2346
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002347 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002348 // C++ [class.dtor]p2:
2349 // If a class has no user-declared destructor, a destructor is
2350 // declared implicitly. An implicitly-declared destructor is an
2351 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002352 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002353 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002354 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002355 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002356 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002357 Context.getFunctionType(Context.VoidTy,
2358 0, 0, false, 0),
2359 /*isInline=*/true,
2360 /*isImplicitlyDeclared=*/true);
2361 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002362 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002363 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002364 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002365
2366 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002367 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002368}
2369
Douglas Gregor6569d682009-05-27 23:11:45 +00002370void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002371 Decl *D = TemplateD.getAs<Decl>();
2372 if (!D)
2373 return;
2374
2375 TemplateParameterList *Params = 0;
2376 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2377 Params = Template->getTemplateParameters();
2378 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2379 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2380 Params = PartialSpec->getTemplateParameters();
2381 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002382 return;
2383
Douglas Gregor6569d682009-05-27 23:11:45 +00002384 for (TemplateParameterList::iterator Param = Params->begin(),
2385 ParamEnd = Params->end();
2386 Param != ParamEnd; ++Param) {
2387 NamedDecl *Named = cast<NamedDecl>(*Param);
2388 if (Named->getDeclName()) {
2389 S->AddDecl(DeclPtrTy::make(Named));
2390 IdResolver.AddDecl(Named);
2391 }
2392 }
2393}
2394
John McCall7a1dc562009-12-19 10:49:29 +00002395void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2396 if (!RecordD) return;
2397 AdjustDeclIfTemplate(RecordD);
2398 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2399 PushDeclContext(S, Record);
2400}
2401
2402void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2403 if (!RecordD) return;
2404 PopDeclContext();
2405}
2406
Douglas Gregor72b505b2008-12-16 21:30:33 +00002407/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2408/// parsing a top-level (non-nested) C++ class, and we are now
2409/// parsing those parts of the given Method declaration that could
2410/// not be parsed earlier (C++ [class.mem]p2), such as default
2411/// arguments. This action should enter the scope of the given
2412/// Method declaration as if we had just parsed the qualified method
2413/// name. However, it should not bring the parameters into scope;
2414/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002415void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002416}
2417
2418/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2419/// C++ method declaration. We're (re-)introducing the given
2420/// function parameter into scope for use in parsing later parts of
2421/// the method declaration. For example, we could see an
2422/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002423void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002424 if (!ParamD)
2425 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Chris Lattnerb28317a2009-03-28 19:18:32 +00002427 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002428
2429 // If this parameter has an unparsed default argument, clear it out
2430 // to make way for the parsed default argument.
2431 if (Param->hasUnparsedDefaultArg())
2432 Param->setDefaultArg(0);
2433
Chris Lattnerb28317a2009-03-28 19:18:32 +00002434 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002435 if (Param->getDeclName())
2436 IdResolver.AddDecl(Param);
2437}
2438
2439/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2440/// processing the delayed method declaration for Method. The method
2441/// declaration is now considered finished. There may be a separate
2442/// ActOnStartOfFunctionDef action later (not necessarily
2443/// immediately!) for this method, if it was also defined inside the
2444/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002445void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002446 if (!MethodD)
2447 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002448
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002449 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Chris Lattnerb28317a2009-03-28 19:18:32 +00002451 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002452
2453 // Now that we have our default arguments, check the constructor
2454 // again. It could produce additional diagnostics or affect whether
2455 // the class has implicitly-declared destructors, among other
2456 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002457 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2458 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002459
2460 // Check the default arguments, which we may have added.
2461 if (!Method->isInvalidDecl())
2462 CheckCXXDefaultArguments(Method);
2463}
2464
Douglas Gregor42a552f2008-11-05 20:51:48 +00002465/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002466/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002467/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002468/// emit diagnostics and set the invalid bit to true. In any case, the type
2469/// will be updated to reflect a well-formed type for the constructor and
2470/// returned.
2471QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2472 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002473 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002474
2475 // C++ [class.ctor]p3:
2476 // A constructor shall not be virtual (10.3) or static (9.4). A
2477 // constructor can be invoked for a const, volatile or const
2478 // volatile object. A constructor shall not be declared const,
2479 // volatile, or const volatile (9.3.2).
2480 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002481 if (!D.isInvalidType())
2482 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2483 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2484 << SourceRange(D.getIdentifierLoc());
2485 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002486 }
2487 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002488 if (!D.isInvalidType())
2489 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2490 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2491 << SourceRange(D.getIdentifierLoc());
2492 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002493 SC = FunctionDecl::None;
2494 }
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Chris Lattner65401802009-04-25 08:28:21 +00002496 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2497 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002498 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002499 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2500 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002501 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002502 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2503 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002504 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2506 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002507 }
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor42a552f2008-11-05 20:51:48 +00002509 // Rebuild the function type "R" without any type qualifiers (in
2510 // case any of the errors above fired) and with "void" as the
2511 // return type, since constructors don't have return types. We
2512 // *always* have to do this, because GetTypeForDeclarator will
2513 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002514 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002515 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2516 Proto->getNumArgs(),
2517 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002518}
2519
Douglas Gregor72b505b2008-12-16 21:30:33 +00002520/// CheckConstructor - Checks a fully-formed constructor for
2521/// well-formedness, issuing any diagnostics required. Returns true if
2522/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002523void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002524 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002525 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2526 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002527 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002528
2529 // C++ [class.copy]p3:
2530 // A declaration of a constructor for a class X is ill-formed if
2531 // its first parameter is of type (optionally cv-qualified) X and
2532 // either there are no other parameters or else all other
2533 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002534 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002535 ((Constructor->getNumParams() == 1) ||
2536 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002537 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2538 Constructor->getTemplateSpecializationKind()
2539 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002540 QualType ParamType = Constructor->getParamDecl(0)->getType();
2541 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2542 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002543 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2544 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002545 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002546
2547 // FIXME: Rather that making the constructor invalid, we should endeavor
2548 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002549 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002550 }
2551 }
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregor72b505b2008-12-16 21:30:33 +00002553 // Notify the class that we've added a constructor.
2554 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002555}
2556
Anders Carlsson37909802009-11-30 21:24:50 +00002557/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2558/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002559bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002560 CXXRecordDecl *RD = Destructor->getParent();
2561
2562 if (Destructor->isVirtual()) {
2563 SourceLocation Loc;
2564
2565 if (!Destructor->isImplicit())
2566 Loc = Destructor->getLocation();
2567 else
2568 Loc = RD->getLocation();
2569
2570 // If we have a virtual destructor, look up the deallocation function
2571 FunctionDecl *OperatorDelete = 0;
2572 DeclarationName Name =
2573 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002574 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002575 return true;
2576
2577 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002578 }
Anders Carlsson37909802009-11-30 21:24:50 +00002579
2580 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002581}
2582
Mike Stump1eb44332009-09-09 15:08:12 +00002583static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002584FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2585 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2586 FTI.ArgInfo[0].Param &&
2587 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2588}
2589
Douglas Gregor42a552f2008-11-05 20:51:48 +00002590/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2591/// the well-formednes of the destructor declarator @p D with type @p
2592/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002593/// emit diagnostics and set the declarator to invalid. Even if this happens,
2594/// will be updated to reflect a well-formed type for the destructor and
2595/// returned.
2596QualType Sema::CheckDestructorDeclarator(Declarator &D,
2597 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002598 // C++ [class.dtor]p1:
2599 // [...] A typedef-name that names a class is a class-name
2600 // (7.1.3); however, a typedef-name that names a class shall not
2601 // be used as the identifier in the declarator for a destructor
2602 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002603 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002604 if (isa<TypedefType>(DeclaratorType)) {
2605 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002606 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002607 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002608 }
2609
2610 // C++ [class.dtor]p2:
2611 // A destructor is used to destroy objects of its class type. A
2612 // destructor takes no parameters, and no return type can be
2613 // specified for it (not even void). The address of a destructor
2614 // shall not be taken. A destructor shall not be static. A
2615 // destructor can be invoked for a const, volatile or const
2616 // volatile object. A destructor shall not be declared const,
2617 // volatile or const volatile (9.3.2).
2618 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002619 if (!D.isInvalidType())
2620 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2621 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2622 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002623 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002624 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002625 }
Chris Lattner65401802009-04-25 08:28:21 +00002626 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002627 // Destructors don't have return types, but the parser will
2628 // happily parse something like:
2629 //
2630 // class X {
2631 // float ~X();
2632 // };
2633 //
2634 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002635 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2636 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2637 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002638 }
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Chris Lattner65401802009-04-25 08:28:21 +00002640 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2641 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002642 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002643 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2644 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002645 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002646 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2647 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002648 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002649 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2650 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002651 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002652 }
2653
2654 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002655 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002656 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2657
2658 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002659 FTI.freeArgs();
2660 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002661 }
2662
Mike Stump1eb44332009-09-09 15:08:12 +00002663 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002664 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002665 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002666 D.setInvalidType();
2667 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002668
2669 // Rebuild the function type "R" without any type qualifiers or
2670 // parameters (in case any of the errors above fired) and with
2671 // "void" as the return type, since destructors don't have return
2672 // types. We *always* have to do this, because GetTypeForDeclarator
2673 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002674 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002675}
2676
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002677/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2678/// well-formednes of the conversion function declarator @p D with
2679/// type @p R. If there are any errors in the declarator, this routine
2680/// will emit diagnostics and return true. Otherwise, it will return
2681/// false. Either way, the type @p R will be updated to reflect a
2682/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002683void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002684 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002685 // C++ [class.conv.fct]p1:
2686 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002687 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002688 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002689 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002690 if (!D.isInvalidType())
2691 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2692 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2693 << SourceRange(D.getIdentifierLoc());
2694 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002695 SC = FunctionDecl::None;
2696 }
Chris Lattner6e475012009-04-25 08:35:12 +00002697 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002698 // Conversion functions don't have return types, but the parser will
2699 // happily parse something like:
2700 //
2701 // class X {
2702 // float operator bool();
2703 // };
2704 //
2705 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002706 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2707 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2708 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002709 }
2710
2711 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002712 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002713 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2714
2715 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002716 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002717 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002718 }
2719
Mike Stump1eb44332009-09-09 15:08:12 +00002720 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002721 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002722 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002723 D.setInvalidType();
2724 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002725
2726 // C++ [class.conv.fct]p4:
2727 // The conversion-type-id shall not represent a function type nor
2728 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002729 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002730 if (ConvType->isArrayType()) {
2731 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2732 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002733 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002734 } else if (ConvType->isFunctionType()) {
2735 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2736 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002737 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002738 }
2739
2740 // Rebuild the function type "R" without any parameters (in case any
2741 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002742 // return type.
2743 R = Context.getFunctionType(ConvType, 0, 0, false,
John McCall183700f2009-09-21 23:43:11 +00002744 R->getAs<FunctionProtoType>()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002745
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002746 // C++0x explicit conversion operators.
2747 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002748 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002749 diag::warn_explicit_conversion_functions)
2750 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002751}
2752
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002753/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2754/// the declaration of the given C++ conversion function. This routine
2755/// is responsible for recording the conversion function in the C++
2756/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002757Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002758 assert(Conversion && "Expected to receive a conversion function declaration");
2759
Douglas Gregor9d350972008-12-12 08:25:50 +00002760 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002761
2762 // Make sure we aren't redeclaring the conversion function.
2763 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002764
2765 // C++ [class.conv.fct]p1:
2766 // [...] A conversion function is never used to convert a
2767 // (possibly cv-qualified) object to the (possibly cv-qualified)
2768 // same object type (or a reference to it), to a (possibly
2769 // cv-qualified) base class of that type (or a reference to it),
2770 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002771 // FIXME: Suppress this warning if the conversion function ends up being a
2772 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002773 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002774 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002775 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002776 ConvType = ConvTypeRef->getPointeeType();
2777 if (ConvType->isRecordType()) {
2778 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2779 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002780 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002781 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002782 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002783 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002784 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002785 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002786 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002787 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002788 }
2789
Douglas Gregor48026d22010-01-11 18:40:55 +00002790 if (Conversion->getPrimaryTemplate()) {
2791 // ignore specializations
2792 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002793 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002794 = Conversion->getDescribedFunctionTemplate()) {
2795 if (ClassDecl->replaceConversion(
2796 ConversionTemplate->getPreviousDeclaration(),
2797 ConversionTemplate))
2798 return DeclPtrTy::make(ConversionTemplate);
2799 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2800 Conversion))
John McCallba135432009-11-21 08:51:07 +00002801 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002802 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002803 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002804 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002805 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002806 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002807 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002808
Chris Lattnerb28317a2009-03-28 19:18:32 +00002809 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002810}
2811
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002812//===----------------------------------------------------------------------===//
2813// Namespace Handling
2814//===----------------------------------------------------------------------===//
2815
2816/// ActOnStartNamespaceDef - This is called at the start of a namespace
2817/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002818Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2819 SourceLocation IdentLoc,
2820 IdentifierInfo *II,
2821 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002822 NamespaceDecl *Namespc =
2823 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2824 Namespc->setLBracLoc(LBrace);
2825
2826 Scope *DeclRegionScope = NamespcScope->getParent();
2827
2828 if (II) {
2829 // C++ [namespace.def]p2:
2830 // The identifier in an original-namespace-definition shall not have been
2831 // previously defined in the declarative region in which the
2832 // original-namespace-definition appears. The identifier in an
2833 // original-namespace-definition is the name of the namespace. Subsequently
2834 // in that declarative region, it is treated as an original-namespace-name.
2835
John McCallf36e02d2009-10-09 21:13:30 +00002836 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002837 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002838 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Douglas Gregor44b43212008-12-11 16:49:14 +00002840 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2841 // This is an extended namespace definition.
2842 // Attach this namespace decl to the chain of extended namespace
2843 // definitions.
2844 OrigNS->setNextNamespace(Namespc);
2845 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002846
Mike Stump1eb44332009-09-09 15:08:12 +00002847 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002848 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002849 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002850 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002851 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002852 } else if (PrevDecl) {
2853 // This is an invalid name redefinition.
2854 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2855 << Namespc->getDeclName();
2856 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2857 Namespc->setInvalidDecl();
2858 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002859 } else if (II->isStr("std") &&
2860 CurContext->getLookupContext()->isTranslationUnit()) {
2861 // This is the first "real" definition of the namespace "std", so update
2862 // our cache of the "std" namespace to point at this definition.
2863 if (StdNamespace) {
2864 // We had already defined a dummy namespace "std". Link this new
2865 // namespace definition to the dummy namespace "std".
2866 StdNamespace->setNextNamespace(Namespc);
2867 StdNamespace->setLocation(IdentLoc);
2868 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2869 }
2870
2871 // Make our StdNamespace cache point at the first real definition of the
2872 // "std" namespace.
2873 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002874 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002875
2876 PushOnScopeChains(Namespc, DeclRegionScope);
2877 } else {
John McCall9aeed322009-10-01 00:25:31 +00002878 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002879 assert(Namespc->isAnonymousNamespace());
2880 CurContext->addDecl(Namespc);
2881
2882 // Link the anonymous namespace into its parent.
2883 NamespaceDecl *PrevDecl;
2884 DeclContext *Parent = CurContext->getLookupContext();
2885 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2886 PrevDecl = TU->getAnonymousNamespace();
2887 TU->setAnonymousNamespace(Namespc);
2888 } else {
2889 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2890 PrevDecl = ND->getAnonymousNamespace();
2891 ND->setAnonymousNamespace(Namespc);
2892 }
2893
2894 // Link the anonymous namespace with its previous declaration.
2895 if (PrevDecl) {
2896 assert(PrevDecl->isAnonymousNamespace());
2897 assert(!PrevDecl->getNextNamespace());
2898 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2899 PrevDecl->setNextNamespace(Namespc);
2900 }
John McCall9aeed322009-10-01 00:25:31 +00002901
2902 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2903 // behaves as if it were replaced by
2904 // namespace unique { /* empty body */ }
2905 // using namespace unique;
2906 // namespace unique { namespace-body }
2907 // where all occurrences of 'unique' in a translation unit are
2908 // replaced by the same identifier and this identifier differs
2909 // from all other identifiers in the entire program.
2910
2911 // We just create the namespace with an empty name and then add an
2912 // implicit using declaration, just like the standard suggests.
2913 //
2914 // CodeGen enforces the "universally unique" aspect by giving all
2915 // declarations semantically contained within an anonymous
2916 // namespace internal linkage.
2917
John McCall5fdd7642009-12-16 02:06:49 +00002918 if (!PrevDecl) {
2919 UsingDirectiveDecl* UD
2920 = UsingDirectiveDecl::Create(Context, CurContext,
2921 /* 'using' */ LBrace,
2922 /* 'namespace' */ SourceLocation(),
2923 /* qualifier */ SourceRange(),
2924 /* NNS */ NULL,
2925 /* identifier */ SourceLocation(),
2926 Namespc,
2927 /* Ancestor */ CurContext);
2928 UD->setImplicit();
2929 CurContext->addDecl(UD);
2930 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002931 }
2932
2933 // Although we could have an invalid decl (i.e. the namespace name is a
2934 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002935 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2936 // for the namespace has the declarations that showed up in that particular
2937 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002938 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002939 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002940}
2941
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002942/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2943/// is a namespace alias, returns the namespace it points to.
2944static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2945 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2946 return AD->getNamespace();
2947 return dyn_cast_or_null<NamespaceDecl>(D);
2948}
2949
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002950/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2951/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002952void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2953 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002954 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2955 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2956 Namespc->setRBracLoc(RBrace);
2957 PopDeclContext();
2958}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002959
Chris Lattnerb28317a2009-03-28 19:18:32 +00002960Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2961 SourceLocation UsingLoc,
2962 SourceLocation NamespcLoc,
2963 const CXXScopeSpec &SS,
2964 SourceLocation IdentLoc,
2965 IdentifierInfo *NamespcName,
2966 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002967 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2968 assert(NamespcName && "Invalid NamespcName.");
2969 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002970 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002971
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002972 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002973
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002974 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00002975 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2976 LookupParsedName(R, S, &SS);
2977 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00002978 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00002979
John McCallf36e02d2009-10-09 21:13:30 +00002980 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002981 NamedDecl *Named = R.getFoundDecl();
2982 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2983 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002984 // C++ [namespace.udir]p1:
2985 // A using-directive specifies that the names in the nominated
2986 // namespace can be used in the scope in which the
2987 // using-directive appears after the using-directive. During
2988 // unqualified name lookup (3.4.1), the names appear as if they
2989 // were declared in the nearest enclosing namespace which
2990 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002991 // namespace. [Note: in this context, "contains" means "contains
2992 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002993
2994 // Find enclosing context containing both using-directive and
2995 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002996 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002997 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2998 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2999 CommonAncestor = CommonAncestor->getParent();
3000
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003001 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003002 SS.getRange(),
3003 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003004 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003005 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003006 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003007 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003008 }
3009
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003010 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003011 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003012 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003013}
3014
3015void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3016 // If scope has associated entity, then using directive is at namespace
3017 // or translation unit scope. We add UsingDirectiveDecls, into
3018 // it's lookup structure.
3019 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003020 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003021 else
3022 // Otherwise it is block-sope. using-directives will affect lookup
3023 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003024 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003025}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003026
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003027
3028Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003029 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003030 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003031 SourceLocation UsingLoc,
3032 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003033 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003034 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003035 bool IsTypeName,
3036 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003037 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Douglas Gregor12c118a2009-11-04 16:30:06 +00003039 switch (Name.getKind()) {
3040 case UnqualifiedId::IK_Identifier:
3041 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003042 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003043 case UnqualifiedId::IK_ConversionFunctionId:
3044 break;
3045
3046 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003047 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003048 // C++0x inherited constructors.
3049 if (getLangOptions().CPlusPlus0x) break;
3050
Douglas Gregor12c118a2009-11-04 16:30:06 +00003051 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3052 << SS.getRange();
3053 return DeclPtrTy();
3054
3055 case UnqualifiedId::IK_DestructorName:
3056 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3057 << SS.getRange();
3058 return DeclPtrTy();
3059
3060 case UnqualifiedId::IK_TemplateId:
3061 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3062 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3063 return DeclPtrTy();
3064 }
3065
3066 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003067 if (!TargetName)
3068 return DeclPtrTy();
3069
John McCall60fa3cf2009-12-11 02:10:03 +00003070 // Warn about using declarations.
3071 // TODO: store that the declaration was written without 'using' and
3072 // talk about access decls instead of using decls in the
3073 // diagnostics.
3074 if (!HasUsingKeyword) {
3075 UsingLoc = Name.getSourceRange().getBegin();
3076
3077 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3078 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3079 "using ");
3080 }
3081
John McCall9488ea12009-11-17 05:59:44 +00003082 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003083 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003084 TargetName, AttrList,
3085 /* IsInstantiation */ false,
3086 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003087 if (UD)
3088 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Anders Carlssonc72160b2009-08-28 05:40:36 +00003090 return DeclPtrTy::make(UD);
3091}
3092
John McCall9f54ad42009-12-10 09:41:52 +00003093/// Determines whether to create a using shadow decl for a particular
3094/// decl, given the set of decls existing prior to this using lookup.
3095bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3096 const LookupResult &Previous) {
3097 // Diagnose finding a decl which is not from a base class of the
3098 // current class. We do this now because there are cases where this
3099 // function will silently decide not to build a shadow decl, which
3100 // will pre-empt further diagnostics.
3101 //
3102 // We don't need to do this in C++0x because we do the check once on
3103 // the qualifier.
3104 //
3105 // FIXME: diagnose the following if we care enough:
3106 // struct A { int foo; };
3107 // struct B : A { using A::foo; };
3108 // template <class T> struct C : A {};
3109 // template <class T> struct D : C<T> { using B::foo; } // <---
3110 // This is invalid (during instantiation) in C++03 because B::foo
3111 // resolves to the using decl in B, which is not a base class of D<T>.
3112 // We can't diagnose it immediately because C<T> is an unknown
3113 // specialization. The UsingShadowDecl in D<T> then points directly
3114 // to A::foo, which will look well-formed when we instantiate.
3115 // The right solution is to not collapse the shadow-decl chain.
3116 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3117 DeclContext *OrigDC = Orig->getDeclContext();
3118
3119 // Handle enums and anonymous structs.
3120 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3121 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3122 while (OrigRec->isAnonymousStructOrUnion())
3123 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3124
3125 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3126 if (OrigDC == CurContext) {
3127 Diag(Using->getLocation(),
3128 diag::err_using_decl_nested_name_specifier_is_current_class)
3129 << Using->getNestedNameRange();
3130 Diag(Orig->getLocation(), diag::note_using_decl_target);
3131 return true;
3132 }
3133
3134 Diag(Using->getNestedNameRange().getBegin(),
3135 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3136 << Using->getTargetNestedNameDecl()
3137 << cast<CXXRecordDecl>(CurContext)
3138 << Using->getNestedNameRange();
3139 Diag(Orig->getLocation(), diag::note_using_decl_target);
3140 return true;
3141 }
3142 }
3143
3144 if (Previous.empty()) return false;
3145
3146 NamedDecl *Target = Orig;
3147 if (isa<UsingShadowDecl>(Target))
3148 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3149
John McCalld7533ec2009-12-11 02:33:26 +00003150 // If the target happens to be one of the previous declarations, we
3151 // don't have a conflict.
3152 //
3153 // FIXME: but we might be increasing its access, in which case we
3154 // should redeclare it.
3155 NamedDecl *NonTag = 0, *Tag = 0;
3156 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3157 I != E; ++I) {
3158 NamedDecl *D = (*I)->getUnderlyingDecl();
3159 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3160 return false;
3161
3162 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3163 }
3164
John McCall9f54ad42009-12-10 09:41:52 +00003165 if (Target->isFunctionOrFunctionTemplate()) {
3166 FunctionDecl *FD;
3167 if (isa<FunctionTemplateDecl>(Target))
3168 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3169 else
3170 FD = cast<FunctionDecl>(Target);
3171
3172 NamedDecl *OldDecl = 0;
3173 switch (CheckOverload(FD, Previous, OldDecl)) {
3174 case Ovl_Overload:
3175 return false;
3176
3177 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003178 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003179 break;
3180
3181 // We found a decl with the exact signature.
3182 case Ovl_Match:
3183 if (isa<UsingShadowDecl>(OldDecl)) {
3184 // Silently ignore the possible conflict.
3185 return false;
3186 }
3187
3188 // If we're in a record, we want to hide the target, so we
3189 // return true (without a diagnostic) to tell the caller not to
3190 // build a shadow decl.
3191 if (CurContext->isRecord())
3192 return true;
3193
3194 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003195 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003196 break;
3197 }
3198
3199 Diag(Target->getLocation(), diag::note_using_decl_target);
3200 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3201 return true;
3202 }
3203
3204 // Target is not a function.
3205
John McCall9f54ad42009-12-10 09:41:52 +00003206 if (isa<TagDecl>(Target)) {
3207 // No conflict between a tag and a non-tag.
3208 if (!Tag) return false;
3209
John McCall41ce66f2009-12-10 19:51:03 +00003210 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003211 Diag(Target->getLocation(), diag::note_using_decl_target);
3212 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3213 return true;
3214 }
3215
3216 // No conflict between a tag and a non-tag.
3217 if (!NonTag) return false;
3218
John McCall41ce66f2009-12-10 19:51:03 +00003219 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003220 Diag(Target->getLocation(), diag::note_using_decl_target);
3221 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3222 return true;
3223}
3224
John McCall9488ea12009-11-17 05:59:44 +00003225/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003226UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003227 UsingDecl *UD,
3228 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003229
3230 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003231 NamedDecl *Target = Orig;
3232 if (isa<UsingShadowDecl>(Target)) {
3233 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3234 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003235 }
3236
3237 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003238 = UsingShadowDecl::Create(Context, CurContext,
3239 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003240 UD->addShadowDecl(Shadow);
3241
3242 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003243 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003244 else
John McCall604e7f12009-12-08 07:46:18 +00003245 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003246 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003247
John McCall604e7f12009-12-08 07:46:18 +00003248 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3249 Shadow->setInvalidDecl();
3250
John McCall9f54ad42009-12-10 09:41:52 +00003251 return Shadow;
3252}
John McCall604e7f12009-12-08 07:46:18 +00003253
John McCall9f54ad42009-12-10 09:41:52 +00003254/// Hides a using shadow declaration. This is required by the current
3255/// using-decl implementation when a resolvable using declaration in a
3256/// class is followed by a declaration which would hide or override
3257/// one or more of the using decl's targets; for example:
3258///
3259/// struct Base { void foo(int); };
3260/// struct Derived : Base {
3261/// using Base::foo;
3262/// void foo(int);
3263/// };
3264///
3265/// The governing language is C++03 [namespace.udecl]p12:
3266///
3267/// When a using-declaration brings names from a base class into a
3268/// derived class scope, member functions in the derived class
3269/// override and/or hide member functions with the same name and
3270/// parameter types in a base class (rather than conflicting).
3271///
3272/// There are two ways to implement this:
3273/// (1) optimistically create shadow decls when they're not hidden
3274/// by existing declarations, or
3275/// (2) don't create any shadow decls (or at least don't make them
3276/// visible) until we've fully parsed/instantiated the class.
3277/// The problem with (1) is that we might have to retroactively remove
3278/// a shadow decl, which requires several O(n) operations because the
3279/// decl structures are (very reasonably) not designed for removal.
3280/// (2) avoids this but is very fiddly and phase-dependent.
3281void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3282 // Remove it from the DeclContext...
3283 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003284
John McCall9f54ad42009-12-10 09:41:52 +00003285 // ...and the scope, if applicable...
3286 if (S) {
3287 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3288 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003289 }
3290
John McCall9f54ad42009-12-10 09:41:52 +00003291 // ...and the using decl.
3292 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3293
3294 // TODO: complain somehow if Shadow was used. It shouldn't
3295 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003296}
3297
John McCall7ba107a2009-11-18 02:36:19 +00003298/// Builds a using declaration.
3299///
3300/// \param IsInstantiation - Whether this call arises from an
3301/// instantiation of an unresolved using declaration. We treat
3302/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003303NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3304 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003305 const CXXScopeSpec &SS,
3306 SourceLocation IdentLoc,
3307 DeclarationName Name,
3308 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003309 bool IsInstantiation,
3310 bool IsTypeName,
3311 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003312 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3313 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003314
Anders Carlsson550b14b2009-08-28 05:49:21 +00003315 // FIXME: We ignore attributes for now.
3316 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003318 if (SS.isEmpty()) {
3319 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003320 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003321 }
Mike Stump1eb44332009-09-09 15:08:12 +00003322
John McCall9f54ad42009-12-10 09:41:52 +00003323 // Do the redeclaration lookup in the current scope.
3324 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3325 ForRedeclaration);
3326 Previous.setHideTags(false);
3327 if (S) {
3328 LookupName(Previous, S);
3329
3330 // It is really dumb that we have to do this.
3331 LookupResult::Filter F = Previous.makeFilter();
3332 while (F.hasNext()) {
3333 NamedDecl *D = F.next();
3334 if (!isDeclInScope(D, CurContext, S))
3335 F.erase();
3336 }
3337 F.done();
3338 } else {
3339 assert(IsInstantiation && "no scope in non-instantiation");
3340 assert(CurContext->isRecord() && "scope not record in instantiation");
3341 LookupQualifiedName(Previous, CurContext);
3342 }
3343
Mike Stump1eb44332009-09-09 15:08:12 +00003344 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003345 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3346
John McCall9f54ad42009-12-10 09:41:52 +00003347 // Check for invalid redeclarations.
3348 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3349 return 0;
3350
3351 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003352 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3353 return 0;
3354
John McCallaf8e6ed2009-11-12 03:15:40 +00003355 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003356 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003357 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003358 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003359 // FIXME: not all declaration name kinds are legal here
3360 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3361 UsingLoc, TypenameLoc,
3362 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003363 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003364 } else {
3365 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3366 UsingLoc, SS.getRange(), NNS,
3367 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003368 }
John McCalled976492009-12-04 22:46:56 +00003369 } else {
3370 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3371 SS.getRange(), UsingLoc, NNS, Name,
3372 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003373 }
John McCalled976492009-12-04 22:46:56 +00003374 D->setAccess(AS);
3375 CurContext->addDecl(D);
3376
3377 if (!LookupContext) return D;
3378 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003379
John McCall604e7f12009-12-08 07:46:18 +00003380 if (RequireCompleteDeclContext(SS)) {
3381 UD->setInvalidDecl();
3382 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003383 }
3384
John McCall604e7f12009-12-08 07:46:18 +00003385 // Look up the target name.
3386
John McCalla24dc2e2009-11-17 02:14:36 +00003387 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003388
John McCall604e7f12009-12-08 07:46:18 +00003389 // Unlike most lookups, we don't always want to hide tag
3390 // declarations: tag names are visible through the using declaration
3391 // even if hidden by ordinary names, *except* in a dependent context
3392 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003393 if (!IsInstantiation)
3394 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003395
John McCalla24dc2e2009-11-17 02:14:36 +00003396 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003397
John McCallf36e02d2009-10-09 21:13:30 +00003398 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003399 Diag(IdentLoc, diag::err_no_member)
3400 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003401 UD->setInvalidDecl();
3402 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003403 }
3404
John McCalled976492009-12-04 22:46:56 +00003405 if (R.isAmbiguous()) {
3406 UD->setInvalidDecl();
3407 return UD;
3408 }
Mike Stump1eb44332009-09-09 15:08:12 +00003409
John McCall7ba107a2009-11-18 02:36:19 +00003410 if (IsTypeName) {
3411 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003412 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003413 Diag(IdentLoc, diag::err_using_typename_non_type);
3414 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3415 Diag((*I)->getUnderlyingDecl()->getLocation(),
3416 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003417 UD->setInvalidDecl();
3418 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003419 }
3420 } else {
3421 // If we asked for a non-typename and we got a type, error out,
3422 // but only if this is an instantiation of an unresolved using
3423 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003424 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003425 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3426 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003427 UD->setInvalidDecl();
3428 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003429 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003430 }
3431
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003432 // C++0x N2914 [namespace.udecl]p6:
3433 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003434 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003435 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3436 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003437 UD->setInvalidDecl();
3438 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003439 }
Mike Stump1eb44332009-09-09 15:08:12 +00003440
John McCall9f54ad42009-12-10 09:41:52 +00003441 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3442 if (!CheckUsingShadowDecl(UD, *I, Previous))
3443 BuildUsingShadowDecl(S, UD, *I);
3444 }
John McCall9488ea12009-11-17 05:59:44 +00003445
3446 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003447}
3448
John McCall9f54ad42009-12-10 09:41:52 +00003449/// Checks that the given using declaration is not an invalid
3450/// redeclaration. Note that this is checking only for the using decl
3451/// itself, not for any ill-formedness among the UsingShadowDecls.
3452bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3453 bool isTypeName,
3454 const CXXScopeSpec &SS,
3455 SourceLocation NameLoc,
3456 const LookupResult &Prev) {
3457 // C++03 [namespace.udecl]p8:
3458 // C++0x [namespace.udecl]p10:
3459 // A using-declaration is a declaration and can therefore be used
3460 // repeatedly where (and only where) multiple declarations are
3461 // allowed.
3462 // That's only in file contexts.
3463 if (CurContext->getLookupContext()->isFileContext())
3464 return false;
3465
3466 NestedNameSpecifier *Qual
3467 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3468
3469 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3470 NamedDecl *D = *I;
3471
3472 bool DTypename;
3473 NestedNameSpecifier *DQual;
3474 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3475 DTypename = UD->isTypeName();
3476 DQual = UD->getTargetNestedNameDecl();
3477 } else if (UnresolvedUsingValueDecl *UD
3478 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3479 DTypename = false;
3480 DQual = UD->getTargetNestedNameSpecifier();
3481 } else if (UnresolvedUsingTypenameDecl *UD
3482 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3483 DTypename = true;
3484 DQual = UD->getTargetNestedNameSpecifier();
3485 } else continue;
3486
3487 // using decls differ if one says 'typename' and the other doesn't.
3488 // FIXME: non-dependent using decls?
3489 if (isTypeName != DTypename) continue;
3490
3491 // using decls differ if they name different scopes (but note that
3492 // template instantiation can cause this check to trigger when it
3493 // didn't before instantiation).
3494 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3495 Context.getCanonicalNestedNameSpecifier(DQual))
3496 continue;
3497
3498 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003499 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003500 return true;
3501 }
3502
3503 return false;
3504}
3505
John McCall604e7f12009-12-08 07:46:18 +00003506
John McCalled976492009-12-04 22:46:56 +00003507/// Checks that the given nested-name qualifier used in a using decl
3508/// in the current context is appropriately related to the current
3509/// scope. If an error is found, diagnoses it and returns true.
3510bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3511 const CXXScopeSpec &SS,
3512 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003513 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003514
John McCall604e7f12009-12-08 07:46:18 +00003515 if (!CurContext->isRecord()) {
3516 // C++03 [namespace.udecl]p3:
3517 // C++0x [namespace.udecl]p8:
3518 // A using-declaration for a class member shall be a member-declaration.
3519
3520 // If we weren't able to compute a valid scope, it must be a
3521 // dependent class scope.
3522 if (!NamedContext || NamedContext->isRecord()) {
3523 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3524 << SS.getRange();
3525 return true;
3526 }
3527
3528 // Otherwise, everything is known to be fine.
3529 return false;
3530 }
3531
3532 // The current scope is a record.
3533
3534 // If the named context is dependent, we can't decide much.
3535 if (!NamedContext) {
3536 // FIXME: in C++0x, we can diagnose if we can prove that the
3537 // nested-name-specifier does not refer to a base class, which is
3538 // still possible in some cases.
3539
3540 // Otherwise we have to conservatively report that things might be
3541 // okay.
3542 return false;
3543 }
3544
3545 if (!NamedContext->isRecord()) {
3546 // Ideally this would point at the last name in the specifier,
3547 // but we don't have that level of source info.
3548 Diag(SS.getRange().getBegin(),
3549 diag::err_using_decl_nested_name_specifier_is_not_class)
3550 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3551 return true;
3552 }
3553
3554 if (getLangOptions().CPlusPlus0x) {
3555 // C++0x [namespace.udecl]p3:
3556 // In a using-declaration used as a member-declaration, the
3557 // nested-name-specifier shall name a base class of the class
3558 // being defined.
3559
3560 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3561 cast<CXXRecordDecl>(NamedContext))) {
3562 if (CurContext == NamedContext) {
3563 Diag(NameLoc,
3564 diag::err_using_decl_nested_name_specifier_is_current_class)
3565 << SS.getRange();
3566 return true;
3567 }
3568
3569 Diag(SS.getRange().getBegin(),
3570 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3571 << (NestedNameSpecifier*) SS.getScopeRep()
3572 << cast<CXXRecordDecl>(CurContext)
3573 << SS.getRange();
3574 return true;
3575 }
3576
3577 return false;
3578 }
3579
3580 // C++03 [namespace.udecl]p4:
3581 // A using-declaration used as a member-declaration shall refer
3582 // to a member of a base class of the class being defined [etc.].
3583
3584 // Salient point: SS doesn't have to name a base class as long as
3585 // lookup only finds members from base classes. Therefore we can
3586 // diagnose here only if we can prove that that can't happen,
3587 // i.e. if the class hierarchies provably don't intersect.
3588
3589 // TODO: it would be nice if "definitely valid" results were cached
3590 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3591 // need to be repeated.
3592
3593 struct UserData {
3594 llvm::DenseSet<const CXXRecordDecl*> Bases;
3595
3596 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3597 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3598 Data->Bases.insert(Base);
3599 return true;
3600 }
3601
3602 bool hasDependentBases(const CXXRecordDecl *Class) {
3603 return !Class->forallBases(collect, this);
3604 }
3605
3606 /// Returns true if the base is dependent or is one of the
3607 /// accumulated base classes.
3608 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3609 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3610 return !Data->Bases.count(Base);
3611 }
3612
3613 bool mightShareBases(const CXXRecordDecl *Class) {
3614 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3615 }
3616 };
3617
3618 UserData Data;
3619
3620 // Returns false if we find a dependent base.
3621 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3622 return false;
3623
3624 // Returns false if the class has a dependent base or if it or one
3625 // of its bases is present in the base set of the current context.
3626 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3627 return false;
3628
3629 Diag(SS.getRange().getBegin(),
3630 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3631 << (NestedNameSpecifier*) SS.getScopeRep()
3632 << cast<CXXRecordDecl>(CurContext)
3633 << SS.getRange();
3634
3635 return true;
John McCalled976492009-12-04 22:46:56 +00003636}
3637
Mike Stump1eb44332009-09-09 15:08:12 +00003638Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003639 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003640 SourceLocation AliasLoc,
3641 IdentifierInfo *Alias,
3642 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003643 SourceLocation IdentLoc,
3644 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Anders Carlsson81c85c42009-03-28 23:53:49 +00003646 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003647 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3648 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003649
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003650 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003651 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003652 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003653 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003654 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003655 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003656 if (!R.isAmbiguous() && !R.empty() &&
3657 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003658 return DeclPtrTy();
3659 }
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003661 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3662 diag::err_redefinition_different_kind;
3663 Diag(AliasLoc, DiagID) << Alias;
3664 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003665 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003666 }
3667
John McCalla24dc2e2009-11-17 02:14:36 +00003668 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003669 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003670
John McCallf36e02d2009-10-09 21:13:30 +00003671 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003672 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003673 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003674 }
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003676 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003677 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3678 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003679 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003680 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003682 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00003683 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003684}
3685
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003686void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3687 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003688 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3689 !Constructor->isUsed()) &&
3690 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Eli Friedman80c30da2009-11-09 19:20:36 +00003692 CXXRecordDecl *ClassDecl
3693 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3694 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003695
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003696 DeclContext *PreviousContext = CurContext;
3697 CurContext = Constructor;
3698 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003699 Diag(CurrentLocation, diag::note_member_synthesized_at)
3700 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003701 Constructor->setInvalidDecl();
3702 } else {
3703 Constructor->setUsed();
3704 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003705 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003706}
3707
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003708void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003709 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003710 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3711 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003712 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003713 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003714
3715 DeclContext *PreviousContext = CurContext;
3716 CurContext = Destructor;
3717
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003718 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003719 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003720 // implicitly defined, all the implicitly-declared default destructors
3721 // for its base class and its non-static data members shall have been
3722 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003723 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3724 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003725 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003726 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003727 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003728 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003729 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3730 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3731 else
Mike Stump1eb44332009-09-09 15:08:12 +00003732 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003733 "DefineImplicitDestructor - missing dtor in a base class");
3734 }
3735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003737 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3738 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003739 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3740 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3741 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003742 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003743 CXXRecordDecl *FieldClassDecl
3744 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3745 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003746 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003747 const_cast<CXXDestructorDecl*>(
3748 FieldClassDecl->getDestructor(Context)))
3749 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3750 else
Mike Stump1eb44332009-09-09 15:08:12 +00003751 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003752 "DefineImplicitDestructor - missing dtor in class of a data member");
3753 }
3754 }
3755 }
Anders Carlsson37909802009-11-30 21:24:50 +00003756
3757 // FIXME: If CheckDestructor fails, we should emit a note about where the
3758 // implicit destructor was needed.
3759 if (CheckDestructor(Destructor)) {
3760 Diag(CurrentLocation, diag::note_member_synthesized_at)
3761 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3762
3763 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003764 CurContext = PreviousContext;
3765
Anders Carlsson37909802009-11-30 21:24:50 +00003766 return;
3767 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003768 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003769
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003770 Destructor->setUsed();
3771}
3772
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003773void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3774 CXXMethodDecl *MethodDecl) {
3775 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3776 MethodDecl->getOverloadedOperator() == OO_Equal &&
3777 !MethodDecl->isUsed()) &&
3778 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003779
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003780 CXXRecordDecl *ClassDecl
3781 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003782
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003783 DeclContext *PreviousContext = CurContext;
3784 CurContext = MethodDecl;
3785
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003786 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003787 // Before the implicitly-declared copy assignment operator for a class is
3788 // implicitly defined, all implicitly-declared copy assignment operators
3789 // for its direct base classes and its nonstatic data members shall have
3790 // been implicitly defined.
3791 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3793 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003794 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003795 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003796 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003797 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3798 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003799 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3800 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3802 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003803 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3804 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3805 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003806 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003807 CXXRecordDecl *FieldClassDecl
3808 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003809 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003810 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3811 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003812 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003813 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003814 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003815 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3816 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003817 Diag(CurrentLocation, diag::note_first_required_here);
3818 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003819 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003821 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3822 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003823 Diag(CurrentLocation, diag::note_first_required_here);
3824 err = true;
3825 }
3826 }
3827 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003828 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003829
3830 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003831}
3832
3833CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003834Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3835 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003836 CXXRecordDecl *ClassDecl) {
3837 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3838 QualType RHSType(LHSType);
3839 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003840 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003841 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003842 RHSType = Context.getCVRQualifiedType(RHSType,
3843 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003844 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003845 LHSType,
3846 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003847 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003848 RHSType,
3849 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003850 Expr *Args[2] = { &*LHS, &*RHS };
3851 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003852 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003853 CandidateSet);
3854 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003855 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003856 return cast<CXXMethodDecl>(Best->Function);
3857 assert(false &&
3858 "getAssignOperatorMethod - copy assignment operator method not found");
3859 return 0;
3860}
3861
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003862void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3863 CXXConstructorDecl *CopyConstructor,
3864 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003865 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003866 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003867 !CopyConstructor->isUsed()) &&
3868 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003870 CXXRecordDecl *ClassDecl
3871 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3872 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003873
3874 DeclContext *PreviousContext = CurContext;
3875 CurContext = CopyConstructor;
3876
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003877 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003878 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003879 // implicitly defined, all the implicitly-declared copy constructors
3880 // for its base class and its non-static data members shall have been
3881 // implicitly defined.
3882 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3883 Base != ClassDecl->bases_end(); ++Base) {
3884 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003885 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003886 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003887 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003888 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003889 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003890 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3891 FieldEnd = ClassDecl->field_end();
3892 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003893 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3894 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3895 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003897 CXXRecordDecl *FieldClassDecl
3898 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003899 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003900 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003901 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003902 }
3903 }
3904 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003905
3906 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003907}
3908
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003909Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003911 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003912 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003913 bool RequiresZeroInit,
3914 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003915 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Douglas Gregor39da0b82009-09-09 23:08:42 +00003917 // C++ [class.copy]p15:
3918 // Whenever a temporary class object is copied using a copy constructor, and
3919 // this object and the copy have the same cv-unqualified type, an
3920 // implementation is permitted to treat the original and the copy as two
3921 // different ways of referring to the same object and not perform a copy at
3922 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003924 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003925 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003926 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003927 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3928 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3929 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003930 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3931 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003932 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3933 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003934 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3935 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3936 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003937
3938 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3939 Elidable = !CE->getCallReturnType()->isReferenceType();
3940 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003941 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003942 else if (isa<CXXConstructExpr>(E))
3943 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003944 }
Mike Stump1eb44332009-09-09 15:08:12 +00003945
3946 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003947 Elidable, move(ExprArgs), RequiresZeroInit,
3948 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003949}
3950
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003951/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3952/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003953Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003954Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3955 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003956 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003957 bool RequiresZeroInit,
3958 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003959 unsigned NumExprs = ExprArgs.size();
3960 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Douglas Gregor7edfb692009-11-23 12:27:39 +00003962 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003963 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00003964 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003965 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003966}
3967
Anders Carlssone7624a72009-08-27 05:08:22 +00003968Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00003969Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
3970 QualType Ty,
3971 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00003972 MultiExprArg Args,
3973 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003974 unsigned NumExprs = Args.size();
3975 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003976
Douglas Gregor7edfb692009-11-23 12:27:39 +00003977 MarkDeclarationReferenced(TyBeginLoc, Constructor);
Douglas Gregor39da0b82009-09-09 23:08:42 +00003978 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
3979 TyBeginLoc, Exprs,
3980 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00003981}
3982
3983
Mike Stump1eb44332009-09-09 15:08:12 +00003984bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003985 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003986 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003987 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00003988 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003989 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00003990 if (TempResult.isInvalid())
3991 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003993 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003994 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00003995 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor78d15832009-05-26 18:54:04 +00003996 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Anders Carlssonfe2de492009-08-25 05:18:00 +00003998 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00003999}
4000
Mike Stump1eb44332009-09-09 15:08:12 +00004001void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004002 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00004003 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004004 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00004005 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004006 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00004007 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004008}
4009
Mike Stump1eb44332009-09-09 15:08:12 +00004010/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004011/// ActOnDeclarator, when a C++ direct initializer is present.
4012/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004013void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4014 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004015 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004016 SourceLocation *CommaLocs,
4017 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004018 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004019 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004020
4021 // If there is no declaration, there was an error parsing it. Just ignore
4022 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004023 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004026 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4027 if (!VDecl) {
4028 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4029 RealDecl->setInvalidDecl();
4030 return;
4031 }
4032
Douglas Gregor83ddad32009-08-26 21:14:46 +00004033 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004034 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004035 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4036 //
4037 // Clients that want to distinguish between the two forms, can check for
4038 // direct initializer using VarDecl::hasCXXDirectInitializer().
4039 // A major benefit is that clients that don't particularly care about which
4040 // exactly form was it (like the CodeGen) can handle both cases without
4041 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004042
Douglas Gregor83ddad32009-08-26 21:14:46 +00004043 // If either the declaration has a dependent type or if any of the expressions
4044 // is type-dependent, we represent the initialization via a ParenListExpr for
4045 // later use during template instantiation.
4046 if (VDecl->getType()->isDependentType() ||
4047 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4048 // Let clients know that initialization was done with a direct initializer.
4049 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Douglas Gregor83ddad32009-08-26 21:14:46 +00004051 // Store the initialization expressions as a ParenListExpr.
4052 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004053 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00004054 new (Context) ParenListExpr(Context, LParenLoc,
4055 (Expr **)Exprs.release(),
4056 NumExprs, RParenLoc));
4057 return;
4058 }
Mike Stump1eb44332009-09-09 15:08:12 +00004059
Douglas Gregor83ddad32009-08-26 21:14:46 +00004060
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004061 // C++ 8.5p11:
4062 // The form of initialization (using parentheses or '=') is generally
4063 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004064 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004065 QualType DeclInitType = VDecl->getType();
4066 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004067 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004068
Douglas Gregor615c5d42009-03-24 16:43:20 +00004069 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4070 diag::err_typecheck_decl_incomplete_type)) {
4071 VDecl->setInvalidDecl();
4072 return;
4073 }
4074
Douglas Gregor90f93822009-12-22 22:17:25 +00004075 // The variable can not have an abstract class type.
4076 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4077 diag::err_abstract_type_in_decl,
4078 AbstractVariableType))
4079 VDecl->setInvalidDecl();
4080
4081 const VarDecl *Def = 0;
4082 if (VDecl->getDefinition(Def)) {
4083 Diag(VDecl->getLocation(), diag::err_redefinition)
4084 << VDecl->getDeclName();
4085 Diag(Def->getLocation(), diag::note_previous_definition);
4086 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004087 return;
4088 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004089
4090 // Capture the variable that is being initialized and the style of
4091 // initialization.
4092 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4093
4094 // FIXME: Poor source location information.
4095 InitializationKind Kind
4096 = InitializationKind::CreateDirect(VDecl->getLocation(),
4097 LParenLoc, RParenLoc);
4098
4099 InitializationSequence InitSeq(*this, Entity, Kind,
4100 (Expr**)Exprs.get(), Exprs.size());
4101 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4102 if (Result.isInvalid()) {
4103 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004104 return;
4105 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004106
4107 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4108 VDecl->setInit(Context, Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004109 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004110
Douglas Gregor90f93822009-12-22 22:17:25 +00004111 if (VDecl->getType()->getAs<RecordType>())
4112 FinalizeVarWithDestructor(VDecl, DeclInitType);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004113}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004114
Douglas Gregor19aeac62009-11-14 03:27:21 +00004115/// \brief Add the applicable constructor candidates for an initialization
4116/// by constructor.
4117static void AddConstructorInitializationCandidates(Sema &SemaRef,
4118 QualType ClassType,
4119 Expr **Args,
4120 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004121 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004122 OverloadCandidateSet &CandidateSet) {
4123 // C++ [dcl.init]p14:
4124 // If the initialization is direct-initialization, or if it is
4125 // copy-initialization where the cv-unqualified version of the
4126 // source type is the same class as, or a derived class of, the
4127 // class of the destination, constructors are considered. The
4128 // applicable constructors are enumerated (13.3.1.3), and the
4129 // best one is chosen through overload resolution (13.3). The
4130 // constructor so selected is called to initialize the object,
4131 // with the initializer expression(s) as its argument(s). If no
4132 // constructor applies, or the overload resolution is ambiguous,
4133 // the initialization is ill-formed.
4134 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4135 assert(ClassRec && "Can only initialize a class type here");
4136
4137 // FIXME: When we decide not to synthesize the implicitly-declared
4138 // constructors, we'll need to make them appear here.
4139
4140 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4141 DeclarationName ConstructorName
4142 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4143 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4144 DeclContext::lookup_const_iterator Con, ConEnd;
4145 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4146 Con != ConEnd; ++Con) {
4147 // Find the constructor (which may be a template).
4148 CXXConstructorDecl *Constructor = 0;
4149 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4150 if (ConstructorTmpl)
4151 Constructor
4152 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4153 else
4154 Constructor = cast<CXXConstructorDecl>(*Con);
4155
Douglas Gregor20093b42009-12-09 23:02:17 +00004156 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4157 (Kind.getKind() == InitializationKind::IK_Value) ||
4158 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004159 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004160 ((Kind.getKind() == InitializationKind::IK_Default) &&
4161 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004162 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004163 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004164 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004165 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004166 Args, NumArgs, CandidateSet);
4167 else
John McCall86820f52010-01-26 01:37:31 +00004168 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4169 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004170 }
4171 }
4172}
4173
4174/// \brief Attempt to perform initialization by constructor
4175/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4176/// copy-initialization.
4177///
4178/// This routine determines whether initialization by constructor is possible,
4179/// but it does not emit any diagnostics in the case where the initialization
4180/// is ill-formed.
4181///
4182/// \param ClassType the type of the object being initialized, which must have
4183/// class type.
4184///
4185/// \param Args the arguments provided to initialize the object
4186///
4187/// \param NumArgs the number of arguments provided to initialize the object
4188///
4189/// \param Kind the type of initialization being performed
4190///
4191/// \returns the constructor used to initialize the object, if successful.
4192/// Otherwise, emits a diagnostic and returns NULL.
4193CXXConstructorDecl *
4194Sema::TryInitializationByConstructor(QualType ClassType,
4195 Expr **Args, unsigned NumArgs,
4196 SourceLocation Loc,
4197 InitializationKind Kind) {
4198 // Build the overload candidate set
4199 OverloadCandidateSet CandidateSet;
4200 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4201 CandidateSet);
4202
4203 // Determine whether we found a constructor we can use.
4204 OverloadCandidateSet::iterator Best;
4205 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4206 case OR_Success:
4207 case OR_Deleted:
4208 // We found a constructor. Return it.
4209 return cast<CXXConstructorDecl>(Best->Function);
4210
4211 case OR_No_Viable_Function:
4212 case OR_Ambiguous:
4213 // Overload resolution failed. Return nothing.
4214 return 0;
4215 }
4216
4217 // Silence GCC warning
4218 return 0;
4219}
4220
Douglas Gregor39da0b82009-09-09 23:08:42 +00004221/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
4222/// may occur as part of direct-initialization or copy-initialization.
4223///
4224/// \param ClassType the type of the object being initialized, which must have
4225/// class type.
4226///
4227/// \param ArgsPtr the arguments provided to initialize the object
4228///
4229/// \param Loc the source location where the initialization occurs
4230///
4231/// \param Range the source range that covers the entire initialization
4232///
4233/// \param InitEntity the name of the entity being initialized, if known
4234///
4235/// \param Kind the type of initialization being performed
4236///
4237/// \param ConvertedArgs a vector that will be filled in with the
4238/// appropriately-converted arguments to the constructor (if initialization
4239/// succeeded).
4240///
4241/// \returns the constructor used to initialize the object, if successful.
4242/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004243CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004244Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004245 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00004246 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004247 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00004248 InitializationKind Kind,
4249 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004250
4251 // Build the overload candidate set
Douglas Gregor39da0b82009-09-09 23:08:42 +00004252 Expr **Args = (Expr **)ArgsPtr.get();
4253 unsigned NumArgs = ArgsPtr.size();
Douglas Gregor18fe5682008-11-03 20:45:27 +00004254 OverloadCandidateSet CandidateSet;
Douglas Gregor19aeac62009-11-14 03:27:21 +00004255 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4256 CandidateSet);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00004257
Douglas Gregor18fe5682008-11-03 20:45:27 +00004258 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004259 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00004260 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00004261 // We found a constructor. Break out so that we can convert the arguments
4262 // appropriately.
4263 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Douglas Gregor18fe5682008-11-03 20:45:27 +00004265 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004266 if (InitEntity)
4267 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004268 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00004269 else
4270 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00004271 << ClassType << Range;
John McCallcbce6062010-01-12 07:18:19 +00004272 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004273 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004274
Douglas Gregor18fe5682008-11-03 20:45:27 +00004275 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00004276 if (InitEntity)
4277 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
4278 else
4279 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
John McCallcbce6062010-01-12 07:18:19 +00004280 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor18fe5682008-11-03 20:45:27 +00004281 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004282
4283 case OR_Deleted:
4284 if (InitEntity)
4285 Diag(Loc, diag::err_ovl_deleted_init)
4286 << Best->Function->isDeleted()
4287 << InitEntity << Range;
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004288 else {
4289 const CXXRecordDecl *RD =
4290 cast<CXXRecordDecl>(ClassType->getAs<RecordType>()->getDecl());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004291 Diag(Loc, diag::err_ovl_deleted_init)
4292 << Best->Function->isDeleted()
Fariborz Jahanian6a587cb2009-11-25 21:53:11 +00004293 << RD->getDeclName() << Range;
4294 }
John McCallcbce6062010-01-12 07:18:19 +00004295 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004296 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004297 }
Mike Stump1eb44332009-09-09 15:08:12 +00004298
Douglas Gregor39da0b82009-09-09 23:08:42 +00004299 // Convert the arguments, fill in default arguments, etc.
4300 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4301 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
4302 return 0;
4303
4304 return Constructor;
4305}
4306
4307/// \brief Given a constructor and the set of arguments provided for the
4308/// constructor, convert the arguments and add any required default arguments
4309/// to form a proper call to this constructor.
4310///
4311/// \returns true if an error occurred, false otherwise.
4312bool
4313Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4314 MultiExprArg ArgsPtr,
4315 SourceLocation Loc,
4316 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4317 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4318 unsigned NumArgs = ArgsPtr.size();
4319 Expr **Args = (Expr **)ArgsPtr.get();
4320
4321 const FunctionProtoType *Proto
4322 = Constructor->getType()->getAs<FunctionProtoType>();
4323 assert(Proto && "Constructor without a prototype?");
4324 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004325
4326 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004327 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004328 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004329 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004330 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004331
4332 VariadicCallType CallType =
4333 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4334 llvm::SmallVector<Expr *, 8> AllArgs;
4335 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4336 Proto, 0, Args, NumArgs, AllArgs,
4337 CallType);
4338 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4339 ConvertedArgs.push_back(AllArgs[i]);
4340 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004341}
4342
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004343/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4344/// determine whether they are reference-related,
4345/// reference-compatible, reference-compatible with added
4346/// qualification, or incompatible, for use in C++ initialization by
4347/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4348/// type, and the first type (T1) is the pointee type of the reference
4349/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004350Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004351Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004352 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004353 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004354 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004355 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004356 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004357
Douglas Gregor393896f2009-11-05 13:06:35 +00004358 QualType T1 = Context.getCanonicalType(OrigT1);
4359 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004360 Qualifiers T1Quals, T2Quals;
4361 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4362 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004363
4364 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004365 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004366 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004367 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004368 if (UnqualT1 == UnqualT2)
4369 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004370 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4371 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4372 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004373 DerivedToBase = true;
4374 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004375 return Ref_Incompatible;
4376
4377 // At this point, we know that T1 and T2 are reference-related (at
4378 // least).
4379
Chandler Carruth28e318c2009-12-29 07:16:59 +00004380 // If the type is an array type, promote the element qualifiers to the type
4381 // for comparison.
4382 if (isa<ArrayType>(T1) && T1Quals)
4383 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4384 if (isa<ArrayType>(T2) && T2Quals)
4385 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4386
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004387 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004388 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004389 // reference-related to T2 and cv1 is the same cv-qualification
4390 // as, or greater cv-qualification than, cv2. For purposes of
4391 // overload resolution, cases for which cv1 is greater
4392 // cv-qualification than cv2 are identified as
4393 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004394 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004395 return Ref_Compatible;
4396 else if (T1.isMoreQualifiedThan(T2))
4397 return Ref_Compatible_With_Added_Qualification;
4398 else
4399 return Ref_Related;
4400}
4401
4402/// CheckReferenceInit - Check the initialization of a reference
4403/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4404/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004405/// list), and DeclType is the type of the declaration. When ICS is
4406/// non-null, this routine will compute the implicit conversion
4407/// sequence according to C++ [over.ics.ref] and will not produce any
4408/// diagnostics; when ICS is null, it will emit diagnostics when any
4409/// errors are found. Either way, a return value of true indicates
4410/// that there was a failure, a return value of false indicates that
4411/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004412///
4413/// When @p SuppressUserConversions, user-defined conversions are
4414/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004415/// When @p AllowExplicit, we also permit explicit user-defined
4416/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004417/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004418/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4419/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004420bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004421Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004422 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004423 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004424 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004425 ImplicitConversionSequence *ICS,
4426 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004427 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4428
Ted Kremenek6217b802009-07-29 21:53:49 +00004429 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004430 QualType T2 = Init->getType();
4431
Douglas Gregor904eed32008-11-10 20:40:00 +00004432 // If the initializer is the address of an overloaded function, try
4433 // to resolve the overloaded function. If all goes well, T2 is the
4434 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004435 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004436 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004437 ICS != 0);
4438 if (Fn) {
4439 // Since we're performing this reference-initialization for
4440 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004441 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004442 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004443 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004444
Anders Carlsson96ad5332009-10-21 17:16:23 +00004445 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004446 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004447
4448 T2 = Fn->getType();
4449 }
4450 }
4451
Douglas Gregor15da57e2008-10-29 02:00:59 +00004452 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004453 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004454 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004455 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4456 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004457 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004458 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004459
4460 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004461 if (ICS) {
4462 ICS->setBad();
4463 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4464 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004465
4466 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004467 // A reference to type "cv1 T1" is initialized by an expression
4468 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004469
4470 // -- If the initializer expression
4471
Sebastian Redla9845802009-03-29 15:27:50 +00004472 // Rvalue references cannot bind to lvalues (N2812).
4473 // There is absolutely no situation where they can. In particular, note that
4474 // this is ill-formed, even if B has a user-defined conversion to A&&:
4475 // B b;
4476 // A&& r = b;
4477 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4478 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004479 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004480 << Init->getSourceRange();
4481 return true;
4482 }
4483
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004484 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004485 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4486 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004487 //
4488 // Note that the bit-field check is skipped if we are just computing
4489 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004490 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004491 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004492 BindsDirectly = true;
4493
Douglas Gregor15da57e2008-10-29 02:00:59 +00004494 if (ICS) {
4495 // C++ [over.ics.ref]p1:
4496 // When a parameter of reference type binds directly (8.5.3)
4497 // to an argument expression, the implicit conversion sequence
4498 // is the identity conversion, unless the argument expression
4499 // has a type that is a derived class of the parameter type,
4500 // in which case the implicit conversion sequence is a
4501 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004502 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004503 ICS->Standard.First = ICK_Identity;
4504 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4505 ICS->Standard.Third = ICK_Identity;
4506 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004507 ICS->Standard.setToType(0, T2);
4508 ICS->Standard.setToType(1, T1);
4509 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004510 ICS->Standard.ReferenceBinding = true;
4511 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004512 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004513 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004514
4515 // Nothing more to do: the inaccessibility/ambiguity check for
4516 // derived-to-base conversions is suppressed when we're
4517 // computing the implicit conversion sequence (C++
4518 // [over.best.ics]p2).
4519 return false;
4520 } else {
4521 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004522 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4523 if (DerivedToBase)
4524 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004525 else if(CheckExceptionSpecCompatibility(Init, T1))
4526 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004527 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004528 }
4529 }
4530
4531 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004532 // implicitly converted to an lvalue of type "cv3 T3,"
4533 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004534 // 92) (this conversion is selected by enumerating the
4535 // applicable conversion functions (13.3.1.6) and choosing
4536 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004537 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004538 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004539 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004540 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004541
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004542 OverloadCandidateSet CandidateSet;
John McCalleec51cf2010-01-20 00:46:10 +00004543 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004544 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004545 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004546 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004547 NamedDecl *D = *I;
4548 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4549 if (isa<UsingShadowDecl>(D))
4550 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4551
Mike Stump1eb44332009-09-09 15:08:12 +00004552 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004553 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004554 CXXConversionDecl *Conv;
4555 if (ConvTemplate)
4556 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4557 else
John McCall701c89e2009-12-03 04:06:58 +00004558 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004559
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004560 // If the conversion function doesn't return a reference type,
4561 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004562 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004563 (AllowExplicit || !Conv->isExplicit())) {
4564 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004565 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004566 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004567 else
John McCall86820f52010-01-26 01:37:31 +00004568 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4569 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004570 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004571 }
4572
4573 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004574 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004575 case OR_Success:
4576 // This is a direct binding.
4577 BindsDirectly = true;
4578
4579 if (ICS) {
4580 // C++ [over.ics.ref]p1:
4581 //
4582 // [...] If the parameter binds directly to the result of
4583 // applying a conversion function to the argument
4584 // expression, the implicit conversion sequence is a
4585 // user-defined conversion sequence (13.3.3.1.2), with the
4586 // second standard conversion sequence either an identity
4587 // conversion or, if the conversion function returns an
4588 // entity of a type that is a derived class of the parameter
4589 // type, a derived-to-base Conversion.
John McCall1d318332010-01-12 00:44:57 +00004590 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004591 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4592 ICS->UserDefined.After = Best->FinalConversion;
4593 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004594 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004595 assert(ICS->UserDefined.After.ReferenceBinding &&
4596 ICS->UserDefined.After.DirectBinding &&
4597 "Expected a direct reference binding!");
4598 return false;
4599 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004600 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004601 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004602 CastExpr::CK_UserDefinedConversion,
4603 cast<CXXMethodDecl>(Best->Function),
4604 Owned(Init));
4605 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004606
4607 if (CheckExceptionSpecCompatibility(Init, T1))
4608 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004609 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4610 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004611 }
4612 break;
4613
4614 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004615 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004616 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004617 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4618 Cand != CandidateSet.end(); ++Cand)
4619 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004620 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004621 break;
4622 }
4623 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4624 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004625 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004626 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004627
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004628 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004629 case OR_Deleted:
4630 // There was no suitable conversion, or we found a deleted
4631 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004632 break;
4633 }
4634 }
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004636 if (BindsDirectly) {
4637 // C++ [dcl.init.ref]p4:
4638 // [...] In all cases where the reference-related or
4639 // reference-compatible relationship of two types is used to
4640 // establish the validity of a reference binding, and T1 is a
4641 // base class of T2, a program that necessitates such a binding
4642 // is ill-formed if T1 is an inaccessible (clause 11) or
4643 // ambiguous (10.2) base class of T2.
4644 //
4645 // Note that we only check this condition when we're allowed to
4646 // complain about errors, because we should not be checking for
4647 // ambiguity (or inaccessibility) unless the reference binding
4648 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004649 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004650 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004651 Init->getSourceRange(),
4652 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004653 else
4654 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004655 }
4656
4657 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004658 // type (i.e., cv1 shall be const), or the reference shall be an
4659 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004660 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004661 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004662 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004663 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004664 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004665 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004666 return true;
4667 }
4668
4669 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004670 // class type, and "cv1 T1" is reference-compatible with
4671 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004672 // following ways (the choice is implementation-defined):
4673 //
4674 // -- The reference is bound to the object represented by
4675 // the rvalue (see 3.10) or to a sub-object within that
4676 // object.
4677 //
Eli Friedman33a31382009-08-05 19:21:58 +00004678 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004679 // a constructor is called to copy the entire rvalue
4680 // object into the temporary. The reference is bound to
4681 // the temporary or to a sub-object within the
4682 // temporary.
4683 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004684 // The constructor that would be used to make the copy
4685 // shall be callable whether or not the copy is actually
4686 // done.
4687 //
Sebastian Redla9845802009-03-29 15:27:50 +00004688 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004689 // freedom, so we will always take the first option and never build
4690 // a temporary in this case. FIXME: We will, however, have to check
4691 // for the presence of a copy constructor in C++98/03 mode.
4692 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004693 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4694 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004695 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004696 ICS->Standard.First = ICK_Identity;
4697 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4698 ICS->Standard.Third = ICK_Identity;
4699 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004700 ICS->Standard.setToType(0, T2);
4701 ICS->Standard.setToType(1, T1);
4702 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004703 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004704 ICS->Standard.DirectBinding = false;
4705 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004706 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004707 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004708 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4709 if (DerivedToBase)
4710 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004711 else if(CheckExceptionSpecCompatibility(Init, T1))
4712 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004713 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004714 }
4715 return false;
4716 }
4717
Eli Friedman33a31382009-08-05 19:21:58 +00004718 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004719 // initialized from the initializer expression using the
4720 // rules for a non-reference copy initialization (8.5). The
4721 // reference is then bound to the temporary. If T1 is
4722 // reference-related to T2, cv1 must be the same
4723 // cv-qualification as, or greater cv-qualification than,
4724 // cv2; otherwise, the program is ill-formed.
4725 if (RefRelationship == Ref_Related) {
4726 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4727 // we would be reference-compatible or reference-compatible with
4728 // added qualification. But that wasn't the case, so the reference
4729 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004730 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004731 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004732 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004733 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004734 return true;
4735 }
4736
Douglas Gregor734d9862009-01-30 23:27:23 +00004737 // If at least one of the types is a class type, the types are not
4738 // related, and we aren't allowed any user conversions, the
4739 // reference binding fails. This case is important for breaking
4740 // recursion, since TryImplicitConversion below will attempt to
4741 // create a temporary through the use of a copy constructor.
4742 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4743 (T1->isRecordType() || T2->isRecordType())) {
4744 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004745 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004746 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004747 return true;
4748 }
4749
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004750 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004751 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004752 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004753 //
Sebastian Redla9845802009-03-29 15:27:50 +00004754 // When a parameter of reference type is not bound directly to
4755 // an argument expression, the conversion sequence is the one
4756 // required to convert the argument expression to the
4757 // underlying type of the reference according to
4758 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4759 // to copy-initializing a temporary of the underlying type with
4760 // the argument expression. Any difference in top-level
4761 // cv-qualification is subsumed by the initialization itself
4762 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004763 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4764 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004765 /*ForceRValue=*/false,
4766 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Sebastian Redla9845802009-03-29 15:27:50 +00004768 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004769 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004770 ICS->Standard.ReferenceBinding = true;
4771 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004772 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004773 ICS->UserDefined.After.ReferenceBinding = true;
4774 ICS->UserDefined.After.RRefBinding = isRValRef;
4775 }
John McCall1d318332010-01-12 00:44:57 +00004776 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004777 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004778 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004779 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004780 false, false,
4781 Conversions);
4782 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004783 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004784 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004785 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004786 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004787 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004788 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004789 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004790 }
4791 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004792 else {
4793 if (isRValRef)
4794 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4795 << Init->getSourceRange();
4796 else
4797 Diag(DeclLoc, diag::err_invalid_initialization)
4798 << DeclType << Init->getType() << Init->getSourceRange();
4799 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004800 }
4801 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004802 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004803}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004804
Anders Carlsson20d45d22009-12-12 00:32:00 +00004805static inline bool
4806CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4807 const FunctionDecl *FnDecl) {
4808 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4809 if (isa<NamespaceDecl>(DC)) {
4810 return SemaRef.Diag(FnDecl->getLocation(),
4811 diag::err_operator_new_delete_declared_in_namespace)
4812 << FnDecl->getDeclName();
4813 }
4814
4815 if (isa<TranslationUnitDecl>(DC) &&
4816 FnDecl->getStorageClass() == FunctionDecl::Static) {
4817 return SemaRef.Diag(FnDecl->getLocation(),
4818 diag::err_operator_new_delete_declared_static)
4819 << FnDecl->getDeclName();
4820 }
4821
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004822 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004823}
4824
Anders Carlsson156c78e2009-12-13 17:53:43 +00004825static inline bool
4826CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4827 CanQualType ExpectedResultType,
4828 CanQualType ExpectedFirstParamType,
4829 unsigned DependentParamTypeDiag,
4830 unsigned InvalidParamTypeDiag) {
4831 QualType ResultType =
4832 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4833
4834 // Check that the result type is not dependent.
4835 if (ResultType->isDependentType())
4836 return SemaRef.Diag(FnDecl->getLocation(),
4837 diag::err_operator_new_delete_dependent_result_type)
4838 << FnDecl->getDeclName() << ExpectedResultType;
4839
4840 // Check that the result type is what we expect.
4841 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4842 return SemaRef.Diag(FnDecl->getLocation(),
4843 diag::err_operator_new_delete_invalid_result_type)
4844 << FnDecl->getDeclName() << ExpectedResultType;
4845
4846 // A function template must have at least 2 parameters.
4847 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4848 return SemaRef.Diag(FnDecl->getLocation(),
4849 diag::err_operator_new_delete_template_too_few_parameters)
4850 << FnDecl->getDeclName();
4851
4852 // The function decl must have at least 1 parameter.
4853 if (FnDecl->getNumParams() == 0)
4854 return SemaRef.Diag(FnDecl->getLocation(),
4855 diag::err_operator_new_delete_too_few_parameters)
4856 << FnDecl->getDeclName();
4857
4858 // Check the the first parameter type is not dependent.
4859 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4860 if (FirstParamType->isDependentType())
4861 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4862 << FnDecl->getDeclName() << ExpectedFirstParamType;
4863
4864 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004865 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004866 ExpectedFirstParamType)
4867 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4868 << FnDecl->getDeclName() << ExpectedFirstParamType;
4869
4870 return false;
4871}
4872
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004873static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004874CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004875 // C++ [basic.stc.dynamic.allocation]p1:
4876 // A program is ill-formed if an allocation function is declared in a
4877 // namespace scope other than global scope or declared static in global
4878 // scope.
4879 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4880 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004881
4882 CanQualType SizeTy =
4883 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4884
4885 // C++ [basic.stc.dynamic.allocation]p1:
4886 // The return type shall be void*. The first parameter shall have type
4887 // std::size_t.
4888 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4889 SizeTy,
4890 diag::err_operator_new_dependent_param_type,
4891 diag::err_operator_new_param_type))
4892 return true;
4893
4894 // C++ [basic.stc.dynamic.allocation]p1:
4895 // The first parameter shall not have an associated default argument.
4896 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004897 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004898 diag::err_operator_new_default_arg)
4899 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4900
4901 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004902}
4903
4904static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004905CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4906 // C++ [basic.stc.dynamic.deallocation]p1:
4907 // A program is ill-formed if deallocation functions are declared in a
4908 // namespace scope other than global scope or declared static in global
4909 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004910 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4911 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004912
4913 // C++ [basic.stc.dynamic.deallocation]p2:
4914 // Each deallocation function shall return void and its first parameter
4915 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004916 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4917 SemaRef.Context.VoidPtrTy,
4918 diag::err_operator_delete_dependent_param_type,
4919 diag::err_operator_delete_param_type))
4920 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004921
Anders Carlsson46991d62009-12-12 00:16:02 +00004922 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4923 if (FirstParamType->isDependentType())
4924 return SemaRef.Diag(FnDecl->getLocation(),
4925 diag::err_operator_delete_dependent_param_type)
4926 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4927
4928 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4929 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004930 return SemaRef.Diag(FnDecl->getLocation(),
4931 diag::err_operator_delete_param_type)
4932 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004933
4934 return false;
4935}
4936
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004937/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4938/// of this overloaded operator is well-formed. If so, returns false;
4939/// otherwise, emits appropriate diagnostics and returns true.
4940bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004941 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004942 "Expected an overloaded operator declaration");
4943
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004944 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4945
Mike Stump1eb44332009-09-09 15:08:12 +00004946 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004947 // The allocation and deallocation functions, operator new,
4948 // operator new[], operator delete and operator delete[], are
4949 // described completely in 3.7.3. The attributes and restrictions
4950 // found in the rest of this subclause do not apply to them unless
4951 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004952 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004953 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004954
Anders Carlssona3ccda52009-12-12 00:26:23 +00004955 if (Op == OO_New || Op == OO_Array_New)
4956 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004957
4958 // C++ [over.oper]p6:
4959 // An operator function shall either be a non-static member
4960 // function or be a non-member function and have at least one
4961 // parameter whose type is a class, a reference to a class, an
4962 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004963 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4964 if (MethodDecl->isStatic())
4965 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004966 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004967 } else {
4968 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004969 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4970 ParamEnd = FnDecl->param_end();
4971 Param != ParamEnd; ++Param) {
4972 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004973 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4974 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004975 ClassOrEnumParam = true;
4976 break;
4977 }
4978 }
4979
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004980 if (!ClassOrEnumParam)
4981 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004982 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004983 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004984 }
4985
4986 // C++ [over.oper]p8:
4987 // An operator function cannot have default arguments (8.3.6),
4988 // except where explicitly stated below.
4989 //
Mike Stump1eb44332009-09-09 15:08:12 +00004990 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004991 // (C++ [over.call]p1).
4992 if (Op != OO_Call) {
4993 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4994 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004995 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004996 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004997 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004998 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004999 }
5000 }
5001
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005002 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5003 { false, false, false }
5004#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5005 , { Unary, Binary, MemberOnly }
5006#include "clang/Basic/OperatorKinds.def"
5007 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005008
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005009 bool CanBeUnaryOperator = OperatorUses[Op][0];
5010 bool CanBeBinaryOperator = OperatorUses[Op][1];
5011 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005012
5013 // C++ [over.oper]p8:
5014 // [...] Operator functions cannot have more or fewer parameters
5015 // than the number required for the corresponding operator, as
5016 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005017 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005018 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005019 if (Op != OO_Call &&
5020 ((NumParams == 1 && !CanBeUnaryOperator) ||
5021 (NumParams == 2 && !CanBeBinaryOperator) ||
5022 (NumParams < 1) || (NumParams > 2))) {
5023 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005024 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005025 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005026 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005027 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005028 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005029 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005030 assert(CanBeBinaryOperator &&
5031 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005032 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005033 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005034
Chris Lattner416e46f2008-11-21 07:57:12 +00005035 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005036 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005037 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005038
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005039 // Overloaded operators other than operator() cannot be variadic.
5040 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005041 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005042 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005043 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005044 }
5045
5046 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005047 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5048 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005049 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005050 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005051 }
5052
5053 // C++ [over.inc]p1:
5054 // The user-defined function called operator++ implements the
5055 // prefix and postfix ++ operator. If this function is a member
5056 // function with no parameters, or a non-member function with one
5057 // parameter of class or enumeration type, it defines the prefix
5058 // increment operator ++ for objects of that type. If the function
5059 // is a member function with one parameter (which shall be of type
5060 // int) or a non-member function with two parameters (the second
5061 // of which shall be of type int), it defines the postfix
5062 // increment operator ++ for objects of that type.
5063 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5064 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5065 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005066 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005067 ParamIsInt = BT->getKind() == BuiltinType::Int;
5068
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005069 if (!ParamIsInt)
5070 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005071 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005072 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005073 }
5074
Sebastian Redl64b45f72009-01-05 20:52:13 +00005075 // Notify the class if it got an assignment operator.
5076 if (Op == OO_Equal) {
5077 // Would have returned earlier otherwise.
5078 assert(isa<CXXMethodDecl>(FnDecl) &&
5079 "Overloaded = not member, but not filtered.");
5080 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5081 Method->getParent()->addedAssignmentOperator(Context, Method);
5082 }
5083
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005084 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005085}
Chris Lattner5a003a42008-12-17 07:09:26 +00005086
Sean Hunta6c058d2010-01-13 09:01:02 +00005087/// CheckLiteralOperatorDeclaration - Check whether the declaration
5088/// of this literal operator function is well-formed. If so, returns
5089/// false; otherwise, emits appropriate diagnostics and returns true.
5090bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5091 DeclContext *DC = FnDecl->getDeclContext();
5092 Decl::Kind Kind = DC->getDeclKind();
5093 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5094 Kind != Decl::LinkageSpec) {
5095 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5096 << FnDecl->getDeclName();
5097 return true;
5098 }
5099
5100 bool Valid = false;
5101
5102 // FIXME: Check for the one valid template signature
5103 // template <char...> type operator "" name();
5104
5105 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5106 // Check the first parameter
5107 QualType T = (*Param)->getType();
5108
5109 // unsigned long long int and long double are allowed, but only
5110 // alone.
5111 // We also allow any character type; their omission seems to be a bug
5112 // in n3000
5113 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5114 Context.hasSameType(T, Context.LongDoubleTy) ||
5115 Context.hasSameType(T, Context.CharTy) ||
5116 Context.hasSameType(T, Context.WCharTy) ||
5117 Context.hasSameType(T, Context.Char16Ty) ||
5118 Context.hasSameType(T, Context.Char32Ty)) {
5119 if (++Param == FnDecl->param_end())
5120 Valid = true;
5121 goto FinishedParams;
5122 }
5123
5124 // Otherwise it must be a pointer to const; let's strip those.
5125 const PointerType *PT = T->getAs<PointerType>();
5126 if (!PT)
5127 goto FinishedParams;
5128 T = PT->getPointeeType();
5129 if (!T.isConstQualified())
5130 goto FinishedParams;
5131 T = T.getUnqualifiedType();
5132
5133 // Move on to the second parameter;
5134 ++Param;
5135
5136 // If there is no second parameter, the first must be a const char *
5137 if (Param == FnDecl->param_end()) {
5138 if (Context.hasSameType(T, Context.CharTy))
5139 Valid = true;
5140 goto FinishedParams;
5141 }
5142
5143 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5144 // are allowed as the first parameter to a two-parameter function
5145 if (!(Context.hasSameType(T, Context.CharTy) ||
5146 Context.hasSameType(T, Context.WCharTy) ||
5147 Context.hasSameType(T, Context.Char16Ty) ||
5148 Context.hasSameType(T, Context.Char32Ty)))
5149 goto FinishedParams;
5150
5151 // The second and final parameter must be an std::size_t
5152 T = (*Param)->getType().getUnqualifiedType();
5153 if (Context.hasSameType(T, Context.getSizeType()) &&
5154 ++Param == FnDecl->param_end())
5155 Valid = true;
5156 }
5157
5158 // FIXME: This diagnostic is absolutely terrible.
5159FinishedParams:
5160 if (!Valid) {
5161 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5162 << FnDecl->getDeclName();
5163 return true;
5164 }
5165
5166 return false;
5167}
5168
Douglas Gregor074149e2009-01-05 19:45:36 +00005169/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5170/// linkage specification, including the language and (if present)
5171/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5172/// the location of the language string literal, which is provided
5173/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5174/// the '{' brace. Otherwise, this linkage specification does not
5175/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005176Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5177 SourceLocation ExternLoc,
5178 SourceLocation LangLoc,
5179 const char *Lang,
5180 unsigned StrSize,
5181 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005182 LinkageSpecDecl::LanguageIDs Language;
5183 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5184 Language = LinkageSpecDecl::lang_c;
5185 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5186 Language = LinkageSpecDecl::lang_cxx;
5187 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005188 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005189 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005190 }
Mike Stump1eb44332009-09-09 15:08:12 +00005191
Chris Lattnercc98eac2008-12-17 07:13:27 +00005192 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005193
Douglas Gregor074149e2009-01-05 19:45:36 +00005194 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005195 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005196 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005197 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005198 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005199 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005200}
5201
Douglas Gregor074149e2009-01-05 19:45:36 +00005202/// ActOnFinishLinkageSpecification - Completely the definition of
5203/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5204/// valid, it's the position of the closing '}' brace in a linkage
5205/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005206Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5207 DeclPtrTy LinkageSpec,
5208 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005209 if (LinkageSpec)
5210 PopDeclContext();
5211 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005212}
5213
Douglas Gregord308e622009-05-18 20:51:54 +00005214/// \brief Perform semantic analysis for the variable declaration that
5215/// occurs within a C++ catch clause, returning the newly-created
5216/// variable.
5217VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005218 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005219 IdentifierInfo *Name,
5220 SourceLocation Loc,
5221 SourceRange Range) {
5222 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005223
5224 // Arrays and functions decay.
5225 if (ExDeclType->isArrayType())
5226 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5227 else if (ExDeclType->isFunctionType())
5228 ExDeclType = Context.getPointerType(ExDeclType);
5229
5230 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5231 // The exception-declaration shall not denote a pointer or reference to an
5232 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005233 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005234 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005235 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005236 Invalid = true;
5237 }
Douglas Gregord308e622009-05-18 20:51:54 +00005238
Sebastian Redl4b07b292008-12-22 19:15:10 +00005239 QualType BaseType = ExDeclType;
5240 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005241 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005242 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005243 BaseType = Ptr->getPointeeType();
5244 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005245 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005246 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005247 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005248 BaseType = Ref->getPointeeType();
5249 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005250 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005251 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005252 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005253 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005254 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005255
Mike Stump1eb44332009-09-09 15:08:12 +00005256 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005257 RequireNonAbstractType(Loc, ExDeclType,
5258 diag::err_abstract_type_in_decl,
5259 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005260 Invalid = true;
5261
Douglas Gregord308e622009-05-18 20:51:54 +00005262 // FIXME: Need to test for ability to copy-construct and destroy the
5263 // exception variable.
5264
Sebastian Redl8351da02008-12-22 21:35:02 +00005265 // FIXME: Need to check for abstract classes.
5266
Mike Stump1eb44332009-09-09 15:08:12 +00005267 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005268 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005269
5270 if (Invalid)
5271 ExDecl->setInvalidDecl();
5272
5273 return ExDecl;
5274}
5275
5276/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5277/// handler.
5278Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005279 TypeSourceInfo *TInfo = 0;
5280 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005281
5282 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005283 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005284 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005285 // The scope should be freshly made just for us. There is just no way
5286 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005287 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005288 if (PrevDecl->isTemplateParameter()) {
5289 // Maybe we will complain about the shadowed template parameter.
5290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005291 }
5292 }
5293
Chris Lattnereaaebc72009-04-25 08:06:05 +00005294 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005295 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5296 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005297 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005298 }
5299
John McCalla93c9342009-12-07 02:54:59 +00005300 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005301 D.getIdentifier(),
5302 D.getIdentifierLoc(),
5303 D.getDeclSpec().getSourceRange());
5304
Chris Lattnereaaebc72009-04-25 08:06:05 +00005305 if (Invalid)
5306 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Sebastian Redl4b07b292008-12-22 19:15:10 +00005308 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005309 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005310 PushOnScopeChains(ExDecl, S);
5311 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005312 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005313
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005314 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005315 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005316}
Anders Carlssonfb311762009-03-14 00:25:26 +00005317
Mike Stump1eb44332009-09-09 15:08:12 +00005318Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005319 ExprArg assertexpr,
5320 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005321 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005322 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005323 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5324
Anders Carlssonc3082412009-03-14 00:33:21 +00005325 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5326 llvm::APSInt Value(32);
5327 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5328 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5329 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005330 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005331 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005332
Anders Carlssonc3082412009-03-14 00:33:21 +00005333 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005334 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005335 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005336 }
5337 }
Mike Stump1eb44332009-09-09 15:08:12 +00005338
Anders Carlsson77d81422009-03-15 17:35:16 +00005339 assertexpr.release();
5340 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005341 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005342 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005343
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005344 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005345 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005346}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005347
John McCalldd4a3b02009-09-16 22:47:08 +00005348/// Handle a friend type declaration. This works in tandem with
5349/// ActOnTag.
5350///
5351/// Notes on friend class templates:
5352///
5353/// We generally treat friend class declarations as if they were
5354/// declaring a class. So, for example, the elaborated type specifier
5355/// in a friend declaration is required to obey the restrictions of a
5356/// class-head (i.e. no typedefs in the scope chain), template
5357/// parameters are required to match up with simple template-ids, &c.
5358/// However, unlike when declaring a template specialization, it's
5359/// okay to refer to a template specialization without an empty
5360/// template parameter declaration, e.g.
5361/// friend class A<T>::B<unsigned>;
5362/// We permit this as a special case; if there are any template
5363/// parameters present at all, require proper matching, i.e.
5364/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005365Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005366 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005367 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005368
5369 assert(DS.isFriendSpecified());
5370 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5371
John McCalldd4a3b02009-09-16 22:47:08 +00005372 // Try to convert the decl specifier to a type. This works for
5373 // friend templates because ActOnTag never produces a ClassTemplateDecl
5374 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005375 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005376 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5377 if (TheDeclarator.isInvalidType())
5378 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005379
John McCalldd4a3b02009-09-16 22:47:08 +00005380 // This is definitely an error in C++98. It's probably meant to
5381 // be forbidden in C++0x, too, but the specification is just
5382 // poorly written.
5383 //
5384 // The problem is with declarations like the following:
5385 // template <T> friend A<T>::foo;
5386 // where deciding whether a class C is a friend or not now hinges
5387 // on whether there exists an instantiation of A that causes
5388 // 'foo' to equal C. There are restrictions on class-heads
5389 // (which we declare (by fiat) elaborated friend declarations to
5390 // be) that makes this tractable.
5391 //
5392 // FIXME: handle "template <> friend class A<T>;", which
5393 // is possibly well-formed? Who even knows?
5394 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5395 Diag(Loc, diag::err_tagless_friend_type_template)
5396 << DS.getSourceRange();
5397 return DeclPtrTy();
5398 }
5399
John McCall02cace72009-08-28 07:59:38 +00005400 // C++ [class.friend]p2:
5401 // An elaborated-type-specifier shall be used in a friend declaration
5402 // for a class.*
5403 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005404 // This is one of the rare places in Clang where it's legitimate to
5405 // ask about the "spelling" of the type.
5406 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5407 // If we evaluated the type to a record type, suggest putting
5408 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005409 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005410 RecordDecl *RD = RT->getDecl();
5411
5412 std::string InsertionText = std::string(" ") + RD->getKindName();
5413
John McCalle3af0232009-10-07 23:34:25 +00005414 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5415 << (unsigned) RD->getTagKind()
5416 << T
5417 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005418 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5419 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005420 return DeclPtrTy();
5421 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005422 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5423 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005424 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005425 }
5426 }
5427
John McCalle3af0232009-10-07 23:34:25 +00005428 // Enum types cannot be friends.
5429 if (T->getAs<EnumType>()) {
5430 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5431 << SourceRange(DS.getFriendSpecLoc());
5432 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005433 }
John McCall02cace72009-08-28 07:59:38 +00005434
John McCall02cace72009-08-28 07:59:38 +00005435 // C++98 [class.friend]p1: A friend of a class is a function
5436 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005437 // This is fixed in DR77, which just barely didn't make the C++03
5438 // deadline. It's also a very silly restriction that seriously
5439 // affects inner classes and which nobody else seems to implement;
5440 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005441
John McCalldd4a3b02009-09-16 22:47:08 +00005442 Decl *D;
5443 if (TempParams.size())
5444 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5445 TempParams.size(),
5446 (TemplateParameterList**) TempParams.release(),
5447 T.getTypePtr(),
5448 DS.getFriendSpecLoc());
5449 else
5450 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5451 DS.getFriendSpecLoc());
5452 D->setAccess(AS_public);
5453 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005454
John McCalldd4a3b02009-09-16 22:47:08 +00005455 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005456}
5457
John McCallbbbcdd92009-09-11 21:02:39 +00005458Sema::DeclPtrTy
5459Sema::ActOnFriendFunctionDecl(Scope *S,
5460 Declarator &D,
5461 bool IsDefinition,
5462 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005463 const DeclSpec &DS = D.getDeclSpec();
5464
5465 assert(DS.isFriendSpecified());
5466 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5467
5468 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005469 TypeSourceInfo *TInfo = 0;
5470 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005471
5472 // C++ [class.friend]p1
5473 // A friend of a class is a function or class....
5474 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005475 // It *doesn't* see through dependent types, which is correct
5476 // according to [temp.arg.type]p3:
5477 // If a declaration acquires a function type through a
5478 // type dependent on a template-parameter and this causes
5479 // a declaration that does not use the syntactic form of a
5480 // function declarator to have a function type, the program
5481 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005482 if (!T->isFunctionType()) {
5483 Diag(Loc, diag::err_unexpected_friend);
5484
5485 // It might be worthwhile to try to recover by creating an
5486 // appropriate declaration.
5487 return DeclPtrTy();
5488 }
5489
5490 // C++ [namespace.memdef]p3
5491 // - If a friend declaration in a non-local class first declares a
5492 // class or function, the friend class or function is a member
5493 // of the innermost enclosing namespace.
5494 // - The name of the friend is not found by simple name lookup
5495 // until a matching declaration is provided in that namespace
5496 // scope (either before or after the class declaration granting
5497 // friendship).
5498 // - If a friend function is called, its name may be found by the
5499 // name lookup that considers functions from namespaces and
5500 // classes associated with the types of the function arguments.
5501 // - When looking for a prior declaration of a class or a function
5502 // declared as a friend, scopes outside the innermost enclosing
5503 // namespace scope are not considered.
5504
John McCall02cace72009-08-28 07:59:38 +00005505 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5506 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005507 assert(Name);
5508
John McCall67d1a672009-08-06 02:15:43 +00005509 // The context we found the declaration in, or in which we should
5510 // create the declaration.
5511 DeclContext *DC;
5512
5513 // FIXME: handle local classes
5514
5515 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005516 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5517 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005518 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005519 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005520 DC = computeDeclContext(ScopeQual);
5521
5522 // FIXME: handle dependent contexts
5523 if (!DC) return DeclPtrTy();
5524
John McCall68263142009-11-18 22:49:29 +00005525 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005526
5527 // If searching in that context implicitly found a declaration in
5528 // a different context, treat it like it wasn't found at all.
5529 // TODO: better diagnostics for this case. Suggesting the right
5530 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005531 // FIXME: getRepresentativeDecl() is not right here at all
5532 if (Previous.empty() ||
5533 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005534 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005535 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5536 return DeclPtrTy();
5537 }
5538
5539 // C++ [class.friend]p1: A friend of a class is a function or
5540 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005541 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005542 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5543
John McCall67d1a672009-08-06 02:15:43 +00005544 // Otherwise walk out to the nearest namespace scope looking for matches.
5545 } else {
5546 // TODO: handle local class contexts.
5547
5548 DC = CurContext;
5549 while (true) {
5550 // Skip class contexts. If someone can cite chapter and verse
5551 // for this behavior, that would be nice --- it's what GCC and
5552 // EDG do, and it seems like a reasonable intent, but the spec
5553 // really only says that checks for unqualified existing
5554 // declarations should stop at the nearest enclosing namespace,
5555 // not that they should only consider the nearest enclosing
5556 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005557 while (DC->isRecord())
5558 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005559
John McCall68263142009-11-18 22:49:29 +00005560 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005561
5562 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005563 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005564 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005565
John McCall67d1a672009-08-06 02:15:43 +00005566 if (DC->isFileContext()) break;
5567 DC = DC->getParent();
5568 }
5569
5570 // C++ [class.friend]p1: A friend of a class is a function or
5571 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005572 // C++0x changes this for both friend types and functions.
5573 // Most C++ 98 compilers do seem to give an error here, so
5574 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005575 if (!Previous.empty() && DC->Equals(CurContext)
5576 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005577 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5578 }
5579
Douglas Gregor182ddf02009-09-28 00:08:27 +00005580 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005581 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005582 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5583 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5584 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005585 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005586 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5587 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005588 return DeclPtrTy();
5589 }
John McCall67d1a672009-08-06 02:15:43 +00005590 }
5591
Douglas Gregor182ddf02009-09-28 00:08:27 +00005592 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005593 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005594 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005595 IsDefinition,
5596 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005597 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005598
Douglas Gregor182ddf02009-09-28 00:08:27 +00005599 assert(ND->getDeclContext() == DC);
5600 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005601
John McCallab88d972009-08-31 22:39:49 +00005602 // Add the function declaration to the appropriate lookup tables,
5603 // adjusting the redeclarations list as necessary. We don't
5604 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005605 //
John McCallab88d972009-08-31 22:39:49 +00005606 // Also update the scope-based lookup if the target context's
5607 // lookup context is in lexical scope.
5608 if (!CurContext->isDependentContext()) {
5609 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005610 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005611 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005612 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005613 }
John McCall02cace72009-08-28 07:59:38 +00005614
5615 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005616 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005617 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005618 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005619 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005620
Douglas Gregor7557a132009-12-24 20:56:24 +00005621 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5622 FrD->setSpecialization(true);
5623
Douglas Gregor182ddf02009-09-28 00:08:27 +00005624 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005625}
5626
Chris Lattnerb28317a2009-03-28 19:18:32 +00005627void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005628 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Chris Lattnerb28317a2009-03-28 19:18:32 +00005630 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005631 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5632 if (!Fn) {
5633 Diag(DelLoc, diag::err_deleted_non_function);
5634 return;
5635 }
5636 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5637 Diag(DelLoc, diag::err_deleted_decl_not_first);
5638 Diag(Prev->getLocation(), diag::note_previous_declaration);
5639 // If the declaration wasn't the first, we delete the function anyway for
5640 // recovery.
5641 }
5642 Fn->setDeleted();
5643}
Sebastian Redl13e88542009-04-27 21:33:24 +00005644
5645static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5647 ++CI) {
5648 Stmt *SubStmt = *CI;
5649 if (!SubStmt)
5650 continue;
5651 if (isa<ReturnStmt>(SubStmt))
5652 Self.Diag(SubStmt->getSourceRange().getBegin(),
5653 diag::err_return_in_constructor_handler);
5654 if (!isa<Expr>(SubStmt))
5655 SearchForReturnInStmt(Self, SubStmt);
5656 }
5657}
5658
5659void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5660 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5661 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5662 SearchForReturnInStmt(*this, Handler);
5663 }
5664}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005665
Mike Stump1eb44332009-09-09 15:08:12 +00005666bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005667 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005668 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5669 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005670
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005671 if (Context.hasSameType(NewTy, OldTy))
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005672 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005673
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005674 // Check if the return types are covariant
5675 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005677 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005678 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5679 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005680 NewClassTy = NewPT->getPointeeType();
5681 OldClassTy = OldPT->getPointeeType();
5682 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005683 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5684 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5685 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5686 NewClassTy = NewRT->getPointeeType();
5687 OldClassTy = OldRT->getPointeeType();
5688 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005689 }
5690 }
Mike Stump1eb44332009-09-09 15:08:12 +00005691
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005692 // The return types aren't either both pointers or references to a class type.
5693 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005694 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005695 diag::err_different_return_type_for_overriding_virtual_function)
5696 << New->getDeclName() << NewTy << OldTy;
5697 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005698
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005699 return true;
5700 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005701
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005702 // C++ [class.virtual]p6:
5703 // If the return type of D::f differs from the return type of B::f, the
5704 // class type in the return type of D::f shall be complete at the point of
5705 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005706 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5707 if (!RT->isBeingDefined() &&
5708 RequireCompleteType(New->getLocation(), NewClassTy,
5709 PDiag(diag::err_covariant_return_incomplete)
5710 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005711 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005712 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005713
Douglas Gregora4923eb2009-11-16 21:35:15 +00005714 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005715 // Check if the new class derives from the old class.
5716 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5717 Diag(New->getLocation(),
5718 diag::err_covariant_return_not_derived)
5719 << New->getDeclName() << NewTy << OldTy;
5720 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5721 return true;
5722 }
Mike Stump1eb44332009-09-09 15:08:12 +00005723
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005724 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00005725 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005726 diag::err_covariant_return_inaccessible_base,
5727 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5728 // FIXME: Should this point to the return type?
5729 New->getLocation(), SourceRange(), New->getDeclName())) {
5730 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5731 return true;
5732 }
5733 }
Mike Stump1eb44332009-09-09 15:08:12 +00005734
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005735 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005736 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005737 Diag(New->getLocation(),
5738 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005739 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005740 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5741 return true;
5742 };
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005744
5745 // The new class type must have the same or less qualifiers as the old type.
5746 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5747 Diag(New->getLocation(),
5748 diag::err_covariant_return_type_class_type_more_qualified)
5749 << New->getDeclName() << NewTy << OldTy;
5750 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5751 return true;
5752 };
Mike Stump1eb44332009-09-09 15:08:12 +00005753
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005754 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005755}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005756
Sean Huntbbd37c62009-11-21 08:43:09 +00005757bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5758 const CXXMethodDecl *Old)
5759{
5760 if (Old->hasAttr<FinalAttr>()) {
5761 Diag(New->getLocation(), diag::err_final_function_overridden)
5762 << New->getDeclName();
5763 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5764 return true;
5765 }
5766
5767 return false;
5768}
5769
Douglas Gregor4ba31362009-12-01 17:24:26 +00005770/// \brief Mark the given method pure.
5771///
5772/// \param Method the method to be marked pure.
5773///
5774/// \param InitRange the source range that covers the "0" initializer.
5775bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5776 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5777 Method->setPure();
5778
5779 // A class is abstract if at least one function is pure virtual.
5780 Method->getParent()->setAbstract(true);
5781 return false;
5782 }
5783
5784 if (!Method->isInvalidDecl())
5785 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5786 << Method->getDeclName() << InitRange;
5787 return true;
5788}
5789
John McCall731ad842009-12-19 09:28:58 +00005790/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5791/// an initializer for the out-of-line declaration 'Dcl'. The scope
5792/// is a fresh scope pushed for just this purpose.
5793///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005794/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5795/// static data member of class X, names should be looked up in the scope of
5796/// class X.
5797void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005798 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005799 Decl *D = Dcl.getAs<Decl>();
5800 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005801
John McCall731ad842009-12-19 09:28:58 +00005802 // We should only get called for declarations with scope specifiers, like:
5803 // int foo::bar;
5804 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005805 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005806}
5807
5808/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005809/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005810void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005811 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005812 Decl *D = Dcl.getAs<Decl>();
5813 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005814
John McCall731ad842009-12-19 09:28:58 +00005815 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005816 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005817}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005818
5819/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5820/// C++ if/switch/while/for statement.
5821/// e.g: "if (int x = f()) {...}"
5822Action::DeclResult
5823Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5824 // C++ 6.4p2:
5825 // The declarator shall not specify a function or an array.
5826 // The type-specifier-seq shall not contain typedef and shall not declare a
5827 // new class or enumeration.
5828 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5829 "Parser allowed 'typedef' as storage class of condition decl.");
5830
John McCalla93c9342009-12-07 02:54:59 +00005831 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005832 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005833 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005834
5835 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5836 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5837 // would be created and CXXConditionDeclExpr wants a VarDecl.
5838 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5839 << D.getSourceRange();
5840 return DeclResult();
5841 } else if (OwnedTag && OwnedTag->isDefinition()) {
5842 // The type-specifier-seq shall not declare a new class or enumeration.
5843 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5844 }
5845
5846 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5847 if (!Dcl)
5848 return DeclResult();
5849
5850 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5851 VD->setDeclaredInCondition(true);
5852 return Dcl;
5853}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005854
Anders Carlssond6a637f2009-12-07 08:24:59 +00005855void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5856 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005857 // Ignore dependent types.
5858 if (MD->isDependentContext())
5859 return;
5860
5861 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005862
5863 // Ignore classes without a vtable.
5864 if (!RD->isDynamicClass())
5865 return;
5866
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005867 // Ignore declarations that are not definitions.
5868 if (!MD->isThisDeclarationADefinition())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005869 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005870
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005871 if (isa<CXXConstructorDecl>(MD)) {
5872 switch (MD->getParent()->getTemplateSpecializationKind()) {
5873 case TSK_Undeclared:
5874 case TSK_ExplicitSpecialization:
5875 // Classes that aren't instantiations of templates don't need their
5876 // virtual methods marked until we see the definition of the key
5877 // function.
5878 return;
5879
5880 case TSK_ImplicitInstantiation:
5881 case TSK_ExplicitInstantiationDeclaration:
5882 case TSK_ExplicitInstantiationDefinition:
5883 // This is a constructor of a class template; mark all of the virtual
5884 // members as referenced to ensure that they get instantiatied.
5885 break;
5886 }
5887 } else if (!MD->isOutOfLine()) {
5888 // Consider only out-of-line definitions of member functions. When we see
5889 // an inline definition, it's too early to compute the key function.
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005890 return;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005891 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5892 // If this is not the key function, we don't need to mark virtual members.
5893 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5894 return;
5895 } else {
5896 // The class has no key function, so we've already noted that we need to
5897 // mark the virtual members of this class.
5898 return;
5899 }
5900
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005901 // We will need to mark all of the virtual members as referenced to build the
5902 // vtable.
5903 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005904}
5905
5906bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5907 if (ClassesWithUnmarkedVirtualMembers.empty())
5908 return false;
5909
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005910 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5911 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5912 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5913 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005914 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005915 }
5916
Anders Carlssond6a637f2009-12-07 08:24:59 +00005917 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005918}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005919
5920void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5921 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5922 e = RD->method_end(); i != e; ++i) {
5923 CXXMethodDecl *MD = *i;
5924
5925 // C++ [basic.def.odr]p2:
5926 // [...] A virtual member function is used if it is not pure. [...]
5927 if (MD->isVirtual() && !MD->isPure())
5928 MarkDeclarationReferenced(Loc, MD);
5929 }
5930}
5931