blob: db81e48f1da5536c38e97459d3ef3457449a021b [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
John McCallbf73b352010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
306 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000419
Douglas Gregorb48fe382008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000426 assert(getLangOptions().CPlusPlus && "No class names in C!");
427
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000428 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000429 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000430 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432 } else
433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000435 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000436 return &II == CurDecl->getIdentifier();
437 else
438 return false;
439}
440
Mike Stump1eb44332009-09-09 15:08:12 +0000441/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447 SourceRange SpecifierRange,
448 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450 SourceLocation BaseLoc) {
451 // C++ [class.union]p1:
452 // A union shall not have base classes.
453 if (Class->isUnion()) {
454 Diag(Class->getLocation(), diag::err_base_clause_on_union)
455 << SpecifierRange;
456 return 0;
457 }
458
459 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000461 Class->getTagKind() == RecordDecl::TK_class,
462 Access, BaseType);
463
464 // Base specifiers must be record types.
465 if (!BaseType->isRecordType()) {
466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.union]p1:
471 // A union shall not be used as a base class.
472 if (BaseType->isUnionType()) {
473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474 return 0;
475 }
476
477 // C++ [class.derived]p2:
478 // The class-name in a base-specifier shall not be an incompletely
479 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000480 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000481 PDiag(diag::err_incomplete_base_class)
482 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000483 return 0;
484
Eli Friedman1d954f62009-08-15 21:55:26 +0000485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000487 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000488 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
491 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000492
Sean Huntbbd37c62009-11-21 08:43:09 +0000493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
494 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
497 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000498 return 0;
499 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000500
Eli Friedmand0137332009-12-05 23:03:49 +0000501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000502
503 // Create the base specifier.
504 // FIXME: Allocate via ASTContext?
505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506 Class->getTagKind() == RecordDecl::TK_class,
507 Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511 const CXXRecordDecl *BaseClass,
512 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000513 // A class with a non-empty base class is not empty.
514 // FIXME: Standard ref?
515 if (!BaseClass->isEmpty())
516 Class->setEmpty(false);
517
518 // C++ [class.virtual]p1:
519 // A class that [...] inherits a virtual function is called a polymorphic
520 // class.
521 if (BaseClass->isPolymorphic())
522 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000523
Douglas Gregor2943aed2009-03-03 04:44:36 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is [...] a class with [...] no base classes [...].
526 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000527
528 // C++ [class]p4:
529 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000530 Class->setPOD(false);
531
Anders Carlsson51f94042009-12-03 17:49:57 +0000532 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000533 // C++ [class.ctor]p5:
534 // A constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000536
537 // C++ [class.copy]p6:
538 // A copy constructor is trivial if its class has no virtual base classes.
539 Class->setHasTrivialCopyConstructor(false);
540
541 // C++ [class.copy]p11:
542 // A copy assignment operator is trivial if its class has no virtual
543 // base classes.
544 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000545
546 // C++0x [meta.unary.prop] is_empty:
547 // T is a class type, but not a union type, with ... no virtual base
548 // classes
549 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000550 } else {
551 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000552 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000553 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000554 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000555 Class->setHasTrivialConstructor(false);
556
557 // C++ [class.copy]p6:
558 // A copy constructor is trivial if all the direct base classes of its
559 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000560 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000561 Class->setHasTrivialCopyConstructor(false);
562
563 // C++ [class.copy]p11:
564 // A copy assignment operator is trivial if all the direct base classes
565 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000566 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000567 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000568 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000569
570 // C++ [class.ctor]p3:
571 // A destructor is trivial if all the direct base classes of its class
572 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000573 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000574 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575}
576
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000579/// example:
580/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000581/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000582Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584 bool Virtual, AccessSpecifier Access,
585 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000586 if (!classdecl)
587 return true;
588
Douglas Gregor40808ce2009-03-09 23:48:35 +0000589 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591 if (!Class)
592 return true;
593
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000594 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596 Virtual, Access,
597 BaseType, BaseLoc))
598 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Douglas Gregor2943aed2009-03-03 04:44:36 +0000600 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000601}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000602
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606 unsigned NumBases) {
607 if (NumBases == 0)
608 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609
610 // Used to keep track of which base types we have already seen, so
611 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000612 // that the key is always the unqualified canonical type of the base
613 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000620 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000622 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000623
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000624 if (KnownBaseTypes[NewBaseType]) {
625 // C++ [class.mi]p3:
626 // A class shall not be specified as a direct base class of a
627 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000629 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000630 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000632
633 // Delete the duplicate base class specifier; we're going to
634 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000635 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636
637 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 } else {
639 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640 KnownBaseTypes[NewBaseType] = Bases[idx];
641 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000642 }
643 }
644
645 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000646 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000647
648 // Delete the remaining (good) base class specifiers, since their
649 // data has been copied into the CXXRecordDecl.
650 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000651 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000652
653 return Invalid;
654}
655
656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
657/// class, after checking whether there are any duplicate base
658/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000660 unsigned NumBases) {
661 if (!ClassDecl || !Bases || !NumBases)
662 return;
663
664 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000666 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000667}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669static CXXRecordDecl *GetClassForType(QualType T) {
670 if (const RecordType *RT = T->getAs<RecordType>())
671 return cast<CXXRecordDecl>(RT->getDecl());
672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
673 return ICT->getDecl();
674 else
675 return 0;
676}
677
Douglas Gregora8f32e02009-10-06 17:59:45 +0000678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000683
684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
John McCall3cb0ebd2010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000690 return false;
691
John McCall86ff3082010-02-04 22:26:26 +0000692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000694}
695
696/// \brief Determine whether the type \p Derived is a C++ class that is
697/// derived from the type \p Base.
698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
699 if (!getLangOptions().CPlusPlus)
700 return false;
701
John McCall3cb0ebd2010-03-10 03:28:59 +0000702 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
703 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704 return false;
705
John McCall3cb0ebd2010-03-10 03:28:59 +0000706 CXXRecordDecl *BaseRD = GetClassForType(Base);
707 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000708 return false;
709
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 return DerivedRD->isDerivedFrom(BaseRD, Paths);
711}
712
713/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
714/// conversion (where Derived and Base are class types) is
715/// well-formed, meaning that the conversion is unambiguous (and
716/// that all of the base classes are accessible). Returns true
717/// and emits a diagnostic if the code is ill-formed, returns false
718/// otherwise. Loc is the location where this routine should point to
719/// if there is an error, and Range is the source range to highlight
720/// if there is an error.
721bool
722Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000723 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000724 unsigned AmbigiousBaseConvID,
725 SourceLocation Loc, SourceRange Range,
726 DeclarationName Name) {
727 // First, determine whether the path from Derived to Base is
728 // ambiguous. This is slightly more expensive than checking whether
729 // the Derived to Base conversion exists, because here we need to
730 // explore multiple paths to determine if there is an ambiguity.
731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
732 /*DetectVirtual=*/false);
733 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
734 assert(DerivationOkay &&
735 "Can only be used with a derived-to-base conversion");
736 (void)DerivationOkay;
737
738 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000739 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000740 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000741
Douglas Gregora8f32e02009-10-06 17:59:45 +0000742 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000743 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
744 Base, Derived, Paths.front(),
745 /*force*/ false,
746 /*unprivileged*/ false,
747 ADK)) {
748 case AR_accessible: return false;
749 case AR_inaccessible: return true;
750 case AR_dependent: return false;
751 case AR_delayed: return false;
752 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000753 }
754
755 // We know that the derived-to-base conversion is ambiguous, and
756 // we're going to produce a diagnostic. Perform the derived-to-base
757 // search just one more time to compute all of the possible paths so
758 // that we can print them out. This is more expensive than any of
759 // the previous derived-to-base checks we've done, but at this point
760 // performance isn't as much of an issue.
761 Paths.clear();
762 Paths.setRecordingPaths(true);
763 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
764 assert(StillOkay && "Can only be used with a derived-to-base conversion");
765 (void)StillOkay;
766
767 // Build up a textual representation of the ambiguous paths, e.g.,
768 // D -> B -> A, that will be used to illustrate the ambiguous
769 // conversions in the diagnostic. We only print one of the paths
770 // to each base class subobject.
771 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
772
773 Diag(Loc, AmbigiousBaseConvID)
774 << Derived << Base << PathDisplayStr << Range << Name;
775 return true;
776}
777
778bool
779Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000780 SourceLocation Loc, SourceRange Range,
781 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000782 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000783 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000784 diag::err_ambiguous_derived_to_base_conv,
785 Loc, Range, DeclarationName());
786}
787
788
789/// @brief Builds a string representing ambiguous paths from a
790/// specific derived class to different subobjects of the same base
791/// class.
792///
793/// This function builds a string that can be used in error messages
794/// to show the different paths that one can take through the
795/// inheritance hierarchy to go from the derived class to different
796/// subobjects of a base class. The result looks something like this:
797/// @code
798/// struct D -> struct B -> struct A
799/// struct D -> struct C -> struct A
800/// @endcode
801std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
802 std::string PathDisplayStr;
803 std::set<unsigned> DisplayedPaths;
804 for (CXXBasePaths::paths_iterator Path = Paths.begin();
805 Path != Paths.end(); ++Path) {
806 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
807 // We haven't displayed a path to this particular base
808 // class subobject yet.
809 PathDisplayStr += "\n ";
810 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
811 for (CXXBasePath::const_iterator Element = Path->begin();
812 Element != Path->end(); ++Element)
813 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
814 }
815 }
816
817 return PathDisplayStr;
818}
819
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000820//===----------------------------------------------------------------------===//
821// C++ class member Handling
822//===----------------------------------------------------------------------===//
823
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
825/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
826/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000827/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000828Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000830 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000831 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
832 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000833 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000834 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000835 Expr *BitWidth = static_cast<Expr*>(BW);
836 Expr *Init = static_cast<Expr*>(InitExpr);
837 SourceLocation Loc = D.getIdentifierLoc();
838
Sebastian Redl669d5d72008-11-14 23:42:31 +0000839 bool isFunc = D.isFunctionDeclarator();
840
John McCall67d1a672009-08-06 02:15:43 +0000841 assert(!DS.isFriendSpecified());
842
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000843 // C++ 9.2p6: A member shall not be declared to have automatic storage
844 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
846 // data members and cannot be applied to names declared const or static,
847 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000848 switch (DS.getStorageClassSpec()) {
849 case DeclSpec::SCS_unspecified:
850 case DeclSpec::SCS_typedef:
851 case DeclSpec::SCS_static:
852 // FALL THROUGH.
853 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000854 case DeclSpec::SCS_mutable:
855 if (isFunc) {
856 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000857 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000858 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000859 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Sebastian Redla11f42f2008-11-17 23:24:37 +0000861 // FIXME: It would be nicer if the keyword was ignored only for this
862 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000863 D.getMutableDeclSpec().ClearStorageClassSpecs();
864 } else {
865 QualType T = GetTypeForDeclarator(D, S);
866 diag::kind err = static_cast<diag::kind>(0);
867 if (T->isReferenceType())
868 err = diag::err_mutable_reference;
869 else if (T.isConstQualified())
870 err = diag::err_mutable_const;
871 if (err != 0) {
872 if (DS.getStorageClassSpecLoc().isValid())
873 Diag(DS.getStorageClassSpecLoc(), err);
874 else
875 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000876 // FIXME: It would be nicer if the keyword was ignored only for this
877 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000878 D.getMutableDeclSpec().ClearStorageClassSpecs();
879 }
880 }
881 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000882 default:
883 if (DS.getStorageClassSpecLoc().isValid())
884 Diag(DS.getStorageClassSpecLoc(),
885 diag::err_storageclass_invalid_for_member);
886 else
887 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
888 D.getMutableDeclSpec().ClearStorageClassSpecs();
889 }
890
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000891 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000892 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000893 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000894 // Check also for this case:
895 //
896 // typedef int f();
897 // f a;
898 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000899 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000900 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000901 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000902
Sebastian Redl669d5d72008-11-14 23:42:31 +0000903 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
904 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000905 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906
907 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000908 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000909 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000910 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
911 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000912 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000913 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000914 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000915 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000916 if (!Member) {
917 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000918 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000919 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000920
921 // Non-instance-fields can't have a bitfield.
922 if (BitWidth) {
923 if (Member->isInvalidDecl()) {
924 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000925 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000926 // C++ 9.6p3: A bit-field shall not be a static member.
927 // "static member 'A' cannot be a bit-field"
928 Diag(Loc, diag::err_static_not_bitfield)
929 << Name << BitWidth->getSourceRange();
930 } else if (isa<TypedefDecl>(Member)) {
931 // "typedef member 'x' cannot be a bit-field"
932 Diag(Loc, diag::err_typedef_not_bitfield)
933 << Name << BitWidth->getSourceRange();
934 } else {
935 // A function typedef ("typedef int f(); f a;").
936 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
937 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000938 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000939 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chris Lattner8b963ef2009-03-05 23:01:03 +0000942 DeleteExpr(BitWidth);
943 BitWidth = 0;
944 Member->setInvalidDecl();
945 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000946
947 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Douglas Gregor37b372b2009-08-20 22:52:58 +0000949 // If we have declared a member function template, set the access of the
950 // templated declaration as well.
951 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
952 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000953 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954
Douglas Gregor10bd3682008-11-17 22:58:34 +0000955 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956
Douglas Gregor021c3b32009-03-11 23:00:04 +0000957 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000958 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000959 if (Deleted) // FIXME: Source location is not very good.
960 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000962 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000963 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000964 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000965 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000966 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000967}
968
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000969/// \brief Find the direct and/or virtual base specifiers that
970/// correspond to the given base type, for use in base initialization
971/// within a constructor.
972static bool FindBaseInitializer(Sema &SemaRef,
973 CXXRecordDecl *ClassDecl,
974 QualType BaseType,
975 const CXXBaseSpecifier *&DirectBaseSpec,
976 const CXXBaseSpecifier *&VirtualBaseSpec) {
977 // First, check for a direct base class.
978 DirectBaseSpec = 0;
979 for (CXXRecordDecl::base_class_const_iterator Base
980 = ClassDecl->bases_begin();
981 Base != ClassDecl->bases_end(); ++Base) {
982 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
983 // We found a direct base of this type. That's what we're
984 // initializing.
985 DirectBaseSpec = &*Base;
986 break;
987 }
988 }
989
990 // Check for a virtual base class.
991 // FIXME: We might be able to short-circuit this if we know in advance that
992 // there are no virtual bases.
993 VirtualBaseSpec = 0;
994 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
995 // We haven't found a base yet; search the class hierarchy for a
996 // virtual base class.
997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
998 /*DetectVirtual=*/false);
999 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1000 BaseType, Paths)) {
1001 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1002 Path != Paths.end(); ++Path) {
1003 if (Path->back().Base->isVirtual()) {
1004 VirtualBaseSpec = Path->back().Base;
1005 break;
1006 }
1007 }
1008 }
1009 }
1010
1011 return DirectBaseSpec || VirtualBaseSpec;
1012}
1013
Douglas Gregor7ad83902008-11-05 04:29:56 +00001014/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001015Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001016Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001017 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001018 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001019 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001020 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001021 SourceLocation IdLoc,
1022 SourceLocation LParenLoc,
1023 ExprTy **Args, unsigned NumArgs,
1024 SourceLocation *CommaLocs,
1025 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001026 if (!ConstructorD)
1027 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001029 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001030
1031 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001032 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001033 if (!Constructor) {
1034 // The user wrote a constructor initializer on a function that is
1035 // not a C++ constructor. Ignore the error for now, because we may
1036 // have more member initializers coming; we'll diagnose it just
1037 // once in ActOnMemInitializers.
1038 return true;
1039 }
1040
1041 CXXRecordDecl *ClassDecl = Constructor->getParent();
1042
1043 // C++ [class.base.init]p2:
1044 // Names in a mem-initializer-id are looked up in the scope of the
1045 // constructor’s class and, if not found in that scope, are looked
1046 // up in the scope containing the constructor’s
1047 // definition. [Note: if the constructor’s class contains a member
1048 // with the same name as a direct or virtual base class of the
1049 // class, a mem-initializer-id naming the member or base class and
1050 // composed of a single identifier refers to the class member. A
1051 // mem-initializer-id for the hidden base class may be specified
1052 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001053 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001054 // Look for a member, first.
1055 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001056 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001057 = ClassDecl->lookup(MemberOrBase);
1058 if (Result.first != Result.second)
1059 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001060
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001061 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001062
Eli Friedman59c04372009-07-29 19:44:27 +00001063 if (Member)
1064 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001065 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001066 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001067 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001068 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001069 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001070
1071 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001072 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001073 } else {
1074 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1075 LookupParsedName(R, S, &SS);
1076
1077 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1078 if (!TyD) {
1079 if (R.isAmbiguous()) return true;
1080
Douglas Gregor7a886e12010-01-19 06:46:48 +00001081 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1082 bool NotUnknownSpecialization = false;
1083 DeclContext *DC = computeDeclContext(SS, false);
1084 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1085 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1086
1087 if (!NotUnknownSpecialization) {
1088 // When the scope specifier can refer to a member of an unknown
1089 // specialization, we take it as a type name.
1090 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1091 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001092 if (BaseType.isNull())
1093 return true;
1094
Douglas Gregor7a886e12010-01-19 06:46:48 +00001095 R.clear();
1096 }
1097 }
1098
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001099 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001100 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001101 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1102 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1103 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1104 // We have found a non-static data member with a similar
1105 // name to what was typed; complain and initialize that
1106 // member.
1107 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1108 << MemberOrBase << true << R.getLookupName()
1109 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1110 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001111 Diag(Member->getLocation(), diag::note_previous_decl)
1112 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001113
1114 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1115 LParenLoc, RParenLoc);
1116 }
1117 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1118 const CXXBaseSpecifier *DirectBaseSpec;
1119 const CXXBaseSpecifier *VirtualBaseSpec;
1120 if (FindBaseInitializer(*this, ClassDecl,
1121 Context.getTypeDeclType(Type),
1122 DirectBaseSpec, VirtualBaseSpec)) {
1123 // We have found a direct or virtual base class with a
1124 // similar name to what was typed; complain and initialize
1125 // that base class.
1126 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1127 << MemberOrBase << false << R.getLookupName()
1128 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1129 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001130
1131 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1132 : VirtualBaseSpec;
1133 Diag(BaseSpec->getSourceRange().getBegin(),
1134 diag::note_base_class_specified_here)
1135 << BaseSpec->getType()
1136 << BaseSpec->getSourceRange();
1137
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001138 TyD = Type;
1139 }
1140 }
1141 }
1142
Douglas Gregor7a886e12010-01-19 06:46:48 +00001143 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001144 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1145 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1146 return true;
1147 }
John McCall2b194412009-12-21 10:41:20 +00001148 }
1149
Douglas Gregor7a886e12010-01-19 06:46:48 +00001150 if (BaseType.isNull()) {
1151 BaseType = Context.getTypeDeclType(TyD);
1152 if (SS.isSet()) {
1153 NestedNameSpecifier *Qualifier =
1154 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001155
Douglas Gregor7a886e12010-01-19 06:46:48 +00001156 // FIXME: preserve source range information
1157 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1158 }
John McCall2b194412009-12-21 10:41:20 +00001159 }
1160 }
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCalla93c9342009-12-07 02:54:59 +00001162 if (!TInfo)
1163 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001164
John McCalla93c9342009-12-07 02:54:59 +00001165 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001166 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001167}
1168
John McCallb4190042009-11-04 23:02:40 +00001169/// Checks an initializer expression for use of uninitialized fields, such as
1170/// containing the field that is being initialized. Returns true if there is an
1171/// uninitialized field was used an updates the SourceLocation parameter; false
1172/// otherwise.
1173static bool InitExprContainsUninitializedFields(const Stmt* S,
1174 const FieldDecl* LhsField,
1175 SourceLocation* L) {
1176 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1177 if (ME) {
1178 const NamedDecl* RhsField = ME->getMemberDecl();
1179 if (RhsField == LhsField) {
1180 // Initializing a field with itself. Throw a warning.
1181 // But wait; there are exceptions!
1182 // Exception #1: The field may not belong to this record.
1183 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1184 const Expr* base = ME->getBase();
1185 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1186 // Even though the field matches, it does not belong to this record.
1187 return false;
1188 }
1189 // None of the exceptions triggered; return true to indicate an
1190 // uninitialized field was used.
1191 *L = ME->getMemberLoc();
1192 return true;
1193 }
1194 }
1195 bool found = false;
1196 for (Stmt::const_child_iterator it = S->child_begin();
1197 it != S->child_end() && found == false;
1198 ++it) {
1199 if (isa<CallExpr>(S)) {
1200 // Do not descend into function calls or constructors, as the use
1201 // of an uninitialized field may be valid. One would have to inspect
1202 // the contents of the function/ctor to determine if it is safe or not.
1203 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1204 // may be safe, depending on what the function/ctor does.
1205 continue;
1206 }
1207 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1208 }
1209 return found;
1210}
1211
Eli Friedman59c04372009-07-29 19:44:27 +00001212Sema::MemInitResult
1213Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1214 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001215 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001216 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001217 // Diagnose value-uses of fields to initialize themselves, e.g.
1218 // foo(foo)
1219 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001220 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001221 for (unsigned i = 0; i < NumArgs; ++i) {
1222 SourceLocation L;
1223 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1224 // FIXME: Return true in the case when other fields are used before being
1225 // uninitialized. For example, let this field be the i'th field. When
1226 // initializing the i'th field, throw a warning if any of the >= i'th
1227 // fields are used, as they are not yet initialized.
1228 // Right now we are only handling the case where the i'th field uses
1229 // itself in its initializer.
1230 Diag(L, diag::warn_field_is_uninit);
1231 }
1232 }
1233
Eli Friedman59c04372009-07-29 19:44:27 +00001234 bool HasDependentArg = false;
1235 for (unsigned i = 0; i < NumArgs; i++)
1236 HasDependentArg |= Args[i]->isTypeDependent();
1237
Eli Friedman59c04372009-07-29 19:44:27 +00001238 QualType FieldType = Member->getType();
1239 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1240 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001241 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001242 if (FieldType->isDependentType() || HasDependentArg) {
1243 // Can't check initialization for a member of dependent type or when
1244 // any of the arguments are type-dependent expressions.
1245 OwningExprResult Init
1246 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1247 RParenLoc));
1248
1249 // Erase any temporaries within this evaluation context; we're not
1250 // going to track them in the AST, since we'll be rebuilding the
1251 // ASTs during template instantiation.
1252 ExprTemporaries.erase(
1253 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1254 ExprTemporaries.end());
1255
1256 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1257 LParenLoc,
1258 Init.takeAs<Expr>(),
1259 RParenLoc);
1260
Douglas Gregor7ad83902008-11-05 04:29:56 +00001261 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001262
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001263 if (Member->isInvalidDecl())
1264 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001265
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001266 // Initialize the member.
1267 InitializedEntity MemberEntity =
1268 InitializedEntity::InitializeMember(Member, 0);
1269 InitializationKind Kind =
1270 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1271
1272 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1273
1274 OwningExprResult MemberInit =
1275 InitSeq.Perform(*this, MemberEntity, Kind,
1276 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1277 if (MemberInit.isInvalid())
1278 return true;
1279
1280 // C++0x [class.base.init]p7:
1281 // The initialization of each base and member constitutes a
1282 // full-expression.
1283 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1284 if (MemberInit.isInvalid())
1285 return true;
1286
1287 // If we are in a dependent context, template instantiation will
1288 // perform this type-checking again. Just save the arguments that we
1289 // received in a ParenListExpr.
1290 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1291 // of the information that we have about the member
1292 // initializer. However, deconstructing the ASTs is a dicey process,
1293 // and this approach is far more likely to get the corner cases right.
1294 if (CurContext->isDependentContext()) {
1295 // Bump the reference count of all of the arguments.
1296 for (unsigned I = 0; I != NumArgs; ++I)
1297 Args[I]->Retain();
1298
1299 OwningExprResult Init
1300 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1301 RParenLoc));
1302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1303 LParenLoc,
1304 Init.takeAs<Expr>(),
1305 RParenLoc);
1306 }
1307
Douglas Gregor802ab452009-12-02 22:36:29 +00001308 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001309 LParenLoc,
1310 MemberInit.takeAs<Expr>(),
1311 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001312}
1313
1314Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001315Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001316 Expr **Args, unsigned NumArgs,
1317 SourceLocation LParenLoc, SourceLocation RParenLoc,
1318 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001319 bool HasDependentArg = false;
1320 for (unsigned i = 0; i < NumArgs; i++)
1321 HasDependentArg |= Args[i]->isTypeDependent();
1322
John McCalla93c9342009-12-07 02:54:59 +00001323 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001324 if (BaseType->isDependentType() || HasDependentArg) {
1325 // Can't check initialization for a base of dependent type or when
1326 // any of the arguments are type-dependent expressions.
1327 OwningExprResult BaseInit
1328 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1329 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001330
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001331 // Erase any temporaries within this evaluation context; we're not
1332 // going to track them in the AST, since we'll be rebuilding the
1333 // ASTs during template instantiation.
1334 ExprTemporaries.erase(
1335 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1336 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001338 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1339 LParenLoc,
1340 BaseInit.takeAs<Expr>(),
1341 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001342 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001343
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001344 if (!BaseType->isRecordType())
1345 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1346 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1347
1348 // C++ [class.base.init]p2:
1349 // [...] Unless the mem-initializer-id names a nonstatic data
1350 // member of the constructor’s class or a direct or virtual base
1351 // of that class, the mem-initializer is ill-formed. A
1352 // mem-initializer-list can initialize a base class using any
1353 // name that denotes that base class type.
1354
1355 // Check for direct and virtual base classes.
1356 const CXXBaseSpecifier *DirectBaseSpec = 0;
1357 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1358 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1359 VirtualBaseSpec);
1360
1361 // C++ [base.class.init]p2:
1362 // If a mem-initializer-id is ambiguous because it designates both
1363 // a direct non-virtual base class and an inherited virtual base
1364 // class, the mem-initializer is ill-formed.
1365 if (DirectBaseSpec && VirtualBaseSpec)
1366 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1367 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1368 // C++ [base.class.init]p2:
1369 // Unless the mem-initializer-id names a nonstatic data membeer of the
1370 // constructor's class ot a direst or virtual base of that class, the
1371 // mem-initializer is ill-formed.
1372 if (!DirectBaseSpec && !VirtualBaseSpec)
1373 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1374 << BaseType << ClassDecl->getNameAsCString()
1375 << BaseTInfo->getTypeLoc().getSourceRange();
1376
1377 CXXBaseSpecifier *BaseSpec
1378 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1379 if (!BaseSpec)
1380 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1381
1382 // Initialize the base.
1383 InitializedEntity BaseEntity =
1384 InitializedEntity::InitializeBase(Context, BaseSpec);
1385 InitializationKind Kind =
1386 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1387
1388 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1389
1390 OwningExprResult BaseInit =
1391 InitSeq.Perform(*this, BaseEntity, Kind,
1392 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1393 if (BaseInit.isInvalid())
1394 return true;
1395
1396 // C++0x [class.base.init]p7:
1397 // The initialization of each base and member constitutes a
1398 // full-expression.
1399 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1400 if (BaseInit.isInvalid())
1401 return true;
1402
1403 // If we are in a dependent context, template instantiation will
1404 // perform this type-checking again. Just save the arguments that we
1405 // received in a ParenListExpr.
1406 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1407 // of the information that we have about the base
1408 // initializer. However, deconstructing the ASTs is a dicey process,
1409 // and this approach is far more likely to get the corner cases right.
1410 if (CurContext->isDependentContext()) {
1411 // Bump the reference count of all of the arguments.
1412 for (unsigned I = 0; I != NumArgs; ++I)
1413 Args[I]->Retain();
1414
1415 OwningExprResult Init
1416 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1417 RParenLoc));
1418 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1419 LParenLoc,
1420 Init.takeAs<Expr>(),
1421 RParenLoc);
1422 }
1423
1424 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1425 LParenLoc,
1426 BaseInit.takeAs<Expr>(),
1427 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001428}
1429
Eli Friedman80c30da2009-11-09 19:20:36 +00001430bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001431Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001432 CXXBaseOrMemberInitializer **Initializers,
1433 unsigned NumInitializers,
1434 bool IsImplicitConstructor,
1435 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001436 // We need to build the initializer AST according to order of construction
1437 // and not what user specified in the Initializers list.
1438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1439 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1440 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1441 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001442 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001444 for (unsigned i = 0; i < NumInitializers; i++) {
1445 CXXBaseOrMemberInitializer *Member = Initializers[i];
1446 if (Member->isBaseInitializer()) {
1447 if (Member->getBaseClass()->isDependentType())
1448 HasDependentBaseInit = true;
1449 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1450 } else {
1451 AllBaseFields[Member->getMember()] = Member;
1452 }
1453 }
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001455 if (HasDependentBaseInit) {
1456 // FIXME. This does not preserve the ordering of the initializers.
1457 // Try (with -Wreorder)
1458 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001459 // template<class X> struct B : A<X> {
1460 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001461 // int x1;
1462 // };
1463 // B<int> x;
1464 // On seeing one dependent type, we should essentially exit this routine
1465 // while preserving user-declared initializer list. When this routine is
1466 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001467 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001469 // If we have a dependent base initialization, we can't determine the
1470 // association between initializers and bases; just dump the known
1471 // initializers into the list, and don't try to deal with other bases.
1472 for (unsigned i = 0; i < NumInitializers; i++) {
1473 CXXBaseOrMemberInitializer *Member = Initializers[i];
1474 if (Member->isBaseInitializer())
1475 AllToInit.push_back(Member);
1476 }
1477 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001478 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1479
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001480 // Push virtual bases before others.
1481 for (CXXRecordDecl::base_class_iterator VBase =
1482 ClassDecl->vbases_begin(),
1483 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1484 if (VBase->getType()->isDependentType())
1485 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001486 if (CXXBaseOrMemberInitializer *Value
1487 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001488 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001489 } else if (!AnyErrors) {
1490 InitializedEntity InitEntity
1491 = InitializedEntity::InitializeBase(Context, VBase);
1492 InitializationKind InitKind
1493 = InitializationKind::CreateDefault(Constructor->getLocation());
1494 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1495 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1496 MultiExprArg(*this, 0, 0));
1497 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1498 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001499 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001500 continue;
1501 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001502
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001503 // Don't attach synthesized base initializers in a dependent
1504 // context; they'll be checked again at template instantiation
1505 // time.
1506 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001507 continue;
1508
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001509 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001510 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001511 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001512 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001513 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001514 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001515 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001516 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001517 }
1518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001520 for (CXXRecordDecl::base_class_iterator Base =
1521 ClassDecl->bases_begin(),
1522 E = ClassDecl->bases_end(); Base != E; ++Base) {
1523 // Virtuals are in the virtual base list and already constructed.
1524 if (Base->isVirtual())
1525 continue;
1526 // Skip dependent types.
1527 if (Base->getType()->isDependentType())
1528 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001529 if (CXXBaseOrMemberInitializer *Value
1530 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001531 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001532 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001533 else if (!AnyErrors) {
1534 InitializedEntity InitEntity
1535 = InitializedEntity::InitializeBase(Context, Base);
1536 InitializationKind InitKind
1537 = InitializationKind::CreateDefault(Constructor->getLocation());
1538 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1539 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1540 MultiExprArg(*this, 0, 0));
1541 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1542 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001543 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001544 continue;
1545 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001546
1547 // Don't attach synthesized base initializers in a dependent
1548 // context; they'll be regenerated at template instantiation
1549 // time.
1550 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001551 continue;
1552
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001553 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001554 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001555 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001556 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001557 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001558 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001559 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001560 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001561 }
1562 }
1563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001565 // non-static data members.
1566 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1567 E = ClassDecl->field_end(); Field != E; ++Field) {
1568 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001569 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001570 Field->getType()->getAs<RecordType>()) {
1571 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001572 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001573 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001574 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1575 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1576 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1577 // set to the anonymous union data member used in the initializer
1578 // list.
1579 Value->setMember(*Field);
1580 Value->setAnonUnionMember(*FA);
1581 AllToInit.push_back(Value);
1582 break;
1583 }
1584 }
1585 }
1586 continue;
1587 }
1588 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1589 AllToInit.push_back(Value);
1590 continue;
1591 }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001593 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001594 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001595
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001596 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001597 if (FT->getAs<RecordType>()) {
1598 InitializedEntity InitEntity
1599 = InitializedEntity::InitializeMember(*Field);
1600 InitializationKind InitKind
1601 = InitializationKind::CreateDefault(Constructor->getLocation());
1602
1603 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1604 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1605 MultiExprArg(*this, 0, 0));
1606 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1607 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001608 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001609 continue;
1610 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001611
1612 // Don't attach synthesized member initializers in a dependent
1613 // context; they'll be regenerated a template instantiation
1614 // time.
1615 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001616 continue;
1617
Mike Stump1eb44332009-09-09 15:08:12 +00001618 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001619 new (Context) CXXBaseOrMemberInitializer(Context,
1620 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001621 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001622 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001623 SourceLocation());
1624
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001625 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001626 }
1627 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001628 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001629 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1630 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001631 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001632 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001633 }
1634 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001635 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001636 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1637 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001638 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001639 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001640 }
1641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001643 NumInitializers = AllToInit.size();
1644 if (NumInitializers > 0) {
1645 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1646 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1647 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001649 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001650 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1651 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1652 baseOrMemberInitializers[Idx] = Member;
1653 if (!Member->isBaseInitializer())
1654 continue;
1655 const Type *BaseType = Member->getBaseClass();
1656 const RecordType *RT = BaseType->getAs<RecordType>();
1657 if (!RT)
1658 continue;
1659 CXXRecordDecl *BaseClassDecl =
1660 cast<CXXRecordDecl>(RT->getDecl());
Rafael Espindola961b1672010-03-13 18:12:56 +00001661
1662 // We don't know if a dependent type will have an implicit destructor.
1663 if (BaseClassDecl->isDependentType())
1664 continue;
1665
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001666 if (BaseClassDecl->hasTrivialDestructor())
1667 continue;
1668 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1669 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1670 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001671 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001672
1673 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001674}
1675
Eli Friedman6347f422009-07-21 19:28:10 +00001676static void *GetKeyForTopLevelField(FieldDecl *Field) {
1677 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001678 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001679 if (RT->getDecl()->isAnonymousStructOrUnion())
1680 return static_cast<void *>(RT->getDecl());
1681 }
1682 return static_cast<void *>(Field);
1683}
1684
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001685static void *GetKeyForBase(QualType BaseType) {
1686 if (const RecordType *RT = BaseType->getAs<RecordType>())
1687 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001689 assert(0 && "Unexpected base type!");
1690 return 0;
1691}
1692
Mike Stump1eb44332009-09-09 15:08:12 +00001693static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001694 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001695 // For fields injected into the class via declaration of an anonymous union,
1696 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001697 if (Member->isMemberInitializer()) {
1698 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Eli Friedman49c16da2009-11-09 01:05:47 +00001700 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001701 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001702 // in AnonUnionMember field.
1703 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1704 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001705 if (Field->getDeclContext()->isRecord()) {
1706 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1707 if (RD->isAnonymousStructOrUnion())
1708 return static_cast<void *>(RD);
1709 }
1710 return static_cast<void *>(Field);
1711 }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001713 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001714}
1715
John McCall6aee6212009-11-04 23:13:52 +00001716/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001717void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001718 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001719 MemInitTy **MemInits, unsigned NumMemInits,
1720 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001721 if (!ConstructorDecl)
1722 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001723
1724 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001725
1726 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001727 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Anders Carlssona7b35212009-03-25 02:58:17 +00001729 if (!Constructor) {
1730 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1731 return;
1732 }
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001734 if (!Constructor->isDependentContext()) {
1735 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1736 bool err = false;
1737 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001738 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001739 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1740 void *KeyToMember = GetKeyForMember(Member);
1741 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1742 if (!PrevMember) {
1743 PrevMember = Member;
1744 continue;
1745 }
1746 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001747 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001748 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001749 << Field->getNameAsString()
1750 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001751 else {
1752 Type *BaseClass = Member->getBaseClass();
1753 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001754 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001755 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001756 << QualType(BaseClass, 0)
1757 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001758 }
1759 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1760 << 0;
1761 err = true;
1762 }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001764 if (err)
1765 return;
1766 }
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Eli Friedman49c16da2009-11-09 01:05:47 +00001768 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001769 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001770 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001772 if (Constructor->isDependentContext())
1773 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
1775 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001776 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001777 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001778 Diagnostic::Ignored)
1779 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001781 // Also issue warning if order of ctor-initializer list does not match order
1782 // of 1) base class declarations and 2) order of non-static data members.
1783 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001785 CXXRecordDecl *ClassDecl
1786 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1787 // Push virtual bases before others.
1788 for (CXXRecordDecl::base_class_iterator VBase =
1789 ClassDecl->vbases_begin(),
1790 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001791 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001793 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1794 E = ClassDecl->bases_end(); Base != E; ++Base) {
1795 // Virtuals are alread in the virtual base list and are constructed
1796 // first.
1797 if (Base->isVirtual())
1798 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001799 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 }
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1803 E = ClassDecl->field_end(); Field != E; ++Field)
1804 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001806 int Last = AllBaseOrMembers.size();
1807 int curIndex = 0;
1808 CXXBaseOrMemberInitializer *PrevMember = 0;
1809 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001810 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001811 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1812 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001813
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001814 for (; curIndex < Last; curIndex++)
1815 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1816 break;
1817 if (curIndex == Last) {
1818 assert(PrevMember && "Member not in member list?!");
1819 // Initializer as specified in ctor-initializer list is out of order.
1820 // Issue a warning diagnostic.
1821 if (PrevMember->isBaseInitializer()) {
1822 // Diagnostics is for an initialized base class.
1823 Type *BaseClass = PrevMember->getBaseClass();
1824 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001825 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001826 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001827 } else {
1828 FieldDecl *Field = PrevMember->getMember();
1829 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001830 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001831 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001832 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001833 // Also the note!
1834 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001835 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001836 diag::note_fieldorbase_initialized_here) << 0
1837 << Field->getNameAsString();
1838 else {
1839 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001840 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001841 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001842 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001843 }
1844 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001845 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001846 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001847 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001848 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001849 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001850}
1851
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001852void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001853Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1854 // Ignore dependent destructors.
1855 if (Destructor->isDependentContext())
1856 return;
1857
1858 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Anders Carlsson9f853df2009-11-17 04:44:12 +00001860 // Non-static data members.
1861 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1862 E = ClassDecl->field_end(); I != E; ++I) {
1863 FieldDecl *Field = *I;
1864
1865 QualType FieldType = Context.getBaseElementType(Field->getType());
1866
1867 const RecordType* RT = FieldType->getAs<RecordType>();
1868 if (!RT)
1869 continue;
1870
1871 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1872 if (FieldClassDecl->hasTrivialDestructor())
1873 continue;
1874
1875 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1876 MarkDeclarationReferenced(Destructor->getLocation(),
1877 const_cast<CXXDestructorDecl*>(Dtor));
1878 }
1879
1880 // Bases.
1881 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1882 E = ClassDecl->bases_end(); Base != E; ++Base) {
1883 // Ignore virtual bases.
1884 if (Base->isVirtual())
1885 continue;
1886
1887 // Ignore trivial destructors.
1888 CXXRecordDecl *BaseClassDecl
1889 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1890 if (BaseClassDecl->hasTrivialDestructor())
1891 continue;
1892
1893 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1894 MarkDeclarationReferenced(Destructor->getLocation(),
1895 const_cast<CXXDestructorDecl*>(Dtor));
1896 }
1897
1898 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001899 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1900 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001901 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001902 CXXRecordDecl *BaseClassDecl
1903 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1904 if (BaseClassDecl->hasTrivialDestructor())
1905 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001906
1907 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1908 MarkDeclarationReferenced(Destructor->getLocation(),
1909 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001910 }
1911}
1912
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001913void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001914 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001915 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001917 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001918
1919 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001920 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001921 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001922}
1923
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001924namespace {
1925 /// PureVirtualMethodCollector - traverses a class and its superclasses
1926 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001927 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 ASTContext &Context;
1929
Sebastian Redldfe292d2009-03-22 21:28:55 +00001930 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001931 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001932
1933 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001934 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001936 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001938 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001939 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001940 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001942 MethodList List;
1943 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001945 // Copy the temporary list to methods, and make sure to ignore any
1946 // null entries.
1947 for (size_t i = 0, e = List.size(); i != e; ++i) {
1948 if (List[i])
1949 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001950 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001951 }
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001953 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001955 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1956 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001957 };
Mike Stump1eb44332009-09-09 15:08:12 +00001958
1959 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001960 MethodList& Methods) {
1961 // First, collect the pure virtual methods for the base classes.
1962 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1963 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001964 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001965 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001966 if (BaseDecl && BaseDecl->isAbstract())
1967 Collect(BaseDecl, Methods);
1968 }
1969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001971 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001972 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001974 MethodSetTy OverriddenMethods;
1975 size_t MethodsSize = Methods.size();
1976
Mike Stump1eb44332009-09-09 15:08:12 +00001977 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001978 i != e; ++i) {
1979 // Traverse the record, looking for methods.
1980 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001981 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001982 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001983 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Anders Carlsson27823022009-10-18 19:34:08 +00001985 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001986 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1987 E = MD->end_overridden_methods(); I != E; ++I) {
1988 // Keep track of the overridden methods.
1989 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001990 }
1991 }
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
1994 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001995 // overridden.
1996 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1997 if (OverriddenMethods.count(Methods[i]))
1998 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Anders Carlsson67e4dd22009-03-22 01:52:17 +00002001 }
2002}
Douglas Gregor7ad83902008-11-05 04:29:56 +00002003
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002004
Mike Stump1eb44332009-09-09 15:08:12 +00002005bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002006 unsigned DiagID, AbstractDiagSelID SelID,
2007 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002008 if (SelID == -1)
2009 return RequireNonAbstractType(Loc, T,
2010 PDiag(DiagID), CurrentRD);
2011 else
2012 return RequireNonAbstractType(Loc, T,
2013 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002014}
2015
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002016bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2017 const PartialDiagnostic &PD,
2018 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002019 if (!getLangOptions().CPlusPlus)
2020 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Anders Carlsson11f21a02009-03-23 19:10:31 +00002022 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002023 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002024 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Ted Kremenek6217b802009-07-29 21:53:49 +00002026 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002027 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002029 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002031 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002032 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002033 }
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenek6217b802009-07-29 21:53:49 +00002035 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002036 if (!RT)
2037 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
John McCall86ff3082010-02-04 22:26:26 +00002039 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002040
Anders Carlssone65a3c82009-03-24 17:23:42 +00002041 if (CurrentRD && CurrentRD != RD)
2042 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCall86ff3082010-02-04 22:26:26 +00002044 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002045 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002046 return false;
2047
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002048 if (!RD->isAbstract())
2049 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002051 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002053 // Check if we've already emitted the list of pure virtual functions for this
2054 // class.
2055 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2056 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002058 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
2060 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002061 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2062 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002063
2064 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002065 MD->getDeclName();
2066 }
2067
2068 if (!PureVirtualClassDiagSet)
2069 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2070 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002072 return true;
2073}
2074
Anders Carlsson8211eff2009-03-24 01:19:16 +00002075namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002076 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002077 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2078 Sema &SemaRef;
2079 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Anders Carlssone65a3c82009-03-24 17:23:42 +00002081 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002082 bool Invalid = false;
2083
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002084 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2085 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002086 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002087
Anders Carlsson8211eff2009-03-24 01:19:16 +00002088 return Invalid;
2089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 public:
2092 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2093 : SemaRef(SemaRef), AbstractClass(ac) {
2094 Visit(SemaRef.Context.getTranslationUnitDecl());
2095 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002096
Anders Carlssone65a3c82009-03-24 17:23:42 +00002097 bool VisitFunctionDecl(const FunctionDecl *FD) {
2098 if (FD->isThisDeclarationADefinition()) {
2099 // No need to do the check if we're in a definition, because it requires
2100 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002101 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002102 return VisitDeclContext(FD);
2103 }
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Anders Carlssone65a3c82009-03-24 17:23:42 +00002105 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002106 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002107 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002108 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2109 diag::err_abstract_type_in_decl,
2110 Sema::AbstractReturnType,
2111 AbstractClass);
2112
Mike Stump1eb44332009-09-09 15:08:12 +00002113 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002114 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002115 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002116 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002117 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002118 VD->getOriginalType(),
2119 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002120 Sema::AbstractParamType,
2121 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002122 }
2123
2124 return Invalid;
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Anders Carlssone65a3c82009-03-24 17:23:42 +00002127 bool VisitDecl(const Decl* D) {
2128 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2129 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Anders Carlssone65a3c82009-03-24 17:23:42 +00002131 return false;
2132 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002133 };
2134}
2135
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002136/// \brief Perform semantic checks on a class definition that has been
2137/// completing, introducing implicitly-declared members, checking for
2138/// abstract types, etc.
2139void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2140 if (!Record || Record->isInvalidDecl())
2141 return;
2142
Eli Friedmanff2d8782009-12-16 20:00:27 +00002143 if (!Record->isDependentType())
2144 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002145
Eli Friedmanff2d8782009-12-16 20:00:27 +00002146 if (Record->isInvalidDecl())
2147 return;
2148
John McCall233a6412010-01-28 07:38:46 +00002149 // Set access bits correctly on the directly-declared conversions.
2150 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2151 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2152 Convs->setAccess(I, (*I)->getAccess());
2153
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002154 if (!Record->isAbstract()) {
2155 // Collect all the pure virtual methods and see if this is an abstract
2156 // class after all.
2157 PureVirtualMethodCollector Collector(Context, Record);
2158 if (!Collector.empty())
2159 Record->setAbstract(true);
2160 }
2161
2162 if (Record->isAbstract())
2163 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002164}
2165
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002166void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002167 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002168 SourceLocation LBrac,
2169 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002170 if (!TagDecl)
2171 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Douglas Gregor42af25f2009-05-11 19:58:34 +00002173 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002174
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002175 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002176 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002177 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002178
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002179 CheckCompletedCXXClass(
2180 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002181}
2182
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002183/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2184/// special functions, such as the default constructor, copy
2185/// constructor, or destructor, to the given C++ class (C++
2186/// [special]p1). This routine can only be executed just before the
2187/// definition of the class is complete.
2188void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002189 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002190 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002191
Sebastian Redl465226e2009-05-27 22:11:52 +00002192 // FIXME: Implicit declarations have exception specifications, which are
2193 // the union of the specifications of the implicitly called functions.
2194
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002195 if (!ClassDecl->hasUserDeclaredConstructor()) {
2196 // C++ [class.ctor]p5:
2197 // A default constructor for a class X is a constructor of class X
2198 // that can be called without an argument. If there is no
2199 // user-declared constructor for class X, a default constructor is
2200 // implicitly declared. An implicitly-declared default constructor
2201 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002202 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002203 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002204 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002205 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002206 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002207 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002208 0, 0, false, 0,
2209 /*FIXME*/false, false,
2210 0, 0, false,
2211 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002212 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002213 /*isExplicit=*/false,
2214 /*isInline=*/true,
2215 /*isImplicitlyDeclared=*/true);
2216 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002217 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002218 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002219 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002220 }
2221
2222 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2223 // C++ [class.copy]p4:
2224 // If the class definition does not explicitly declare a copy
2225 // constructor, one is declared implicitly.
2226
2227 // C++ [class.copy]p5:
2228 // The implicitly-declared copy constructor for a class X will
2229 // have the form
2230 //
2231 // X::X(const X&)
2232 //
2233 // if
2234 bool HasConstCopyConstructor = true;
2235
2236 // -- each direct or virtual base class B of X has a copy
2237 // constructor whose first parameter is of type const B& or
2238 // const volatile B&, and
2239 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2240 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2241 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002243 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002244 = BaseClassDecl->hasConstCopyConstructor(Context);
2245 }
2246
2247 // -- for all the nonstatic data members of X that are of a
2248 // class type M (or array thereof), each such class type
2249 // has a copy constructor whose first parameter is of type
2250 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002251 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2252 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002253 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002254 QualType FieldType = (*Field)->getType();
2255 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2256 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002257 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002258 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002259 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002260 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002261 = FieldClassDecl->hasConstCopyConstructor(Context);
2262 }
2263 }
2264
Sebastian Redl64b45f72009-01-05 20:52:13 +00002265 // Otherwise, the implicitly declared copy constructor will have
2266 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002267 //
2268 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002269 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002270 if (HasConstCopyConstructor)
2271 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002272 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002273
Sebastian Redl64b45f72009-01-05 20:52:13 +00002274 // An implicitly-declared copy constructor is an inline public
2275 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002276 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002277 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002278 CXXConstructorDecl *CopyConstructor
2279 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002280 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002281 Context.getFunctionType(Context.VoidTy,
2282 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002283 false, 0,
2284 /*FIXME:*/false,
2285 false, 0, 0, false,
2286 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002287 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002288 /*isExplicit=*/false,
2289 /*isInline=*/true,
2290 /*isImplicitlyDeclared=*/true);
2291 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002292 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002293 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002294
2295 // Add the parameter to the constructor.
2296 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2297 ClassDecl->getLocation(),
2298 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002299 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002300 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002301 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002302 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002303 }
2304
Sebastian Redl64b45f72009-01-05 20:52:13 +00002305 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2306 // Note: The following rules are largely analoguous to the copy
2307 // constructor rules. Note that virtual bases are not taken into account
2308 // for determining the argument type of the operator. Note also that
2309 // operators taking an object instead of a reference are allowed.
2310 //
2311 // C++ [class.copy]p10:
2312 // If the class definition does not explicitly declare a copy
2313 // assignment operator, one is declared implicitly.
2314 // The implicitly-defined copy assignment operator for a class X
2315 // will have the form
2316 //
2317 // X& X::operator=(const X&)
2318 //
2319 // if
2320 bool HasConstCopyAssignment = true;
2321
2322 // -- each direct base class B of X has a copy assignment operator
2323 // whose parameter is of type const B&, const volatile B& or B,
2324 // and
2325 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2326 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002327 assert(!Base->getType()->isDependentType() &&
2328 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002329 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002330 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002331 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002332 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002333 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002334 }
2335
2336 // -- for all the nonstatic data members of X that are of a class
2337 // type M (or array thereof), each such class type has a copy
2338 // assignment operator whose parameter is of type const M&,
2339 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002340 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2341 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002342 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002343 QualType FieldType = (*Field)->getType();
2344 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2345 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002346 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002347 const CXXRecordDecl *FieldClassDecl
2348 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002349 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002350 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002351 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002352 }
2353 }
2354
2355 // Otherwise, the implicitly declared copy assignment operator will
2356 // have the form
2357 //
2358 // X& X::operator=(X&)
2359 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002360 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002361 if (HasConstCopyAssignment)
2362 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002363 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002364
2365 // An implicitly-declared copy assignment operator is an inline public
2366 // member of its class.
2367 DeclarationName Name =
2368 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2369 CXXMethodDecl *CopyAssignment =
2370 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2371 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002372 false, 0,
2373 /*FIXME:*/false,
2374 false, 0, 0, false,
2375 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002376 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002377 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002378 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002379 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002380 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002381
2382 // Add the parameter to the operator.
2383 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2384 ClassDecl->getLocation(),
2385 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002386 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002387 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002388 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002389
2390 // Don't call addedAssignmentOperator. There is no way to distinguish an
2391 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002392 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002393 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002394 }
2395
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002396 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002397 // C++ [class.dtor]p2:
2398 // If a class has no user-declared destructor, a destructor is
2399 // declared implicitly. An implicitly-declared destructor is an
2400 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002401 QualType Ty = Context.getFunctionType(Context.VoidTy,
2402 0, 0, false, 0,
2403 /*FIXME:*/false,
2404 false, 0, 0, false,
2405 CC_Default);
2406
Mike Stump1eb44332009-09-09 15:08:12 +00002407 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002408 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002409 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002410 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002411 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002412 /*isInline=*/true,
2413 /*isImplicitlyDeclared=*/true);
2414 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002415 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002416 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002417 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002418
2419 // This could be uniqued if it ever proves significant.
2420 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002421
2422 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002423 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002424}
2425
Douglas Gregor6569d682009-05-27 23:11:45 +00002426void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002427 Decl *D = TemplateD.getAs<Decl>();
2428 if (!D)
2429 return;
2430
2431 TemplateParameterList *Params = 0;
2432 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2433 Params = Template->getTemplateParameters();
2434 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2435 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2436 Params = PartialSpec->getTemplateParameters();
2437 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002438 return;
2439
Douglas Gregor6569d682009-05-27 23:11:45 +00002440 for (TemplateParameterList::iterator Param = Params->begin(),
2441 ParamEnd = Params->end();
2442 Param != ParamEnd; ++Param) {
2443 NamedDecl *Named = cast<NamedDecl>(*Param);
2444 if (Named->getDeclName()) {
2445 S->AddDecl(DeclPtrTy::make(Named));
2446 IdResolver.AddDecl(Named);
2447 }
2448 }
2449}
2450
John McCall7a1dc562009-12-19 10:49:29 +00002451void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2452 if (!RecordD) return;
2453 AdjustDeclIfTemplate(RecordD);
2454 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2455 PushDeclContext(S, Record);
2456}
2457
2458void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2459 if (!RecordD) return;
2460 PopDeclContext();
2461}
2462
Douglas Gregor72b505b2008-12-16 21:30:33 +00002463/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2464/// parsing a top-level (non-nested) C++ class, and we are now
2465/// parsing those parts of the given Method declaration that could
2466/// not be parsed earlier (C++ [class.mem]p2), such as default
2467/// arguments. This action should enter the scope of the given
2468/// Method declaration as if we had just parsed the qualified method
2469/// name. However, it should not bring the parameters into scope;
2470/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002471void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002472}
2473
2474/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2475/// C++ method declaration. We're (re-)introducing the given
2476/// function parameter into scope for use in parsing later parts of
2477/// the method declaration. For example, we could see an
2478/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002479void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002480 if (!ParamD)
2481 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Chris Lattnerb28317a2009-03-28 19:18:32 +00002483 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002484
2485 // If this parameter has an unparsed default argument, clear it out
2486 // to make way for the parsed default argument.
2487 if (Param->hasUnparsedDefaultArg())
2488 Param->setDefaultArg(0);
2489
Chris Lattnerb28317a2009-03-28 19:18:32 +00002490 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002491 if (Param->getDeclName())
2492 IdResolver.AddDecl(Param);
2493}
2494
2495/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2496/// processing the delayed method declaration for Method. The method
2497/// declaration is now considered finished. There may be a separate
2498/// ActOnStartOfFunctionDef action later (not necessarily
2499/// immediately!) for this method, if it was also defined inside the
2500/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002501void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002502 if (!MethodD)
2503 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002505 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002506
Chris Lattnerb28317a2009-03-28 19:18:32 +00002507 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002508
2509 // Now that we have our default arguments, check the constructor
2510 // again. It could produce additional diagnostics or affect whether
2511 // the class has implicitly-declared destructors, among other
2512 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002513 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2514 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002515
2516 // Check the default arguments, which we may have added.
2517 if (!Method->isInvalidDecl())
2518 CheckCXXDefaultArguments(Method);
2519}
2520
Douglas Gregor42a552f2008-11-05 20:51:48 +00002521/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002522/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002523/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002524/// emit diagnostics and set the invalid bit to true. In any case, the type
2525/// will be updated to reflect a well-formed type for the constructor and
2526/// returned.
2527QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2528 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002529 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002530
2531 // C++ [class.ctor]p3:
2532 // A constructor shall not be virtual (10.3) or static (9.4). A
2533 // constructor can be invoked for a const, volatile or const
2534 // volatile object. A constructor shall not be declared const,
2535 // volatile, or const volatile (9.3.2).
2536 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002537 if (!D.isInvalidType())
2538 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2539 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2540 << SourceRange(D.getIdentifierLoc());
2541 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002542 }
2543 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002544 if (!D.isInvalidType())
2545 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2546 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2547 << SourceRange(D.getIdentifierLoc());
2548 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002549 SC = FunctionDecl::None;
2550 }
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Chris Lattner65401802009-04-25 08:28:21 +00002552 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2553 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002554 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002555 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2556 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002557 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002558 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2559 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002560 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002561 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2562 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002563 }
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Douglas Gregor42a552f2008-11-05 20:51:48 +00002565 // Rebuild the function type "R" without any type qualifiers (in
2566 // case any of the errors above fired) and with "void" as the
2567 // return type, since constructors don't have return types. We
2568 // *always* have to do this, because GetTypeForDeclarator will
2569 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002570 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002571 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2572 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002573 Proto->isVariadic(), 0,
2574 Proto->hasExceptionSpec(),
2575 Proto->hasAnyExceptionSpec(),
2576 Proto->getNumExceptions(),
2577 Proto->exception_begin(),
2578 Proto->getNoReturnAttr(),
2579 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002580}
2581
Douglas Gregor72b505b2008-12-16 21:30:33 +00002582/// CheckConstructor - Checks a fully-formed constructor for
2583/// well-formedness, issuing any diagnostics required. Returns true if
2584/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002585void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002586 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002587 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2588 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002589 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002590
2591 // C++ [class.copy]p3:
2592 // A declaration of a constructor for a class X is ill-formed if
2593 // its first parameter is of type (optionally cv-qualified) X and
2594 // either there are no other parameters or else all other
2595 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002596 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002597 ((Constructor->getNumParams() == 1) ||
2598 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002599 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2600 Constructor->getTemplateSpecializationKind()
2601 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002602 QualType ParamType = Constructor->getParamDecl(0)->getType();
2603 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2604 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002605 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2606 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002607 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002608
2609 // FIXME: Rather that making the constructor invalid, we should endeavor
2610 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002611 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002612 }
2613 }
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Douglas Gregor72b505b2008-12-16 21:30:33 +00002615 // Notify the class that we've added a constructor.
2616 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002617}
2618
Anders Carlsson37909802009-11-30 21:24:50 +00002619/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2620/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002621bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002622 CXXRecordDecl *RD = Destructor->getParent();
2623
2624 if (Destructor->isVirtual()) {
2625 SourceLocation Loc;
2626
2627 if (!Destructor->isImplicit())
2628 Loc = Destructor->getLocation();
2629 else
2630 Loc = RD->getLocation();
2631
2632 // If we have a virtual destructor, look up the deallocation function
2633 FunctionDecl *OperatorDelete = 0;
2634 DeclarationName Name =
2635 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002636 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002637 return true;
2638
2639 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002640 }
Anders Carlsson37909802009-11-30 21:24:50 +00002641
2642 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002643}
2644
Mike Stump1eb44332009-09-09 15:08:12 +00002645static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002646FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2647 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2648 FTI.ArgInfo[0].Param &&
2649 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2650}
2651
Douglas Gregor42a552f2008-11-05 20:51:48 +00002652/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2653/// the well-formednes of the destructor declarator @p D with type @p
2654/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002655/// emit diagnostics and set the declarator to invalid. Even if this happens,
2656/// will be updated to reflect a well-formed type for the destructor and
2657/// returned.
2658QualType Sema::CheckDestructorDeclarator(Declarator &D,
2659 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002660 // C++ [class.dtor]p1:
2661 // [...] A typedef-name that names a class is a class-name
2662 // (7.1.3); however, a typedef-name that names a class shall not
2663 // be used as the identifier in the declarator for a destructor
2664 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002665 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002666 if (isa<TypedefType>(DeclaratorType)) {
2667 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002668 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002669 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002670 }
2671
2672 // C++ [class.dtor]p2:
2673 // A destructor is used to destroy objects of its class type. A
2674 // destructor takes no parameters, and no return type can be
2675 // specified for it (not even void). The address of a destructor
2676 // shall not be taken. A destructor shall not be static. A
2677 // destructor can be invoked for a const, volatile or const
2678 // volatile object. A destructor shall not be declared const,
2679 // volatile or const volatile (9.3.2).
2680 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002681 if (!D.isInvalidType())
2682 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2683 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2684 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002685 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002686 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002687 }
Chris Lattner65401802009-04-25 08:28:21 +00002688 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002689 // Destructors don't have return types, but the parser will
2690 // happily parse something like:
2691 //
2692 // class X {
2693 // float ~X();
2694 // };
2695 //
2696 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002697 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2698 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2699 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002700 }
Mike Stump1eb44332009-09-09 15:08:12 +00002701
Chris Lattner65401802009-04-25 08:28:21 +00002702 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2703 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002704 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002705 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2706 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002707 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002708 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2709 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002710 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002711 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2712 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002713 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002714 }
2715
2716 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002717 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002718 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2719
2720 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002721 FTI.freeArgs();
2722 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002723 }
2724
Mike Stump1eb44332009-09-09 15:08:12 +00002725 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002726 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002727 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002728 D.setInvalidType();
2729 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002730
2731 // Rebuild the function type "R" without any type qualifiers or
2732 // parameters (in case any of the errors above fired) and with
2733 // "void" as the return type, since destructors don't have return
2734 // types. We *always* have to do this, because GetTypeForDeclarator
2735 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002736 // FIXME: Exceptions!
2737 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2738 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002739}
2740
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002741/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2742/// well-formednes of the conversion function declarator @p D with
2743/// type @p R. If there are any errors in the declarator, this routine
2744/// will emit diagnostics and return true. Otherwise, it will return
2745/// false. Either way, the type @p R will be updated to reflect a
2746/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002747void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002748 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002749 // C++ [class.conv.fct]p1:
2750 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002751 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002752 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002753 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002754 if (!D.isInvalidType())
2755 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2756 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2757 << SourceRange(D.getIdentifierLoc());
2758 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002759 SC = FunctionDecl::None;
2760 }
Chris Lattner6e475012009-04-25 08:35:12 +00002761 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002762 // Conversion functions don't have return types, but the parser will
2763 // happily parse something like:
2764 //
2765 // class X {
2766 // float operator bool();
2767 // };
2768 //
2769 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002770 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2771 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2772 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002773 }
2774
2775 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002776 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002777 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2778
2779 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002780 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002781 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002782 }
2783
Mike Stump1eb44332009-09-09 15:08:12 +00002784 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002785 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002786 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002787 D.setInvalidType();
2788 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002789
2790 // C++ [class.conv.fct]p4:
2791 // The conversion-type-id shall not represent a function type nor
2792 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002793 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002794 if (ConvType->isArrayType()) {
2795 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2796 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002797 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002798 } else if (ConvType->isFunctionType()) {
2799 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2800 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002801 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002802 }
2803
2804 // Rebuild the function type "R" without any parameters (in case any
2805 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002806 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002807 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002808 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002809 Proto->getTypeQuals(),
2810 Proto->hasExceptionSpec(),
2811 Proto->hasAnyExceptionSpec(),
2812 Proto->getNumExceptions(),
2813 Proto->exception_begin(),
2814 Proto->getNoReturnAttr(),
2815 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002816
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002817 // C++0x explicit conversion operators.
2818 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002819 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002820 diag::warn_explicit_conversion_functions)
2821 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002822}
2823
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002824/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2825/// the declaration of the given C++ conversion function. This routine
2826/// is responsible for recording the conversion function in the C++
2827/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002828Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002829 assert(Conversion && "Expected to receive a conversion function declaration");
2830
Douglas Gregor9d350972008-12-12 08:25:50 +00002831 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002832
2833 // Make sure we aren't redeclaring the conversion function.
2834 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002835
2836 // C++ [class.conv.fct]p1:
2837 // [...] A conversion function is never used to convert a
2838 // (possibly cv-qualified) object to the (possibly cv-qualified)
2839 // same object type (or a reference to it), to a (possibly
2840 // cv-qualified) base class of that type (or a reference to it),
2841 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002842 // FIXME: Suppress this warning if the conversion function ends up being a
2843 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002844 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002845 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002846 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002847 ConvType = ConvTypeRef->getPointeeType();
2848 if (ConvType->isRecordType()) {
2849 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2850 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002851 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002852 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002853 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002854 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002855 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002856 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002857 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002858 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002859 }
2860
Douglas Gregor48026d22010-01-11 18:40:55 +00002861 if (Conversion->getPrimaryTemplate()) {
2862 // ignore specializations
2863 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002864 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002865 = Conversion->getDescribedFunctionTemplate()) {
2866 if (ClassDecl->replaceConversion(
2867 ConversionTemplate->getPreviousDeclaration(),
2868 ConversionTemplate))
2869 return DeclPtrTy::make(ConversionTemplate);
2870 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2871 Conversion))
John McCallba135432009-11-21 08:51:07 +00002872 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002873 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002874 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002875 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002876 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002877 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002878 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002879
Chris Lattnerb28317a2009-03-28 19:18:32 +00002880 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002881}
2882
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002883//===----------------------------------------------------------------------===//
2884// Namespace Handling
2885//===----------------------------------------------------------------------===//
2886
2887/// ActOnStartNamespaceDef - This is called at the start of a namespace
2888/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002889Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2890 SourceLocation IdentLoc,
2891 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002892 SourceLocation LBrace,
2893 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002894 NamespaceDecl *Namespc =
2895 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2896 Namespc->setLBracLoc(LBrace);
2897
2898 Scope *DeclRegionScope = NamespcScope->getParent();
2899
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002900 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2901
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002902 if (II) {
2903 // C++ [namespace.def]p2:
2904 // The identifier in an original-namespace-definition shall not have been
2905 // previously defined in the declarative region in which the
2906 // original-namespace-definition appears. The identifier in an
2907 // original-namespace-definition is the name of the namespace. Subsequently
2908 // in that declarative region, it is treated as an original-namespace-name.
2909
John McCallf36e02d2009-10-09 21:13:30 +00002910 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002911 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002912 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Douglas Gregor44b43212008-12-11 16:49:14 +00002914 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2915 // This is an extended namespace definition.
2916 // Attach this namespace decl to the chain of extended namespace
2917 // definitions.
2918 OrigNS->setNextNamespace(Namespc);
2919 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002920
Mike Stump1eb44332009-09-09 15:08:12 +00002921 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002922 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002923 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002924 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002925 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002926 } else if (PrevDecl) {
2927 // This is an invalid name redefinition.
2928 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2929 << Namespc->getDeclName();
2930 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2931 Namespc->setInvalidDecl();
2932 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002933 } else if (II->isStr("std") &&
2934 CurContext->getLookupContext()->isTranslationUnit()) {
2935 // This is the first "real" definition of the namespace "std", so update
2936 // our cache of the "std" namespace to point at this definition.
2937 if (StdNamespace) {
2938 // We had already defined a dummy namespace "std". Link this new
2939 // namespace definition to the dummy namespace "std".
2940 StdNamespace->setNextNamespace(Namespc);
2941 StdNamespace->setLocation(IdentLoc);
2942 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2943 }
2944
2945 // Make our StdNamespace cache point at the first real definition of the
2946 // "std" namespace.
2947 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002948 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002949
2950 PushOnScopeChains(Namespc, DeclRegionScope);
2951 } else {
John McCall9aeed322009-10-01 00:25:31 +00002952 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002953 assert(Namespc->isAnonymousNamespace());
2954 CurContext->addDecl(Namespc);
2955
2956 // Link the anonymous namespace into its parent.
2957 NamespaceDecl *PrevDecl;
2958 DeclContext *Parent = CurContext->getLookupContext();
2959 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2960 PrevDecl = TU->getAnonymousNamespace();
2961 TU->setAnonymousNamespace(Namespc);
2962 } else {
2963 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2964 PrevDecl = ND->getAnonymousNamespace();
2965 ND->setAnonymousNamespace(Namespc);
2966 }
2967
2968 // Link the anonymous namespace with its previous declaration.
2969 if (PrevDecl) {
2970 assert(PrevDecl->isAnonymousNamespace());
2971 assert(!PrevDecl->getNextNamespace());
2972 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2973 PrevDecl->setNextNamespace(Namespc);
2974 }
John McCall9aeed322009-10-01 00:25:31 +00002975
2976 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2977 // behaves as if it were replaced by
2978 // namespace unique { /* empty body */ }
2979 // using namespace unique;
2980 // namespace unique { namespace-body }
2981 // where all occurrences of 'unique' in a translation unit are
2982 // replaced by the same identifier and this identifier differs
2983 // from all other identifiers in the entire program.
2984
2985 // We just create the namespace with an empty name and then add an
2986 // implicit using declaration, just like the standard suggests.
2987 //
2988 // CodeGen enforces the "universally unique" aspect by giving all
2989 // declarations semantically contained within an anonymous
2990 // namespace internal linkage.
2991
John McCall5fdd7642009-12-16 02:06:49 +00002992 if (!PrevDecl) {
2993 UsingDirectiveDecl* UD
2994 = UsingDirectiveDecl::Create(Context, CurContext,
2995 /* 'using' */ LBrace,
2996 /* 'namespace' */ SourceLocation(),
2997 /* qualifier */ SourceRange(),
2998 /* NNS */ NULL,
2999 /* identifier */ SourceLocation(),
3000 Namespc,
3001 /* Ancestor */ CurContext);
3002 UD->setImplicit();
3003 CurContext->addDecl(UD);
3004 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003005 }
3006
3007 // Although we could have an invalid decl (i.e. the namespace name is a
3008 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003009 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3010 // for the namespace has the declarations that showed up in that particular
3011 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003012 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003013 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003014}
3015
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003016/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3017/// is a namespace alias, returns the namespace it points to.
3018static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3019 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3020 return AD->getNamespace();
3021 return dyn_cast_or_null<NamespaceDecl>(D);
3022}
3023
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003024/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3025/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003026void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3027 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003028 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3029 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3030 Namespc->setRBracLoc(RBrace);
3031 PopDeclContext();
3032}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003033
Chris Lattnerb28317a2009-03-28 19:18:32 +00003034Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3035 SourceLocation UsingLoc,
3036 SourceLocation NamespcLoc,
3037 const CXXScopeSpec &SS,
3038 SourceLocation IdentLoc,
3039 IdentifierInfo *NamespcName,
3040 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003041 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3042 assert(NamespcName && "Invalid NamespcName.");
3043 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003044 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003045
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003046 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003047
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003048 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003049 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3050 LookupParsedName(R, S, &SS);
3051 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003052 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003053
John McCallf36e02d2009-10-09 21:13:30 +00003054 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003055 NamedDecl *Named = R.getFoundDecl();
3056 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3057 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003058 // C++ [namespace.udir]p1:
3059 // A using-directive specifies that the names in the nominated
3060 // namespace can be used in the scope in which the
3061 // using-directive appears after the using-directive. During
3062 // unqualified name lookup (3.4.1), the names appear as if they
3063 // were declared in the nearest enclosing namespace which
3064 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003065 // namespace. [Note: in this context, "contains" means "contains
3066 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003067
3068 // Find enclosing context containing both using-directive and
3069 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003070 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003071 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3072 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3073 CommonAncestor = CommonAncestor->getParent();
3074
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003075 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003076 SS.getRange(),
3077 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003078 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003079 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003080 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003081 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003082 }
3083
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003084 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003085 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003086 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003087}
3088
3089void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3090 // If scope has associated entity, then using directive is at namespace
3091 // or translation unit scope. We add UsingDirectiveDecls, into
3092 // it's lookup structure.
3093 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003094 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003095 else
3096 // Otherwise it is block-sope. using-directives will affect lookup
3097 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003098 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003099}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003100
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003101
3102Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003103 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003104 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003105 SourceLocation UsingLoc,
3106 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003107 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003108 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003109 bool IsTypeName,
3110 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003111 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Douglas Gregor12c118a2009-11-04 16:30:06 +00003113 switch (Name.getKind()) {
3114 case UnqualifiedId::IK_Identifier:
3115 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003116 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003117 case UnqualifiedId::IK_ConversionFunctionId:
3118 break;
3119
3120 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003121 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003122 // C++0x inherited constructors.
3123 if (getLangOptions().CPlusPlus0x) break;
3124
Douglas Gregor12c118a2009-11-04 16:30:06 +00003125 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3126 << SS.getRange();
3127 return DeclPtrTy();
3128
3129 case UnqualifiedId::IK_DestructorName:
3130 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3131 << SS.getRange();
3132 return DeclPtrTy();
3133
3134 case UnqualifiedId::IK_TemplateId:
3135 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3136 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3137 return DeclPtrTy();
3138 }
3139
3140 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003141 if (!TargetName)
3142 return DeclPtrTy();
3143
John McCall60fa3cf2009-12-11 02:10:03 +00003144 // Warn about using declarations.
3145 // TODO: store that the declaration was written without 'using' and
3146 // talk about access decls instead of using decls in the
3147 // diagnostics.
3148 if (!HasUsingKeyword) {
3149 UsingLoc = Name.getSourceRange().getBegin();
3150
3151 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3152 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3153 "using ");
3154 }
3155
John McCall9488ea12009-11-17 05:59:44 +00003156 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003157 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003158 TargetName, AttrList,
3159 /* IsInstantiation */ false,
3160 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003161 if (UD)
3162 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Anders Carlssonc72160b2009-08-28 05:40:36 +00003164 return DeclPtrTy::make(UD);
3165}
3166
John McCall9f54ad42009-12-10 09:41:52 +00003167/// Determines whether to create a using shadow decl for a particular
3168/// decl, given the set of decls existing prior to this using lookup.
3169bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3170 const LookupResult &Previous) {
3171 // Diagnose finding a decl which is not from a base class of the
3172 // current class. We do this now because there are cases where this
3173 // function will silently decide not to build a shadow decl, which
3174 // will pre-empt further diagnostics.
3175 //
3176 // We don't need to do this in C++0x because we do the check once on
3177 // the qualifier.
3178 //
3179 // FIXME: diagnose the following if we care enough:
3180 // struct A { int foo; };
3181 // struct B : A { using A::foo; };
3182 // template <class T> struct C : A {};
3183 // template <class T> struct D : C<T> { using B::foo; } // <---
3184 // This is invalid (during instantiation) in C++03 because B::foo
3185 // resolves to the using decl in B, which is not a base class of D<T>.
3186 // We can't diagnose it immediately because C<T> is an unknown
3187 // specialization. The UsingShadowDecl in D<T> then points directly
3188 // to A::foo, which will look well-formed when we instantiate.
3189 // The right solution is to not collapse the shadow-decl chain.
3190 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3191 DeclContext *OrigDC = Orig->getDeclContext();
3192
3193 // Handle enums and anonymous structs.
3194 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3195 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3196 while (OrigRec->isAnonymousStructOrUnion())
3197 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3198
3199 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3200 if (OrigDC == CurContext) {
3201 Diag(Using->getLocation(),
3202 diag::err_using_decl_nested_name_specifier_is_current_class)
3203 << Using->getNestedNameRange();
3204 Diag(Orig->getLocation(), diag::note_using_decl_target);
3205 return true;
3206 }
3207
3208 Diag(Using->getNestedNameRange().getBegin(),
3209 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3210 << Using->getTargetNestedNameDecl()
3211 << cast<CXXRecordDecl>(CurContext)
3212 << Using->getNestedNameRange();
3213 Diag(Orig->getLocation(), diag::note_using_decl_target);
3214 return true;
3215 }
3216 }
3217
3218 if (Previous.empty()) return false;
3219
3220 NamedDecl *Target = Orig;
3221 if (isa<UsingShadowDecl>(Target))
3222 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3223
John McCalld7533ec2009-12-11 02:33:26 +00003224 // If the target happens to be one of the previous declarations, we
3225 // don't have a conflict.
3226 //
3227 // FIXME: but we might be increasing its access, in which case we
3228 // should redeclare it.
3229 NamedDecl *NonTag = 0, *Tag = 0;
3230 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3231 I != E; ++I) {
3232 NamedDecl *D = (*I)->getUnderlyingDecl();
3233 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3234 return false;
3235
3236 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3237 }
3238
John McCall9f54ad42009-12-10 09:41:52 +00003239 if (Target->isFunctionOrFunctionTemplate()) {
3240 FunctionDecl *FD;
3241 if (isa<FunctionTemplateDecl>(Target))
3242 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3243 else
3244 FD = cast<FunctionDecl>(Target);
3245
3246 NamedDecl *OldDecl = 0;
3247 switch (CheckOverload(FD, Previous, OldDecl)) {
3248 case Ovl_Overload:
3249 return false;
3250
3251 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003252 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003253 break;
3254
3255 // We found a decl with the exact signature.
3256 case Ovl_Match:
3257 if (isa<UsingShadowDecl>(OldDecl)) {
3258 // Silently ignore the possible conflict.
3259 return false;
3260 }
3261
3262 // If we're in a record, we want to hide the target, so we
3263 // return true (without a diagnostic) to tell the caller not to
3264 // build a shadow decl.
3265 if (CurContext->isRecord())
3266 return true;
3267
3268 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003269 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003270 break;
3271 }
3272
3273 Diag(Target->getLocation(), diag::note_using_decl_target);
3274 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3275 return true;
3276 }
3277
3278 // Target is not a function.
3279
John McCall9f54ad42009-12-10 09:41:52 +00003280 if (isa<TagDecl>(Target)) {
3281 // No conflict between a tag and a non-tag.
3282 if (!Tag) return false;
3283
John McCall41ce66f2009-12-10 19:51:03 +00003284 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003285 Diag(Target->getLocation(), diag::note_using_decl_target);
3286 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3287 return true;
3288 }
3289
3290 // No conflict between a tag and a non-tag.
3291 if (!NonTag) return false;
3292
John McCall41ce66f2009-12-10 19:51:03 +00003293 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003294 Diag(Target->getLocation(), diag::note_using_decl_target);
3295 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3296 return true;
3297}
3298
John McCall9488ea12009-11-17 05:59:44 +00003299/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003300UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003301 UsingDecl *UD,
3302 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003303
3304 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003305 NamedDecl *Target = Orig;
3306 if (isa<UsingShadowDecl>(Target)) {
3307 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3308 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003309 }
3310
3311 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003312 = UsingShadowDecl::Create(Context, CurContext,
3313 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003314 UD->addShadowDecl(Shadow);
3315
3316 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003317 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003318 else
John McCall604e7f12009-12-08 07:46:18 +00003319 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003320 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003321
John McCall604e7f12009-12-08 07:46:18 +00003322 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3323 Shadow->setInvalidDecl();
3324
John McCall9f54ad42009-12-10 09:41:52 +00003325 return Shadow;
3326}
John McCall604e7f12009-12-08 07:46:18 +00003327
John McCall9f54ad42009-12-10 09:41:52 +00003328/// Hides a using shadow declaration. This is required by the current
3329/// using-decl implementation when a resolvable using declaration in a
3330/// class is followed by a declaration which would hide or override
3331/// one or more of the using decl's targets; for example:
3332///
3333/// struct Base { void foo(int); };
3334/// struct Derived : Base {
3335/// using Base::foo;
3336/// void foo(int);
3337/// };
3338///
3339/// The governing language is C++03 [namespace.udecl]p12:
3340///
3341/// When a using-declaration brings names from a base class into a
3342/// derived class scope, member functions in the derived class
3343/// override and/or hide member functions with the same name and
3344/// parameter types in a base class (rather than conflicting).
3345///
3346/// There are two ways to implement this:
3347/// (1) optimistically create shadow decls when they're not hidden
3348/// by existing declarations, or
3349/// (2) don't create any shadow decls (or at least don't make them
3350/// visible) until we've fully parsed/instantiated the class.
3351/// The problem with (1) is that we might have to retroactively remove
3352/// a shadow decl, which requires several O(n) operations because the
3353/// decl structures are (very reasonably) not designed for removal.
3354/// (2) avoids this but is very fiddly and phase-dependent.
3355void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3356 // Remove it from the DeclContext...
3357 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003358
John McCall9f54ad42009-12-10 09:41:52 +00003359 // ...and the scope, if applicable...
3360 if (S) {
3361 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3362 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003363 }
3364
John McCall9f54ad42009-12-10 09:41:52 +00003365 // ...and the using decl.
3366 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3367
3368 // TODO: complain somehow if Shadow was used. It shouldn't
3369 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003370}
3371
John McCall7ba107a2009-11-18 02:36:19 +00003372/// Builds a using declaration.
3373///
3374/// \param IsInstantiation - Whether this call arises from an
3375/// instantiation of an unresolved using declaration. We treat
3376/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003377NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3378 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003379 const CXXScopeSpec &SS,
3380 SourceLocation IdentLoc,
3381 DeclarationName Name,
3382 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003383 bool IsInstantiation,
3384 bool IsTypeName,
3385 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003386 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3387 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003388
Anders Carlsson550b14b2009-08-28 05:49:21 +00003389 // FIXME: We ignore attributes for now.
3390 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003392 if (SS.isEmpty()) {
3393 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003394 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003395 }
Mike Stump1eb44332009-09-09 15:08:12 +00003396
John McCall9f54ad42009-12-10 09:41:52 +00003397 // Do the redeclaration lookup in the current scope.
3398 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3399 ForRedeclaration);
3400 Previous.setHideTags(false);
3401 if (S) {
3402 LookupName(Previous, S);
3403
3404 // It is really dumb that we have to do this.
3405 LookupResult::Filter F = Previous.makeFilter();
3406 while (F.hasNext()) {
3407 NamedDecl *D = F.next();
3408 if (!isDeclInScope(D, CurContext, S))
3409 F.erase();
3410 }
3411 F.done();
3412 } else {
3413 assert(IsInstantiation && "no scope in non-instantiation");
3414 assert(CurContext->isRecord() && "scope not record in instantiation");
3415 LookupQualifiedName(Previous, CurContext);
3416 }
3417
Mike Stump1eb44332009-09-09 15:08:12 +00003418 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003419 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3420
John McCall9f54ad42009-12-10 09:41:52 +00003421 // Check for invalid redeclarations.
3422 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3423 return 0;
3424
3425 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003426 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3427 return 0;
3428
John McCallaf8e6ed2009-11-12 03:15:40 +00003429 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003430 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003431 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003432 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003433 // FIXME: not all declaration name kinds are legal here
3434 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3435 UsingLoc, TypenameLoc,
3436 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003437 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003438 } else {
3439 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3440 UsingLoc, SS.getRange(), NNS,
3441 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003442 }
John McCalled976492009-12-04 22:46:56 +00003443 } else {
3444 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3445 SS.getRange(), UsingLoc, NNS, Name,
3446 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003447 }
John McCalled976492009-12-04 22:46:56 +00003448 D->setAccess(AS);
3449 CurContext->addDecl(D);
3450
3451 if (!LookupContext) return D;
3452 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003453
John McCall604e7f12009-12-08 07:46:18 +00003454 if (RequireCompleteDeclContext(SS)) {
3455 UD->setInvalidDecl();
3456 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003457 }
3458
John McCall604e7f12009-12-08 07:46:18 +00003459 // Look up the target name.
3460
John McCalla24dc2e2009-11-17 02:14:36 +00003461 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003462
John McCall604e7f12009-12-08 07:46:18 +00003463 // Unlike most lookups, we don't always want to hide tag
3464 // declarations: tag names are visible through the using declaration
3465 // even if hidden by ordinary names, *except* in a dependent context
3466 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003467 if (!IsInstantiation)
3468 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003469
John McCalla24dc2e2009-11-17 02:14:36 +00003470 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003471
John McCallf36e02d2009-10-09 21:13:30 +00003472 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003473 Diag(IdentLoc, diag::err_no_member)
3474 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003475 UD->setInvalidDecl();
3476 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003477 }
3478
John McCalled976492009-12-04 22:46:56 +00003479 if (R.isAmbiguous()) {
3480 UD->setInvalidDecl();
3481 return UD;
3482 }
Mike Stump1eb44332009-09-09 15:08:12 +00003483
John McCall7ba107a2009-11-18 02:36:19 +00003484 if (IsTypeName) {
3485 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003486 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003487 Diag(IdentLoc, diag::err_using_typename_non_type);
3488 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3489 Diag((*I)->getUnderlyingDecl()->getLocation(),
3490 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003491 UD->setInvalidDecl();
3492 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003493 }
3494 } else {
3495 // If we asked for a non-typename and we got a type, error out,
3496 // but only if this is an instantiation of an unresolved using
3497 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003498 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003499 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3500 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003501 UD->setInvalidDecl();
3502 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003503 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003504 }
3505
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003506 // C++0x N2914 [namespace.udecl]p6:
3507 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003508 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003509 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3510 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003511 UD->setInvalidDecl();
3512 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
John McCall9f54ad42009-12-10 09:41:52 +00003515 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3516 if (!CheckUsingShadowDecl(UD, *I, Previous))
3517 BuildUsingShadowDecl(S, UD, *I);
3518 }
John McCall9488ea12009-11-17 05:59:44 +00003519
3520 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003521}
3522
John McCall9f54ad42009-12-10 09:41:52 +00003523/// Checks that the given using declaration is not an invalid
3524/// redeclaration. Note that this is checking only for the using decl
3525/// itself, not for any ill-formedness among the UsingShadowDecls.
3526bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3527 bool isTypeName,
3528 const CXXScopeSpec &SS,
3529 SourceLocation NameLoc,
3530 const LookupResult &Prev) {
3531 // C++03 [namespace.udecl]p8:
3532 // C++0x [namespace.udecl]p10:
3533 // A using-declaration is a declaration and can therefore be used
3534 // repeatedly where (and only where) multiple declarations are
3535 // allowed.
3536 // That's only in file contexts.
3537 if (CurContext->getLookupContext()->isFileContext())
3538 return false;
3539
3540 NestedNameSpecifier *Qual
3541 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3542
3543 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3544 NamedDecl *D = *I;
3545
3546 bool DTypename;
3547 NestedNameSpecifier *DQual;
3548 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3549 DTypename = UD->isTypeName();
3550 DQual = UD->getTargetNestedNameDecl();
3551 } else if (UnresolvedUsingValueDecl *UD
3552 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3553 DTypename = false;
3554 DQual = UD->getTargetNestedNameSpecifier();
3555 } else if (UnresolvedUsingTypenameDecl *UD
3556 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3557 DTypename = true;
3558 DQual = UD->getTargetNestedNameSpecifier();
3559 } else continue;
3560
3561 // using decls differ if one says 'typename' and the other doesn't.
3562 // FIXME: non-dependent using decls?
3563 if (isTypeName != DTypename) continue;
3564
3565 // using decls differ if they name different scopes (but note that
3566 // template instantiation can cause this check to trigger when it
3567 // didn't before instantiation).
3568 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3569 Context.getCanonicalNestedNameSpecifier(DQual))
3570 continue;
3571
3572 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003573 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003574 return true;
3575 }
3576
3577 return false;
3578}
3579
John McCall604e7f12009-12-08 07:46:18 +00003580
John McCalled976492009-12-04 22:46:56 +00003581/// Checks that the given nested-name qualifier used in a using decl
3582/// in the current context is appropriately related to the current
3583/// scope. If an error is found, diagnoses it and returns true.
3584bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3585 const CXXScopeSpec &SS,
3586 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003587 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003588
John McCall604e7f12009-12-08 07:46:18 +00003589 if (!CurContext->isRecord()) {
3590 // C++03 [namespace.udecl]p3:
3591 // C++0x [namespace.udecl]p8:
3592 // A using-declaration for a class member shall be a member-declaration.
3593
3594 // If we weren't able to compute a valid scope, it must be a
3595 // dependent class scope.
3596 if (!NamedContext || NamedContext->isRecord()) {
3597 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3598 << SS.getRange();
3599 return true;
3600 }
3601
3602 // Otherwise, everything is known to be fine.
3603 return false;
3604 }
3605
3606 // The current scope is a record.
3607
3608 // If the named context is dependent, we can't decide much.
3609 if (!NamedContext) {
3610 // FIXME: in C++0x, we can diagnose if we can prove that the
3611 // nested-name-specifier does not refer to a base class, which is
3612 // still possible in some cases.
3613
3614 // Otherwise we have to conservatively report that things might be
3615 // okay.
3616 return false;
3617 }
3618
3619 if (!NamedContext->isRecord()) {
3620 // Ideally this would point at the last name in the specifier,
3621 // but we don't have that level of source info.
3622 Diag(SS.getRange().getBegin(),
3623 diag::err_using_decl_nested_name_specifier_is_not_class)
3624 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3625 return true;
3626 }
3627
3628 if (getLangOptions().CPlusPlus0x) {
3629 // C++0x [namespace.udecl]p3:
3630 // In a using-declaration used as a member-declaration, the
3631 // nested-name-specifier shall name a base class of the class
3632 // being defined.
3633
3634 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3635 cast<CXXRecordDecl>(NamedContext))) {
3636 if (CurContext == NamedContext) {
3637 Diag(NameLoc,
3638 diag::err_using_decl_nested_name_specifier_is_current_class)
3639 << SS.getRange();
3640 return true;
3641 }
3642
3643 Diag(SS.getRange().getBegin(),
3644 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3645 << (NestedNameSpecifier*) SS.getScopeRep()
3646 << cast<CXXRecordDecl>(CurContext)
3647 << SS.getRange();
3648 return true;
3649 }
3650
3651 return false;
3652 }
3653
3654 // C++03 [namespace.udecl]p4:
3655 // A using-declaration used as a member-declaration shall refer
3656 // to a member of a base class of the class being defined [etc.].
3657
3658 // Salient point: SS doesn't have to name a base class as long as
3659 // lookup only finds members from base classes. Therefore we can
3660 // diagnose here only if we can prove that that can't happen,
3661 // i.e. if the class hierarchies provably don't intersect.
3662
3663 // TODO: it would be nice if "definitely valid" results were cached
3664 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3665 // need to be repeated.
3666
3667 struct UserData {
3668 llvm::DenseSet<const CXXRecordDecl*> Bases;
3669
3670 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3671 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3672 Data->Bases.insert(Base);
3673 return true;
3674 }
3675
3676 bool hasDependentBases(const CXXRecordDecl *Class) {
3677 return !Class->forallBases(collect, this);
3678 }
3679
3680 /// Returns true if the base is dependent or is one of the
3681 /// accumulated base classes.
3682 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3683 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3684 return !Data->Bases.count(Base);
3685 }
3686
3687 bool mightShareBases(const CXXRecordDecl *Class) {
3688 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3689 }
3690 };
3691
3692 UserData Data;
3693
3694 // Returns false if we find a dependent base.
3695 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3696 return false;
3697
3698 // Returns false if the class has a dependent base or if it or one
3699 // of its bases is present in the base set of the current context.
3700 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3701 return false;
3702
3703 Diag(SS.getRange().getBegin(),
3704 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3705 << (NestedNameSpecifier*) SS.getScopeRep()
3706 << cast<CXXRecordDecl>(CurContext)
3707 << SS.getRange();
3708
3709 return true;
John McCalled976492009-12-04 22:46:56 +00003710}
3711
Mike Stump1eb44332009-09-09 15:08:12 +00003712Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003713 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003714 SourceLocation AliasLoc,
3715 IdentifierInfo *Alias,
3716 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003717 SourceLocation IdentLoc,
3718 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Anders Carlsson81c85c42009-03-28 23:53:49 +00003720 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003721 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3722 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003723
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003724 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003725 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003726 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003727 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003728 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003729 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003730 if (!R.isAmbiguous() && !R.empty() &&
3731 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003732 return DeclPtrTy();
3733 }
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003735 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3736 diag::err_redefinition_different_kind;
3737 Diag(AliasLoc, DiagID) << Alias;
3738 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003739 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003740 }
3741
John McCalla24dc2e2009-11-17 02:14:36 +00003742 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003743 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003744
John McCallf36e02d2009-10-09 21:13:30 +00003745 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003746 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003747 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003748 }
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003750 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003751 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3752 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003753 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003754 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003755
John McCall3dbd3d52010-02-16 06:53:13 +00003756 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003757 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003758}
3759
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003760void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3761 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003762 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3763 !Constructor->isUsed()) &&
3764 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Eli Friedman80c30da2009-11-09 19:20:36 +00003766 CXXRecordDecl *ClassDecl
3767 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3768 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003769
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003770 DeclContext *PreviousContext = CurContext;
3771 CurContext = Constructor;
3772 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003773 Diag(CurrentLocation, diag::note_member_synthesized_at)
3774 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003775 Constructor->setInvalidDecl();
3776 } else {
3777 Constructor->setUsed();
3778 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003779 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003780}
3781
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003782void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003783 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003784 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3785 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003786 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003787 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003788
3789 DeclContext *PreviousContext = CurContext;
3790 CurContext = Destructor;
3791
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003792 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003793 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003794 // implicitly defined, all the implicitly-declared default destructors
3795 // for its base class and its non-static data members shall have been
3796 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003797 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3798 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003799 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003800 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003801 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003802 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003803 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3804 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3805 else
Mike Stump1eb44332009-09-09 15:08:12 +00003806 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003807 "DefineImplicitDestructor - missing dtor in a base class");
3808 }
3809 }
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003811 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3812 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003813 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3814 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3815 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003816 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003817 CXXRecordDecl *FieldClassDecl
3818 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3819 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003821 const_cast<CXXDestructorDecl*>(
3822 FieldClassDecl->getDestructor(Context)))
3823 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3824 else
Mike Stump1eb44332009-09-09 15:08:12 +00003825 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003826 "DefineImplicitDestructor - missing dtor in class of a data member");
3827 }
3828 }
3829 }
Anders Carlsson37909802009-11-30 21:24:50 +00003830
3831 // FIXME: If CheckDestructor fails, we should emit a note about where the
3832 // implicit destructor was needed.
3833 if (CheckDestructor(Destructor)) {
3834 Diag(CurrentLocation, diag::note_member_synthesized_at)
3835 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3836
3837 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003838 CurContext = PreviousContext;
3839
Anders Carlsson37909802009-11-30 21:24:50 +00003840 return;
3841 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003842 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003843
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003844 Destructor->setUsed();
3845}
3846
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003847void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3848 CXXMethodDecl *MethodDecl) {
3849 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3850 MethodDecl->getOverloadedOperator() == OO_Equal &&
3851 !MethodDecl->isUsed()) &&
3852 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003853
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003854 CXXRecordDecl *ClassDecl
3855 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003857 DeclContext *PreviousContext = CurContext;
3858 CurContext = MethodDecl;
3859
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003860 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003861 // Before the implicitly-declared copy assignment operator for a class is
3862 // implicitly defined, all implicitly-declared copy assignment operators
3863 // for its direct base classes and its nonstatic data members shall have
3864 // been implicitly defined.
3865 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003866 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3867 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003868 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003869 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003870 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003871 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3872 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003873 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3874 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003875 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3876 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003877 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3878 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3879 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003880 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003881 CXXRecordDecl *FieldClassDecl
3882 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003883 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003884 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3885 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003886 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003887 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003889 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3890 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003891 Diag(CurrentLocation, diag::note_first_required_here);
3892 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003893 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003894 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003895 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3896 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003897 Diag(CurrentLocation, diag::note_first_required_here);
3898 err = true;
3899 }
3900 }
3901 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003902 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003903
3904 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003905}
3906
3907CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003908Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3909 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003910 CXXRecordDecl *ClassDecl) {
3911 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3912 QualType RHSType(LHSType);
3913 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003914 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003915 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003916 RHSType = Context.getCVRQualifiedType(RHSType,
3917 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003918 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003919 LHSType,
3920 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003921 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003922 RHSType,
3923 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003924 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003925 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003926 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003927 CandidateSet);
3928 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003929 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003930 return cast<CXXMethodDecl>(Best->Function);
3931 assert(false &&
3932 "getAssignOperatorMethod - copy assignment operator method not found");
3933 return 0;
3934}
3935
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003936void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3937 CXXConstructorDecl *CopyConstructor,
3938 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003939 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003940 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003941 !CopyConstructor->isUsed()) &&
3942 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003943
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003944 CXXRecordDecl *ClassDecl
3945 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3946 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003947
3948 DeclContext *PreviousContext = CurContext;
3949 CurContext = CopyConstructor;
3950
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003951 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003952 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003953 // implicitly defined, all the implicitly-declared copy constructors
3954 // for its base class and its non-static data members shall have been
3955 // implicitly defined.
3956 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3957 Base != ClassDecl->bases_end(); ++Base) {
3958 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003959 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003960 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003961 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003962 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003963 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003964 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3965 FieldEnd = ClassDecl->field_end();
3966 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003967 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3968 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3969 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003970 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003971 CXXRecordDecl *FieldClassDecl
3972 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003973 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003974 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003975 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003976 }
3977 }
3978 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003979
3980 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003981}
3982
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003983Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003984Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003985 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003986 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003987 bool RequiresZeroInit,
3988 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003989 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregor39da0b82009-09-09 23:08:42 +00003991 // C++ [class.copy]p15:
3992 // Whenever a temporary class object is copied using a copy constructor, and
3993 // this object and the copy have the same cv-unqualified type, an
3994 // implementation is permitted to treat the original and the copy as two
3995 // different ways of referring to the same object and not perform a copy at
3996 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003998 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003999 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004000 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4002 if (ICE->getCastKind() == CastExpr::CK_NoOp)
4003 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00004004 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
4005 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004006 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
4007 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004008 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4009 if (ICE->getCastKind() == CastExpr::CK_NoOp)
4010 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00004011
4012 if (CallExpr *CE = dyn_cast<CallExpr>(E))
4013 Elidable = !CE->getCallReturnType()->isReferenceType();
4014 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004015 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00004016 else if (isa<CXXConstructExpr>(E))
4017 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
4020 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004021 Elidable, move(ExprArgs), RequiresZeroInit,
4022 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004023}
4024
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004025/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4026/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004027Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004028Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4029 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004030 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004031 bool RequiresZeroInit,
4032 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004033 unsigned NumExprs = ExprArgs.size();
4034 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Douglas Gregor7edfb692009-11-23 12:27:39 +00004036 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004037 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004038 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004039 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004040}
4041
Mike Stump1eb44332009-09-09 15:08:12 +00004042bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004043 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004044 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004045 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004046 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004047 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004048 if (TempResult.isInvalid())
4049 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004051 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004052 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004053 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004054 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Anders Carlssonfe2de492009-08-25 05:18:00 +00004056 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004057}
4058
John McCall68c6c9a2010-02-02 09:10:11 +00004059void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4060 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004061 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4062 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004063 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4064 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004065 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004066 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004067}
4068
Mike Stump1eb44332009-09-09 15:08:12 +00004069/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004070/// ActOnDeclarator, when a C++ direct initializer is present.
4071/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004072void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4073 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004074 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004075 SourceLocation *CommaLocs,
4076 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004077 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004078 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004079
4080 // If there is no declaration, there was an error parsing it. Just ignore
4081 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004082 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004085 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4086 if (!VDecl) {
4087 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4088 RealDecl->setInvalidDecl();
4089 return;
4090 }
4091
Douglas Gregor83ddad32009-08-26 21:14:46 +00004092 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004093 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004094 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4095 //
4096 // Clients that want to distinguish between the two forms, can check for
4097 // direct initializer using VarDecl::hasCXXDirectInitializer().
4098 // A major benefit is that clients that don't particularly care about which
4099 // exactly form was it (like the CodeGen) can handle both cases without
4100 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004101
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004102 // C++ 8.5p11:
4103 // The form of initialization (using parentheses or '=') is generally
4104 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004105 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004106 QualType DeclInitType = VDecl->getType();
4107 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004108 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004109
Douglas Gregor4dffad62010-02-11 22:55:30 +00004110 if (!VDecl->getType()->isDependentType() &&
4111 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004112 diag::err_typecheck_decl_incomplete_type)) {
4113 VDecl->setInvalidDecl();
4114 return;
4115 }
4116
Douglas Gregor90f93822009-12-22 22:17:25 +00004117 // The variable can not have an abstract class type.
4118 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4119 diag::err_abstract_type_in_decl,
4120 AbstractVariableType))
4121 VDecl->setInvalidDecl();
4122
Sebastian Redl31310a22010-02-01 20:16:42 +00004123 const VarDecl *Def;
4124 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004125 Diag(VDecl->getLocation(), diag::err_redefinition)
4126 << VDecl->getDeclName();
4127 Diag(Def->getLocation(), diag::note_previous_definition);
4128 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004129 return;
4130 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004131
4132 // If either the declaration has a dependent type or if any of the
4133 // expressions is type-dependent, we represent the initialization
4134 // via a ParenListExpr for later use during template instantiation.
4135 if (VDecl->getType()->isDependentType() ||
4136 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4137 // Let clients know that initialization was done with a direct initializer.
4138 VDecl->setCXXDirectInitializer(true);
4139
4140 // Store the initialization expressions as a ParenListExpr.
4141 unsigned NumExprs = Exprs.size();
4142 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4143 (Expr **)Exprs.release(),
4144 NumExprs, RParenLoc));
4145 return;
4146 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004147
4148 // Capture the variable that is being initialized and the style of
4149 // initialization.
4150 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4151
4152 // FIXME: Poor source location information.
4153 InitializationKind Kind
4154 = InitializationKind::CreateDirect(VDecl->getLocation(),
4155 LParenLoc, RParenLoc);
4156
4157 InitializationSequence InitSeq(*this, Entity, Kind,
4158 (Expr**)Exprs.get(), Exprs.size());
4159 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4160 if (Result.isInvalid()) {
4161 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004162 return;
4163 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004164
4165 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004166 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004167 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004168
John McCall68c6c9a2010-02-02 09:10:11 +00004169 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4170 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004171}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004172
Douglas Gregor19aeac62009-11-14 03:27:21 +00004173/// \brief Add the applicable constructor candidates for an initialization
4174/// by constructor.
4175static void AddConstructorInitializationCandidates(Sema &SemaRef,
4176 QualType ClassType,
4177 Expr **Args,
4178 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004179 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004180 OverloadCandidateSet &CandidateSet) {
4181 // C++ [dcl.init]p14:
4182 // If the initialization is direct-initialization, or if it is
4183 // copy-initialization where the cv-unqualified version of the
4184 // source type is the same class as, or a derived class of, the
4185 // class of the destination, constructors are considered. The
4186 // applicable constructors are enumerated (13.3.1.3), and the
4187 // best one is chosen through overload resolution (13.3). The
4188 // constructor so selected is called to initialize the object,
4189 // with the initializer expression(s) as its argument(s). If no
4190 // constructor applies, or the overload resolution is ambiguous,
4191 // the initialization is ill-formed.
4192 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4193 assert(ClassRec && "Can only initialize a class type here");
4194
4195 // FIXME: When we decide not to synthesize the implicitly-declared
4196 // constructors, we'll need to make them appear here.
4197
4198 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4199 DeclarationName ConstructorName
4200 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4201 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4202 DeclContext::lookup_const_iterator Con, ConEnd;
4203 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4204 Con != ConEnd; ++Con) {
4205 // Find the constructor (which may be a template).
4206 CXXConstructorDecl *Constructor = 0;
4207 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4208 if (ConstructorTmpl)
4209 Constructor
4210 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4211 else
4212 Constructor = cast<CXXConstructorDecl>(*Con);
4213
Douglas Gregor20093b42009-12-09 23:02:17 +00004214 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4215 (Kind.getKind() == InitializationKind::IK_Value) ||
4216 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004217 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004218 ((Kind.getKind() == InitializationKind::IK_Default) &&
4219 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004220 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004221 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004222 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004223 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004224 Args, NumArgs, CandidateSet);
4225 else
John McCall86820f52010-01-26 01:37:31 +00004226 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4227 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004228 }
4229 }
4230}
4231
4232/// \brief Attempt to perform initialization by constructor
4233/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4234/// copy-initialization.
4235///
4236/// This routine determines whether initialization by constructor is possible,
4237/// but it does not emit any diagnostics in the case where the initialization
4238/// is ill-formed.
4239///
4240/// \param ClassType the type of the object being initialized, which must have
4241/// class type.
4242///
4243/// \param Args the arguments provided to initialize the object
4244///
4245/// \param NumArgs the number of arguments provided to initialize the object
4246///
4247/// \param Kind the type of initialization being performed
4248///
4249/// \returns the constructor used to initialize the object, if successful.
4250/// Otherwise, emits a diagnostic and returns NULL.
4251CXXConstructorDecl *
4252Sema::TryInitializationByConstructor(QualType ClassType,
4253 Expr **Args, unsigned NumArgs,
4254 SourceLocation Loc,
4255 InitializationKind Kind) {
4256 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004257 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004258 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4259 CandidateSet);
4260
4261 // Determine whether we found a constructor we can use.
4262 OverloadCandidateSet::iterator Best;
4263 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4264 case OR_Success:
4265 case OR_Deleted:
4266 // We found a constructor. Return it.
4267 return cast<CXXConstructorDecl>(Best->Function);
4268
4269 case OR_No_Viable_Function:
4270 case OR_Ambiguous:
4271 // Overload resolution failed. Return nothing.
4272 return 0;
4273 }
4274
4275 // Silence GCC warning
4276 return 0;
4277}
4278
Douglas Gregor39da0b82009-09-09 23:08:42 +00004279/// \brief Given a constructor and the set of arguments provided for the
4280/// constructor, convert the arguments and add any required default arguments
4281/// to form a proper call to this constructor.
4282///
4283/// \returns true if an error occurred, false otherwise.
4284bool
4285Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4286 MultiExprArg ArgsPtr,
4287 SourceLocation Loc,
4288 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4289 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4290 unsigned NumArgs = ArgsPtr.size();
4291 Expr **Args = (Expr **)ArgsPtr.get();
4292
4293 const FunctionProtoType *Proto
4294 = Constructor->getType()->getAs<FunctionProtoType>();
4295 assert(Proto && "Constructor without a prototype?");
4296 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004297
4298 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004299 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004300 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004301 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004302 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004303
4304 VariadicCallType CallType =
4305 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4306 llvm::SmallVector<Expr *, 8> AllArgs;
4307 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4308 Proto, 0, Args, NumArgs, AllArgs,
4309 CallType);
4310 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4311 ConvertedArgs.push_back(AllArgs[i]);
4312 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004313}
4314
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004315/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4316/// determine whether they are reference-related,
4317/// reference-compatible, reference-compatible with added
4318/// qualification, or incompatible, for use in C++ initialization by
4319/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4320/// type, and the first type (T1) is the pointee type of the reference
4321/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004322Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004323Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004324 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004325 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004326 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004327 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004328 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004329
Douglas Gregor393896f2009-11-05 13:06:35 +00004330 QualType T1 = Context.getCanonicalType(OrigT1);
4331 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004332 Qualifiers T1Quals, T2Quals;
4333 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4334 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004335
4336 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004337 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004338 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004339 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004340 if (UnqualT1 == UnqualT2)
4341 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004342 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4343 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4344 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004345 DerivedToBase = true;
4346 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004347 return Ref_Incompatible;
4348
4349 // At this point, we know that T1 and T2 are reference-related (at
4350 // least).
4351
Chandler Carruth28e318c2009-12-29 07:16:59 +00004352 // If the type is an array type, promote the element qualifiers to the type
4353 // for comparison.
4354 if (isa<ArrayType>(T1) && T1Quals)
4355 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4356 if (isa<ArrayType>(T2) && T2Quals)
4357 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4358
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004359 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004360 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004361 // reference-related to T2 and cv1 is the same cv-qualification
4362 // as, or greater cv-qualification than, cv2. For purposes of
4363 // overload resolution, cases for which cv1 is greater
4364 // cv-qualification than cv2 are identified as
4365 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004366 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004367 return Ref_Compatible;
4368 else if (T1.isMoreQualifiedThan(T2))
4369 return Ref_Compatible_With_Added_Qualification;
4370 else
4371 return Ref_Related;
4372}
4373
4374/// CheckReferenceInit - Check the initialization of a reference
4375/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4376/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004377/// list), and DeclType is the type of the declaration. When ICS is
4378/// non-null, this routine will compute the implicit conversion
4379/// sequence according to C++ [over.ics.ref] and will not produce any
4380/// diagnostics; when ICS is null, it will emit diagnostics when any
4381/// errors are found. Either way, a return value of true indicates
4382/// that there was a failure, a return value of false indicates that
4383/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004384///
4385/// When @p SuppressUserConversions, user-defined conversions are
4386/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004387/// When @p AllowExplicit, we also permit explicit user-defined
4388/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004389/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004390/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4391/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004392bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004393Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004394 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004395 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004396 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004397 ImplicitConversionSequence *ICS,
4398 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004399 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4400
Ted Kremenek6217b802009-07-29 21:53:49 +00004401 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004402 QualType T2 = Init->getType();
4403
Douglas Gregor904eed32008-11-10 20:40:00 +00004404 // If the initializer is the address of an overloaded function, try
4405 // to resolve the overloaded function. If all goes well, T2 is the
4406 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004407 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004408 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004409 ICS != 0);
4410 if (Fn) {
4411 // Since we're performing this reference-initialization for
4412 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004413 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004414 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004415 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004416
Anders Carlsson96ad5332009-10-21 17:16:23 +00004417 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004418 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004419
4420 T2 = Fn->getType();
4421 }
4422 }
4423
Douglas Gregor15da57e2008-10-29 02:00:59 +00004424 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004425 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004426 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004427 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4428 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004429 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004430 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004431
4432 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004433 if (ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00004434 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCalladbb8f82010-01-13 09:16:55 +00004435 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004436
4437 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004438 // A reference to type "cv1 T1" is initialized by an expression
4439 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004440
4441 // -- If the initializer expression
4442
Sebastian Redla9845802009-03-29 15:27:50 +00004443 // Rvalue references cannot bind to lvalues (N2812).
4444 // There is absolutely no situation where they can. In particular, note that
4445 // this is ill-formed, even if B has a user-defined conversion to A&&:
4446 // B b;
4447 // A&& r = b;
4448 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4449 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004450 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004451 << Init->getSourceRange();
4452 return true;
4453 }
4454
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004455 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004456 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4457 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004458 //
4459 // Note that the bit-field check is skipped if we are just computing
4460 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004461 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004462 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004463 BindsDirectly = true;
4464
Douglas Gregor15da57e2008-10-29 02:00:59 +00004465 if (ICS) {
4466 // C++ [over.ics.ref]p1:
4467 // When a parameter of reference type binds directly (8.5.3)
4468 // to an argument expression, the implicit conversion sequence
4469 // is the identity conversion, unless the argument expression
4470 // has a type that is a derived class of the parameter type,
4471 // in which case the implicit conversion sequence is a
4472 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004473 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004474 ICS->Standard.First = ICK_Identity;
4475 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4476 ICS->Standard.Third = ICK_Identity;
4477 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004478 ICS->Standard.setToType(0, T2);
4479 ICS->Standard.setToType(1, T1);
4480 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004481 ICS->Standard.ReferenceBinding = true;
4482 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004483 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004484 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004485
4486 // Nothing more to do: the inaccessibility/ambiguity check for
4487 // derived-to-base conversions is suppressed when we're
4488 // computing the implicit conversion sequence (C++
4489 // [over.best.ics]p2).
4490 return false;
4491 } else {
4492 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004493 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4494 if (DerivedToBase)
4495 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004496 else if(CheckExceptionSpecCompatibility(Init, T1))
4497 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004498 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004499 }
4500 }
4501
4502 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004503 // implicitly converted to an lvalue of type "cv3 T3,"
4504 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004505 // 92) (this conversion is selected by enumerating the
4506 // applicable conversion functions (13.3.1.6) and choosing
4507 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004508 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004509 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004510 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004511 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004512
John McCall5769d612010-02-08 23:07:23 +00004513 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004514 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004515 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004516 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004517 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004518 NamedDecl *D = *I;
4519 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4520 if (isa<UsingShadowDecl>(D))
4521 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4522
Mike Stump1eb44332009-09-09 15:08:12 +00004523 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004524 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004525 CXXConversionDecl *Conv;
4526 if (ConvTemplate)
4527 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4528 else
John McCall701c89e2009-12-03 04:06:58 +00004529 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004530
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004531 // If the conversion function doesn't return a reference type,
4532 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004533 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004534 (AllowExplicit || !Conv->isExplicit())) {
4535 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004536 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004537 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004538 else
John McCall86820f52010-01-26 01:37:31 +00004539 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4540 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004541 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004542 }
4543
4544 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004545 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004546 case OR_Success:
Douglas Gregora1a9f032010-03-07 23:17:44 +00004547 // C++ [over.ics.ref]p1:
4548 //
4549 // [...] If the parameter binds directly to the result of
4550 // applying a conversion function to the argument
4551 // expression, the implicit conversion sequence is a
4552 // user-defined conversion sequence (13.3.3.1.2), with the
4553 // second standard conversion sequence either an identity
4554 // conversion or, if the conversion function returns an
4555 // entity of a type that is a derived class of the parameter
4556 // type, a derived-to-base Conversion.
4557 if (!Best->FinalConversion.DirectBinding)
4558 break;
4559
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004560 // This is a direct binding.
4561 BindsDirectly = true;
4562
4563 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004564 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004565 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4566 ICS->UserDefined.After = Best->FinalConversion;
4567 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004568 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004569 assert(ICS->UserDefined.After.ReferenceBinding &&
4570 ICS->UserDefined.After.DirectBinding &&
4571 "Expected a direct reference binding!");
4572 return false;
4573 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004574 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004575 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004576 CastExpr::CK_UserDefinedConversion,
4577 cast<CXXMethodDecl>(Best->Function),
4578 Owned(Init));
4579 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004580
4581 if (CheckExceptionSpecCompatibility(Init, T1))
4582 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004583 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4584 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004585 }
4586 break;
4587
4588 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004589 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004590 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004591 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4592 Cand != CandidateSet.end(); ++Cand)
4593 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004594 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004595 break;
4596 }
4597 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4598 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004599 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004600 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004601
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004602 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004603 case OR_Deleted:
4604 // There was no suitable conversion, or we found a deleted
4605 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004606 break;
4607 }
4608 }
Mike Stump1eb44332009-09-09 15:08:12 +00004609
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004610 if (BindsDirectly) {
4611 // C++ [dcl.init.ref]p4:
4612 // [...] In all cases where the reference-related or
4613 // reference-compatible relationship of two types is used to
4614 // establish the validity of a reference binding, and T1 is a
4615 // base class of T2, a program that necessitates such a binding
4616 // is ill-formed if T1 is an inaccessible (clause 11) or
4617 // ambiguous (10.2) base class of T2.
4618 //
4619 // Note that we only check this condition when we're allowed to
4620 // complain about errors, because we should not be checking for
4621 // ambiguity (or inaccessibility) unless the reference binding
4622 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004623 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004624 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004625 Init->getSourceRange(),
4626 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004627 else
4628 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004629 }
4630
4631 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004632 // type (i.e., cv1 shall be const), or the reference shall be an
4633 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004634 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004635 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004636 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004637 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004638 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004639 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004640 return true;
4641 }
4642
4643 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004644 // class type, and "cv1 T1" is reference-compatible with
4645 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004646 // following ways (the choice is implementation-defined):
4647 //
4648 // -- The reference is bound to the object represented by
4649 // the rvalue (see 3.10) or to a sub-object within that
4650 // object.
4651 //
Eli Friedman33a31382009-08-05 19:21:58 +00004652 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004653 // a constructor is called to copy the entire rvalue
4654 // object into the temporary. The reference is bound to
4655 // the temporary or to a sub-object within the
4656 // temporary.
4657 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004658 // The constructor that would be used to make the copy
4659 // shall be callable whether or not the copy is actually
4660 // done.
4661 //
Sebastian Redla9845802009-03-29 15:27:50 +00004662 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004663 // freedom, so we will always take the first option and never build
4664 // a temporary in this case. FIXME: We will, however, have to check
4665 // for the presence of a copy constructor in C++98/03 mode.
4666 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004667 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4668 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004669 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004670 ICS->Standard.First = ICK_Identity;
4671 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4672 ICS->Standard.Third = ICK_Identity;
4673 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004674 ICS->Standard.setToType(0, T2);
4675 ICS->Standard.setToType(1, T1);
4676 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004677 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004678 ICS->Standard.DirectBinding = false;
4679 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004680 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004681 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004682 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4683 if (DerivedToBase)
4684 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004685 else if(CheckExceptionSpecCompatibility(Init, T1))
4686 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004687 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004688 }
4689 return false;
4690 }
4691
Eli Friedman33a31382009-08-05 19:21:58 +00004692 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004693 // initialized from the initializer expression using the
4694 // rules for a non-reference copy initialization (8.5). The
4695 // reference is then bound to the temporary. If T1 is
4696 // reference-related to T2, cv1 must be the same
4697 // cv-qualification as, or greater cv-qualification than,
4698 // cv2; otherwise, the program is ill-formed.
4699 if (RefRelationship == Ref_Related) {
4700 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4701 // we would be reference-compatible or reference-compatible with
4702 // added qualification. But that wasn't the case, so the reference
4703 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004704 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004705 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004706 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004707 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004708 return true;
4709 }
4710
Douglas Gregor734d9862009-01-30 23:27:23 +00004711 // If at least one of the types is a class type, the types are not
4712 // related, and we aren't allowed any user conversions, the
4713 // reference binding fails. This case is important for breaking
4714 // recursion, since TryImplicitConversion below will attempt to
4715 // create a temporary through the use of a copy constructor.
4716 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4717 (T1->isRecordType() || T2->isRecordType())) {
4718 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004719 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004720 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004721 return true;
4722 }
4723
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004724 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004725 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004726 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004727 //
Sebastian Redla9845802009-03-29 15:27:50 +00004728 // When a parameter of reference type is not bound directly to
4729 // an argument expression, the conversion sequence is the one
4730 // required to convert the argument expression to the
4731 // underlying type of the reference according to
4732 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4733 // to copy-initializing a temporary of the underlying type with
4734 // the argument expression. Any difference in top-level
4735 // cv-qualification is subsumed by the initialization itself
4736 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004737 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4738 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004739 /*ForceRValue=*/false,
4740 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004741
Sebastian Redla9845802009-03-29 15:27:50 +00004742 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004743 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004744 ICS->Standard.ReferenceBinding = true;
4745 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004746 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004747 ICS->UserDefined.After.ReferenceBinding = true;
4748 ICS->UserDefined.After.RRefBinding = isRValRef;
4749 }
John McCall1d318332010-01-12 00:44:57 +00004750 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004751 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004752 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004753 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004754 false, false,
4755 Conversions);
4756 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004757 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004758 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004759 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004760 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004761 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004762 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004763 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004764 }
4765 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004766 else {
4767 if (isRValRef)
4768 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4769 << Init->getSourceRange();
4770 else
4771 Diag(DeclLoc, diag::err_invalid_initialization)
4772 << DeclType << Init->getType() << Init->getSourceRange();
4773 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004774 }
4775 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004776 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004777}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004778
Anders Carlsson20d45d22009-12-12 00:32:00 +00004779static inline bool
4780CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4781 const FunctionDecl *FnDecl) {
4782 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4783 if (isa<NamespaceDecl>(DC)) {
4784 return SemaRef.Diag(FnDecl->getLocation(),
4785 diag::err_operator_new_delete_declared_in_namespace)
4786 << FnDecl->getDeclName();
4787 }
4788
4789 if (isa<TranslationUnitDecl>(DC) &&
4790 FnDecl->getStorageClass() == FunctionDecl::Static) {
4791 return SemaRef.Diag(FnDecl->getLocation(),
4792 diag::err_operator_new_delete_declared_static)
4793 << FnDecl->getDeclName();
4794 }
4795
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004796 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004797}
4798
Anders Carlsson156c78e2009-12-13 17:53:43 +00004799static inline bool
4800CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4801 CanQualType ExpectedResultType,
4802 CanQualType ExpectedFirstParamType,
4803 unsigned DependentParamTypeDiag,
4804 unsigned InvalidParamTypeDiag) {
4805 QualType ResultType =
4806 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4807
4808 // Check that the result type is not dependent.
4809 if (ResultType->isDependentType())
4810 return SemaRef.Diag(FnDecl->getLocation(),
4811 diag::err_operator_new_delete_dependent_result_type)
4812 << FnDecl->getDeclName() << ExpectedResultType;
4813
4814 // Check that the result type is what we expect.
4815 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4816 return SemaRef.Diag(FnDecl->getLocation(),
4817 diag::err_operator_new_delete_invalid_result_type)
4818 << FnDecl->getDeclName() << ExpectedResultType;
4819
4820 // A function template must have at least 2 parameters.
4821 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4822 return SemaRef.Diag(FnDecl->getLocation(),
4823 diag::err_operator_new_delete_template_too_few_parameters)
4824 << FnDecl->getDeclName();
4825
4826 // The function decl must have at least 1 parameter.
4827 if (FnDecl->getNumParams() == 0)
4828 return SemaRef.Diag(FnDecl->getLocation(),
4829 diag::err_operator_new_delete_too_few_parameters)
4830 << FnDecl->getDeclName();
4831
4832 // Check the the first parameter type is not dependent.
4833 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4834 if (FirstParamType->isDependentType())
4835 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4836 << FnDecl->getDeclName() << ExpectedFirstParamType;
4837
4838 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004839 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004840 ExpectedFirstParamType)
4841 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4842 << FnDecl->getDeclName() << ExpectedFirstParamType;
4843
4844 return false;
4845}
4846
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004847static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004848CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004849 // C++ [basic.stc.dynamic.allocation]p1:
4850 // A program is ill-formed if an allocation function is declared in a
4851 // namespace scope other than global scope or declared static in global
4852 // scope.
4853 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4854 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004855
4856 CanQualType SizeTy =
4857 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4858
4859 // C++ [basic.stc.dynamic.allocation]p1:
4860 // The return type shall be void*. The first parameter shall have type
4861 // std::size_t.
4862 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4863 SizeTy,
4864 diag::err_operator_new_dependent_param_type,
4865 diag::err_operator_new_param_type))
4866 return true;
4867
4868 // C++ [basic.stc.dynamic.allocation]p1:
4869 // The first parameter shall not have an associated default argument.
4870 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004871 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004872 diag::err_operator_new_default_arg)
4873 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4874
4875 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004876}
4877
4878static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004879CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4880 // C++ [basic.stc.dynamic.deallocation]p1:
4881 // A program is ill-formed if deallocation functions are declared in a
4882 // namespace scope other than global scope or declared static in global
4883 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004884 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4885 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004886
4887 // C++ [basic.stc.dynamic.deallocation]p2:
4888 // Each deallocation function shall return void and its first parameter
4889 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004890 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4891 SemaRef.Context.VoidPtrTy,
4892 diag::err_operator_delete_dependent_param_type,
4893 diag::err_operator_delete_param_type))
4894 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004895
Anders Carlsson46991d62009-12-12 00:16:02 +00004896 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4897 if (FirstParamType->isDependentType())
4898 return SemaRef.Diag(FnDecl->getLocation(),
4899 diag::err_operator_delete_dependent_param_type)
4900 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4901
4902 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4903 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004904 return SemaRef.Diag(FnDecl->getLocation(),
4905 diag::err_operator_delete_param_type)
4906 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004907
4908 return false;
4909}
4910
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004911/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4912/// of this overloaded operator is well-formed. If so, returns false;
4913/// otherwise, emits appropriate diagnostics and returns true.
4914bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004915 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004916 "Expected an overloaded operator declaration");
4917
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004918 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4919
Mike Stump1eb44332009-09-09 15:08:12 +00004920 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004921 // The allocation and deallocation functions, operator new,
4922 // operator new[], operator delete and operator delete[], are
4923 // described completely in 3.7.3. The attributes and restrictions
4924 // found in the rest of this subclause do not apply to them unless
4925 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004926 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004927 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004928
Anders Carlssona3ccda52009-12-12 00:26:23 +00004929 if (Op == OO_New || Op == OO_Array_New)
4930 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004931
4932 // C++ [over.oper]p6:
4933 // An operator function shall either be a non-static member
4934 // function or be a non-member function and have at least one
4935 // parameter whose type is a class, a reference to a class, an
4936 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004937 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4938 if (MethodDecl->isStatic())
4939 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004940 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004941 } else {
4942 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004943 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4944 ParamEnd = FnDecl->param_end();
4945 Param != ParamEnd; ++Param) {
4946 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004947 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4948 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004949 ClassOrEnumParam = true;
4950 break;
4951 }
4952 }
4953
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004954 if (!ClassOrEnumParam)
4955 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004956 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004957 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004958 }
4959
4960 // C++ [over.oper]p8:
4961 // An operator function cannot have default arguments (8.3.6),
4962 // except where explicitly stated below.
4963 //
Mike Stump1eb44332009-09-09 15:08:12 +00004964 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004965 // (C++ [over.call]p1).
4966 if (Op != OO_Call) {
4967 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4968 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004969 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004970 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004971 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004972 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004973 }
4974 }
4975
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004976 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4977 { false, false, false }
4978#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4979 , { Unary, Binary, MemberOnly }
4980#include "clang/Basic/OperatorKinds.def"
4981 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004982
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004983 bool CanBeUnaryOperator = OperatorUses[Op][0];
4984 bool CanBeBinaryOperator = OperatorUses[Op][1];
4985 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004986
4987 // C++ [over.oper]p8:
4988 // [...] Operator functions cannot have more or fewer parameters
4989 // than the number required for the corresponding operator, as
4990 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004991 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004992 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004993 if (Op != OO_Call &&
4994 ((NumParams == 1 && !CanBeUnaryOperator) ||
4995 (NumParams == 2 && !CanBeBinaryOperator) ||
4996 (NumParams < 1) || (NumParams > 2))) {
4997 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004998 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004999 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005000 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005001 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005002 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005003 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005004 assert(CanBeBinaryOperator &&
5005 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005006 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005007 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005008
Chris Lattner416e46f2008-11-21 07:57:12 +00005009 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005010 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005011 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005012
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005013 // Overloaded operators other than operator() cannot be variadic.
5014 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005015 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005016 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005017 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005018 }
5019
5020 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005021 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5022 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005023 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005024 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005025 }
5026
5027 // C++ [over.inc]p1:
5028 // The user-defined function called operator++ implements the
5029 // prefix and postfix ++ operator. If this function is a member
5030 // function with no parameters, or a non-member function with one
5031 // parameter of class or enumeration type, it defines the prefix
5032 // increment operator ++ for objects of that type. If the function
5033 // is a member function with one parameter (which shall be of type
5034 // int) or a non-member function with two parameters (the second
5035 // of which shall be of type int), it defines the postfix
5036 // increment operator ++ for objects of that type.
5037 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5038 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5039 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005040 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005041 ParamIsInt = BT->getKind() == BuiltinType::Int;
5042
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005043 if (!ParamIsInt)
5044 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005045 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005046 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005047 }
5048
Sebastian Redl64b45f72009-01-05 20:52:13 +00005049 // Notify the class if it got an assignment operator.
5050 if (Op == OO_Equal) {
5051 // Would have returned earlier otherwise.
5052 assert(isa<CXXMethodDecl>(FnDecl) &&
5053 "Overloaded = not member, but not filtered.");
5054 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5055 Method->getParent()->addedAssignmentOperator(Context, Method);
5056 }
5057
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005058 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005059}
Chris Lattner5a003a42008-12-17 07:09:26 +00005060
Sean Hunta6c058d2010-01-13 09:01:02 +00005061/// CheckLiteralOperatorDeclaration - Check whether the declaration
5062/// of this literal operator function is well-formed. If so, returns
5063/// false; otherwise, emits appropriate diagnostics and returns true.
5064bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5065 DeclContext *DC = FnDecl->getDeclContext();
5066 Decl::Kind Kind = DC->getDeclKind();
5067 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5068 Kind != Decl::LinkageSpec) {
5069 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5070 << FnDecl->getDeclName();
5071 return true;
5072 }
5073
5074 bool Valid = false;
5075
5076 // FIXME: Check for the one valid template signature
5077 // template <char...> type operator "" name();
5078
5079 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5080 // Check the first parameter
5081 QualType T = (*Param)->getType();
5082
5083 // unsigned long long int and long double are allowed, but only
5084 // alone.
5085 // We also allow any character type; their omission seems to be a bug
5086 // in n3000
5087 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5088 Context.hasSameType(T, Context.LongDoubleTy) ||
5089 Context.hasSameType(T, Context.CharTy) ||
5090 Context.hasSameType(T, Context.WCharTy) ||
5091 Context.hasSameType(T, Context.Char16Ty) ||
5092 Context.hasSameType(T, Context.Char32Ty)) {
5093 if (++Param == FnDecl->param_end())
5094 Valid = true;
5095 goto FinishedParams;
5096 }
5097
5098 // Otherwise it must be a pointer to const; let's strip those.
5099 const PointerType *PT = T->getAs<PointerType>();
5100 if (!PT)
5101 goto FinishedParams;
5102 T = PT->getPointeeType();
5103 if (!T.isConstQualified())
5104 goto FinishedParams;
5105 T = T.getUnqualifiedType();
5106
5107 // Move on to the second parameter;
5108 ++Param;
5109
5110 // If there is no second parameter, the first must be a const char *
5111 if (Param == FnDecl->param_end()) {
5112 if (Context.hasSameType(T, Context.CharTy))
5113 Valid = true;
5114 goto FinishedParams;
5115 }
5116
5117 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5118 // are allowed as the first parameter to a two-parameter function
5119 if (!(Context.hasSameType(T, Context.CharTy) ||
5120 Context.hasSameType(T, Context.WCharTy) ||
5121 Context.hasSameType(T, Context.Char16Ty) ||
5122 Context.hasSameType(T, Context.Char32Ty)))
5123 goto FinishedParams;
5124
5125 // The second and final parameter must be an std::size_t
5126 T = (*Param)->getType().getUnqualifiedType();
5127 if (Context.hasSameType(T, Context.getSizeType()) &&
5128 ++Param == FnDecl->param_end())
5129 Valid = true;
5130 }
5131
5132 // FIXME: This diagnostic is absolutely terrible.
5133FinishedParams:
5134 if (!Valid) {
5135 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5136 << FnDecl->getDeclName();
5137 return true;
5138 }
5139
5140 return false;
5141}
5142
Douglas Gregor074149e2009-01-05 19:45:36 +00005143/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5144/// linkage specification, including the language and (if present)
5145/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5146/// the location of the language string literal, which is provided
5147/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5148/// the '{' brace. Otherwise, this linkage specification does not
5149/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005150Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5151 SourceLocation ExternLoc,
5152 SourceLocation LangLoc,
5153 const char *Lang,
5154 unsigned StrSize,
5155 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005156 LinkageSpecDecl::LanguageIDs Language;
5157 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5158 Language = LinkageSpecDecl::lang_c;
5159 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5160 Language = LinkageSpecDecl::lang_cxx;
5161 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005162 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005163 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005164 }
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Chris Lattnercc98eac2008-12-17 07:13:27 +00005166 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Douglas Gregor074149e2009-01-05 19:45:36 +00005168 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005169 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005170 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005171 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005172 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005173 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005174}
5175
Douglas Gregor074149e2009-01-05 19:45:36 +00005176/// ActOnFinishLinkageSpecification - Completely the definition of
5177/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5178/// valid, it's the position of the closing '}' brace in a linkage
5179/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005180Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5181 DeclPtrTy LinkageSpec,
5182 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005183 if (LinkageSpec)
5184 PopDeclContext();
5185 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005186}
5187
Douglas Gregord308e622009-05-18 20:51:54 +00005188/// \brief Perform semantic analysis for the variable declaration that
5189/// occurs within a C++ catch clause, returning the newly-created
5190/// variable.
5191VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005192 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005193 IdentifierInfo *Name,
5194 SourceLocation Loc,
5195 SourceRange Range) {
5196 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005197
5198 // Arrays and functions decay.
5199 if (ExDeclType->isArrayType())
5200 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5201 else if (ExDeclType->isFunctionType())
5202 ExDeclType = Context.getPointerType(ExDeclType);
5203
5204 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5205 // The exception-declaration shall not denote a pointer or reference to an
5206 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005207 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005208 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005209 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005210 Invalid = true;
5211 }
Douglas Gregord308e622009-05-18 20:51:54 +00005212
Douglas Gregora2762912010-03-08 01:47:36 +00005213 // GCC allows catching pointers and references to incomplete types
5214 // as an extension; so do we, but we warn by default.
5215
Sebastian Redl4b07b292008-12-22 19:15:10 +00005216 QualType BaseType = ExDeclType;
5217 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005218 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005219 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005220 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005221 BaseType = Ptr->getPointeeType();
5222 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00005223 DK = diag::ext_catch_incomplete_ptr;
5224 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005225 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005226 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005227 BaseType = Ref->getPointeeType();
5228 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00005229 DK = diag::ext_catch_incomplete_ref;
5230 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005231 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005232 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00005233 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5234 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00005235 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005236
Mike Stump1eb44332009-09-09 15:08:12 +00005237 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005238 RequireNonAbstractType(Loc, ExDeclType,
5239 diag::err_abstract_type_in_decl,
5240 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005241 Invalid = true;
5242
Mike Stump1eb44332009-09-09 15:08:12 +00005243 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005244 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005245
Douglas Gregor6d182892010-03-05 23:38:39 +00005246 if (!Invalid) {
5247 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5248 // C++ [except.handle]p16:
5249 // The object declared in an exception-declaration or, if the
5250 // exception-declaration does not specify a name, a temporary (12.2) is
5251 // copy-initialized (8.5) from the exception object. [...]
5252 // The object is destroyed when the handler exits, after the destruction
5253 // of any automatic objects initialized within the handler.
5254 //
5255 // We just pretend to initialize the object with itself, then make sure
5256 // it can be destroyed later.
5257 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5258 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5259 Loc, ExDeclType, 0);
5260 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5261 SourceLocation());
5262 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5263 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5264 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5265 if (Result.isInvalid())
5266 Invalid = true;
5267 else
5268 FinalizeVarWithDestructor(ExDecl, RecordTy);
5269 }
5270 }
5271
Douglas Gregord308e622009-05-18 20:51:54 +00005272 if (Invalid)
5273 ExDecl->setInvalidDecl();
5274
5275 return ExDecl;
5276}
5277
5278/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5279/// handler.
5280Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005281 TypeSourceInfo *TInfo = 0;
5282 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005283
5284 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005285 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005286 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005287 // The scope should be freshly made just for us. There is just no way
5288 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005289 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005290 if (PrevDecl->isTemplateParameter()) {
5291 // Maybe we will complain about the shadowed template parameter.
5292 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005293 }
5294 }
5295
Chris Lattnereaaebc72009-04-25 08:06:05 +00005296 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005297 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5298 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005299 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005300 }
5301
John McCalla93c9342009-12-07 02:54:59 +00005302 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005303 D.getIdentifier(),
5304 D.getIdentifierLoc(),
5305 D.getDeclSpec().getSourceRange());
5306
Chris Lattnereaaebc72009-04-25 08:06:05 +00005307 if (Invalid)
5308 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005309
Sebastian Redl4b07b292008-12-22 19:15:10 +00005310 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005311 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005312 PushOnScopeChains(ExDecl, S);
5313 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005314 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005315
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005316 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005317 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005318}
Anders Carlssonfb311762009-03-14 00:25:26 +00005319
Mike Stump1eb44332009-09-09 15:08:12 +00005320Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005321 ExprArg assertexpr,
5322 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005323 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005324 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005325 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5326
Anders Carlssonc3082412009-03-14 00:33:21 +00005327 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5328 llvm::APSInt Value(32);
5329 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5330 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5331 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005332 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005333 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005334
Anders Carlssonc3082412009-03-14 00:33:21 +00005335 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005336 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005337 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005338 }
5339 }
Mike Stump1eb44332009-09-09 15:08:12 +00005340
Anders Carlsson77d81422009-03-15 17:35:16 +00005341 assertexpr.release();
5342 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005343 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005344 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005345
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005346 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005347 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005348}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005349
John McCalldd4a3b02009-09-16 22:47:08 +00005350/// Handle a friend type declaration. This works in tandem with
5351/// ActOnTag.
5352///
5353/// Notes on friend class templates:
5354///
5355/// We generally treat friend class declarations as if they were
5356/// declaring a class. So, for example, the elaborated type specifier
5357/// in a friend declaration is required to obey the restrictions of a
5358/// class-head (i.e. no typedefs in the scope chain), template
5359/// parameters are required to match up with simple template-ids, &c.
5360/// However, unlike when declaring a template specialization, it's
5361/// okay to refer to a template specialization without an empty
5362/// template parameter declaration, e.g.
5363/// friend class A<T>::B<unsigned>;
5364/// We permit this as a special case; if there are any template
5365/// parameters present at all, require proper matching, i.e.
5366/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005367Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005368 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005369 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005370
5371 assert(DS.isFriendSpecified());
5372 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5373
John McCalldd4a3b02009-09-16 22:47:08 +00005374 // Try to convert the decl specifier to a type. This works for
5375 // friend templates because ActOnTag never produces a ClassTemplateDecl
5376 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005377 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005378 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5379 if (TheDeclarator.isInvalidType())
5380 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005381
John McCalldd4a3b02009-09-16 22:47:08 +00005382 // This is definitely an error in C++98. It's probably meant to
5383 // be forbidden in C++0x, too, but the specification is just
5384 // poorly written.
5385 //
5386 // The problem is with declarations like the following:
5387 // template <T> friend A<T>::foo;
5388 // where deciding whether a class C is a friend or not now hinges
5389 // on whether there exists an instantiation of A that causes
5390 // 'foo' to equal C. There are restrictions on class-heads
5391 // (which we declare (by fiat) elaborated friend declarations to
5392 // be) that makes this tractable.
5393 //
5394 // FIXME: handle "template <> friend class A<T>;", which
5395 // is possibly well-formed? Who even knows?
5396 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5397 Diag(Loc, diag::err_tagless_friend_type_template)
5398 << DS.getSourceRange();
5399 return DeclPtrTy();
5400 }
5401
John McCall02cace72009-08-28 07:59:38 +00005402 // C++ [class.friend]p2:
5403 // An elaborated-type-specifier shall be used in a friend declaration
5404 // for a class.*
5405 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005406 // This is one of the rare places in Clang where it's legitimate to
5407 // ask about the "spelling" of the type.
5408 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5409 // If we evaluated the type to a record type, suggest putting
5410 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005411 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005412 RecordDecl *RD = RT->getDecl();
5413
5414 std::string InsertionText = std::string(" ") + RD->getKindName();
5415
John McCalle3af0232009-10-07 23:34:25 +00005416 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5417 << (unsigned) RD->getTagKind()
5418 << T
5419 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005420 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5421 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005422 return DeclPtrTy();
5423 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005424 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5425 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005426 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005427 }
5428 }
5429
John McCalle3af0232009-10-07 23:34:25 +00005430 // Enum types cannot be friends.
5431 if (T->getAs<EnumType>()) {
5432 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5433 << SourceRange(DS.getFriendSpecLoc());
5434 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005435 }
John McCall02cace72009-08-28 07:59:38 +00005436
John McCall02cace72009-08-28 07:59:38 +00005437 // C++98 [class.friend]p1: A friend of a class is a function
5438 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005439 // This is fixed in DR77, which just barely didn't make the C++03
5440 // deadline. It's also a very silly restriction that seriously
5441 // affects inner classes and which nobody else seems to implement;
5442 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005443
John McCalldd4a3b02009-09-16 22:47:08 +00005444 Decl *D;
5445 if (TempParams.size())
5446 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5447 TempParams.size(),
5448 (TemplateParameterList**) TempParams.release(),
5449 T.getTypePtr(),
5450 DS.getFriendSpecLoc());
5451 else
5452 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5453 DS.getFriendSpecLoc());
5454 D->setAccess(AS_public);
5455 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005456
John McCalldd4a3b02009-09-16 22:47:08 +00005457 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005458}
5459
John McCallbbbcdd92009-09-11 21:02:39 +00005460Sema::DeclPtrTy
5461Sema::ActOnFriendFunctionDecl(Scope *S,
5462 Declarator &D,
5463 bool IsDefinition,
5464 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005465 const DeclSpec &DS = D.getDeclSpec();
5466
5467 assert(DS.isFriendSpecified());
5468 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5469
5470 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005471 TypeSourceInfo *TInfo = 0;
5472 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005473
5474 // C++ [class.friend]p1
5475 // A friend of a class is a function or class....
5476 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005477 // It *doesn't* see through dependent types, which is correct
5478 // according to [temp.arg.type]p3:
5479 // If a declaration acquires a function type through a
5480 // type dependent on a template-parameter and this causes
5481 // a declaration that does not use the syntactic form of a
5482 // function declarator to have a function type, the program
5483 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005484 if (!T->isFunctionType()) {
5485 Diag(Loc, diag::err_unexpected_friend);
5486
5487 // It might be worthwhile to try to recover by creating an
5488 // appropriate declaration.
5489 return DeclPtrTy();
5490 }
5491
5492 // C++ [namespace.memdef]p3
5493 // - If a friend declaration in a non-local class first declares a
5494 // class or function, the friend class or function is a member
5495 // of the innermost enclosing namespace.
5496 // - The name of the friend is not found by simple name lookup
5497 // until a matching declaration is provided in that namespace
5498 // scope (either before or after the class declaration granting
5499 // friendship).
5500 // - If a friend function is called, its name may be found by the
5501 // name lookup that considers functions from namespaces and
5502 // classes associated with the types of the function arguments.
5503 // - When looking for a prior declaration of a class or a function
5504 // declared as a friend, scopes outside the innermost enclosing
5505 // namespace scope are not considered.
5506
John McCall02cace72009-08-28 07:59:38 +00005507 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5508 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005509 assert(Name);
5510
John McCall67d1a672009-08-06 02:15:43 +00005511 // The context we found the declaration in, or in which we should
5512 // create the declaration.
5513 DeclContext *DC;
5514
5515 // FIXME: handle local classes
5516
5517 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005518 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5519 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005520 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005521 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005522 DC = computeDeclContext(ScopeQual);
5523
5524 // FIXME: handle dependent contexts
5525 if (!DC) return DeclPtrTy();
5526
John McCall68263142009-11-18 22:49:29 +00005527 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005528
5529 // If searching in that context implicitly found a declaration in
5530 // a different context, treat it like it wasn't found at all.
5531 // TODO: better diagnostics for this case. Suggesting the right
5532 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005533 // FIXME: getRepresentativeDecl() is not right here at all
5534 if (Previous.empty() ||
5535 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005536 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005537 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5538 return DeclPtrTy();
5539 }
5540
5541 // C++ [class.friend]p1: A friend of a class is a function or
5542 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005543 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005544 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5545
John McCall67d1a672009-08-06 02:15:43 +00005546 // Otherwise walk out to the nearest namespace scope looking for matches.
5547 } else {
5548 // TODO: handle local class contexts.
5549
5550 DC = CurContext;
5551 while (true) {
5552 // Skip class contexts. If someone can cite chapter and verse
5553 // for this behavior, that would be nice --- it's what GCC and
5554 // EDG do, and it seems like a reasonable intent, but the spec
5555 // really only says that checks for unqualified existing
5556 // declarations should stop at the nearest enclosing namespace,
5557 // not that they should only consider the nearest enclosing
5558 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005559 while (DC->isRecord())
5560 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005561
John McCall68263142009-11-18 22:49:29 +00005562 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005563
5564 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005565 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005566 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005567
John McCall67d1a672009-08-06 02:15:43 +00005568 if (DC->isFileContext()) break;
5569 DC = DC->getParent();
5570 }
5571
5572 // C++ [class.friend]p1: A friend of a class is a function or
5573 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005574 // C++0x changes this for both friend types and functions.
5575 // Most C++ 98 compilers do seem to give an error here, so
5576 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005577 if (!Previous.empty() && DC->Equals(CurContext)
5578 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005579 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5580 }
5581
Douglas Gregor182ddf02009-09-28 00:08:27 +00005582 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005583 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005584 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5585 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5586 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005587 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005588 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5589 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005590 return DeclPtrTy();
5591 }
John McCall67d1a672009-08-06 02:15:43 +00005592 }
5593
Douglas Gregor182ddf02009-09-28 00:08:27 +00005594 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005595 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005596 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005597 IsDefinition,
5598 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005599 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005600
Douglas Gregor182ddf02009-09-28 00:08:27 +00005601 assert(ND->getDeclContext() == DC);
5602 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005603
John McCallab88d972009-08-31 22:39:49 +00005604 // Add the function declaration to the appropriate lookup tables,
5605 // adjusting the redeclarations list as necessary. We don't
5606 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005607 //
John McCallab88d972009-08-31 22:39:49 +00005608 // Also update the scope-based lookup if the target context's
5609 // lookup context is in lexical scope.
5610 if (!CurContext->isDependentContext()) {
5611 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005612 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005613 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005614 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005615 }
John McCall02cace72009-08-28 07:59:38 +00005616
5617 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005618 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005619 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005620 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005621 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005622
Douglas Gregor7557a132009-12-24 20:56:24 +00005623 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5624 FrD->setSpecialization(true);
5625
Douglas Gregor182ddf02009-09-28 00:08:27 +00005626 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005627}
5628
Chris Lattnerb28317a2009-03-28 19:18:32 +00005629void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005630 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005631
Chris Lattnerb28317a2009-03-28 19:18:32 +00005632 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005633 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5634 if (!Fn) {
5635 Diag(DelLoc, diag::err_deleted_non_function);
5636 return;
5637 }
5638 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5639 Diag(DelLoc, diag::err_deleted_decl_not_first);
5640 Diag(Prev->getLocation(), diag::note_previous_declaration);
5641 // If the declaration wasn't the first, we delete the function anyway for
5642 // recovery.
5643 }
5644 Fn->setDeleted();
5645}
Sebastian Redl13e88542009-04-27 21:33:24 +00005646
5647static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5648 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5649 ++CI) {
5650 Stmt *SubStmt = *CI;
5651 if (!SubStmt)
5652 continue;
5653 if (isa<ReturnStmt>(SubStmt))
5654 Self.Diag(SubStmt->getSourceRange().getBegin(),
5655 diag::err_return_in_constructor_handler);
5656 if (!isa<Expr>(SubStmt))
5657 SearchForReturnInStmt(Self, SubStmt);
5658 }
5659}
5660
5661void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5662 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5663 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5664 SearchForReturnInStmt(*this, Handler);
5665 }
5666}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005667
Mike Stump1eb44332009-09-09 15:08:12 +00005668bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005669 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005670 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5671 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005672
Chandler Carruth73857792010-02-15 11:53:20 +00005673 if (Context.hasSameType(NewTy, OldTy) ||
5674 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005675 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005677 // Check if the return types are covariant
5678 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005679
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005680 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005681 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5682 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005683 NewClassTy = NewPT->getPointeeType();
5684 OldClassTy = OldPT->getPointeeType();
5685 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005686 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5687 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5688 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5689 NewClassTy = NewRT->getPointeeType();
5690 OldClassTy = OldRT->getPointeeType();
5691 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005692 }
5693 }
Mike Stump1eb44332009-09-09 15:08:12 +00005694
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005695 // The return types aren't either both pointers or references to a class type.
5696 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005697 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005698 diag::err_different_return_type_for_overriding_virtual_function)
5699 << New->getDeclName() << NewTy << OldTy;
5700 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005701
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005702 return true;
5703 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005704
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005705 // C++ [class.virtual]p6:
5706 // If the return type of D::f differs from the return type of B::f, the
5707 // class type in the return type of D::f shall be complete at the point of
5708 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005709 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5710 if (!RT->isBeingDefined() &&
5711 RequireCompleteType(New->getLocation(), NewClassTy,
5712 PDiag(diag::err_covariant_return_incomplete)
5713 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005714 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005715 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005716
Douglas Gregora4923eb2009-11-16 21:35:15 +00005717 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005718 // Check if the new class derives from the old class.
5719 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5720 Diag(New->getLocation(),
5721 diag::err_covariant_return_not_derived)
5722 << New->getDeclName() << NewTy << OldTy;
5723 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5724 return true;
5725 }
Mike Stump1eb44332009-09-09 15:08:12 +00005726
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005727 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005728 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005729 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5730 // FIXME: Should this point to the return type?
5731 New->getLocation(), SourceRange(), New->getDeclName())) {
5732 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5733 return true;
5734 }
5735 }
Mike Stump1eb44332009-09-09 15:08:12 +00005736
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005737 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005738 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005739 Diag(New->getLocation(),
5740 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005741 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005742 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5743 return true;
5744 };
Mike Stump1eb44332009-09-09 15:08:12 +00005745
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005746
5747 // The new class type must have the same or less qualifiers as the old type.
5748 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5749 Diag(New->getLocation(),
5750 diag::err_covariant_return_type_class_type_more_qualified)
5751 << New->getDeclName() << NewTy << OldTy;
5752 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5753 return true;
5754 };
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005756 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005757}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005758
Sean Huntbbd37c62009-11-21 08:43:09 +00005759bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5760 const CXXMethodDecl *Old)
5761{
5762 if (Old->hasAttr<FinalAttr>()) {
5763 Diag(New->getLocation(), diag::err_final_function_overridden)
5764 << New->getDeclName();
5765 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5766 return true;
5767 }
5768
5769 return false;
5770}
5771
Douglas Gregor4ba31362009-12-01 17:24:26 +00005772/// \brief Mark the given method pure.
5773///
5774/// \param Method the method to be marked pure.
5775///
5776/// \param InitRange the source range that covers the "0" initializer.
5777bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5778 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5779 Method->setPure();
5780
5781 // A class is abstract if at least one function is pure virtual.
5782 Method->getParent()->setAbstract(true);
5783 return false;
5784 }
5785
5786 if (!Method->isInvalidDecl())
5787 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5788 << Method->getDeclName() << InitRange;
5789 return true;
5790}
5791
John McCall731ad842009-12-19 09:28:58 +00005792/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5793/// an initializer for the out-of-line declaration 'Dcl'. The scope
5794/// is a fresh scope pushed for just this purpose.
5795///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005796/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5797/// static data member of class X, names should be looked up in the scope of
5798/// class X.
5799void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005800 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005801 Decl *D = Dcl.getAs<Decl>();
5802 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005803
John McCall731ad842009-12-19 09:28:58 +00005804 // We should only get called for declarations with scope specifiers, like:
5805 // int foo::bar;
5806 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005807 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005808}
5809
5810/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005811/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005812void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005813 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005814 Decl *D = Dcl.getAs<Decl>();
5815 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005816
John McCall731ad842009-12-19 09:28:58 +00005817 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005818 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005819}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005820
5821/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5822/// C++ if/switch/while/for statement.
5823/// e.g: "if (int x = f()) {...}"
5824Action::DeclResult
5825Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5826 // C++ 6.4p2:
5827 // The declarator shall not specify a function or an array.
5828 // The type-specifier-seq shall not contain typedef and shall not declare a
5829 // new class or enumeration.
5830 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5831 "Parser allowed 'typedef' as storage class of condition decl.");
5832
John McCalla93c9342009-12-07 02:54:59 +00005833 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005834 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005835 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005836
5837 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5838 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5839 // would be created and CXXConditionDeclExpr wants a VarDecl.
5840 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5841 << D.getSourceRange();
5842 return DeclResult();
5843 } else if (OwnedTag && OwnedTag->isDefinition()) {
5844 // The type-specifier-seq shall not declare a new class or enumeration.
5845 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5846 }
5847
5848 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5849 if (!Dcl)
5850 return DeclResult();
5851
5852 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5853 VD->setDeclaredInCondition(true);
5854 return Dcl;
5855}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005856
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005857static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005858 // Ignore dependent types.
5859 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005860 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005861
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005862 // Ignore declarations that are not definitions.
5863 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005864 return false;
5865
5866 CXXRecordDecl *RD = MD->getParent();
5867
5868 // Ignore classes without a vtable.
5869 if (!RD->isDynamicClass())
5870 return false;
5871
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 break;
5879
5880 case TSK_ImplicitInstantiation:
5881 // This is a constructor of a class template; mark all of the virtual
5882 // members as referenced to ensure that they get instantiatied.
5883 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5884 return true;
5885 break;
5886
5887 case TSK_ExplicitInstantiationDeclaration:
5888 return true; //FIXME: This looks wrong.
5889
5890 case TSK_ExplicitInstantiationDefinition:
5891 // This is method of a explicit instantiation; mark all of the virtual
5892 // members as referenced to ensure that they get instantiatied.
5893 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005894 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005895
5896 // Consider only out-of-line definitions of member functions. When we see
5897 // an inline definition, it's too early to compute the key function.
5898 if (!MD->isOutOfLine())
5899 return false;
5900
5901 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5902
5903 // If there is no key function, we will need a copy of the vtable.
5904 if (!KeyFunction)
5905 return true;
5906
5907 // If this is the key function, we need to mark virtual members.
5908 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5909 return true;
5910
5911 return false;
5912}
5913
5914void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5915 CXXMethodDecl *MD) {
5916 CXXRecordDecl *RD = MD->getParent();
5917
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005918 // We will need to mark all of the virtual members as referenced to build the
5919 // vtable.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005920 if (!needsVtable(MD, Context))
5921 return;
5922
5923 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5924 if (kind == TSK_ImplicitInstantiation)
5925 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5926 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005927 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005928}
5929
5930bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5931 if (ClassesWithUnmarkedVirtualMembers.empty())
5932 return false;
5933
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005934 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5935 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5936 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5937 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005938 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005939 }
5940
Anders Carlssond6a637f2009-12-07 08:24:59 +00005941 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005942}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005943
5944void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5945 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5946 e = RD->method_end(); i != e; ++i) {
5947 CXXMethodDecl *MD = *i;
5948
5949 // C++ [basic.def.odr]p2:
5950 // [...] A virtual member function is used if it is not pure. [...]
5951 if (MD->isVirtual() && !MD->isPure())
5952 MarkDeclarationReferenced(Loc, MD);
5953 }
5954}