blob: e694cb470c252df0e5be91f3144829d8bd842b21 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
Douglas Gregord85cef52009-09-17 19:51:30 +0000301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000356 }
357 }
358
Douglas Gregore13ad832010-02-12 07:32:17 +0000359 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000360 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361
Douglas Gregorcda9c672009-02-16 17:45:42 +0000362 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000363}
364
365/// CheckCXXDefaultArguments - Verify that the default arguments for a
366/// function declaration are well-formed according to C++
367/// [dcl.fct.default].
368void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
369 unsigned NumParams = FD->getNumParams();
370 unsigned p;
371
372 // Find first parameter with a default argument
373 for (p = 0; p < NumParams; ++p) {
374 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000375 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376 break;
377 }
378
379 // C++ [dcl.fct.default]p4:
380 // In a given function declaration, all parameters
381 // subsequent to a parameter with a default argument shall
382 // have default arguments supplied in this or previous
383 // declarations. A default argument shall not be redefined
384 // by a later declaration (not even to the same value).
385 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000386 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000387 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000388 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000389 if (Param->isInvalidDecl())
390 /* We already complained about this parameter. */;
391 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000392 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000394 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000395 else
Mike Stump1eb44332009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 LastMissingDefaultArg = p;
400 }
401 }
402
403 if (LastMissingDefaultArg > 0) {
404 // Some default arguments were missing. Clear out all of the
405 // default arguments up to (and including) the last missing
406 // default argument, so that we leave the function parameters
407 // in a semantically valid state.
408 for (p = 0; p <= LastMissingDefaultArg; ++p) {
409 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000410 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000411 if (!Param->hasUnparsedDefaultArg())
412 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000413 Param->setDefaultArg(0);
414 }
415 }
416 }
417}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000418
Douglas Gregorb48fe382008-10-31 09:07:45 +0000419/// isCurrentClassName - Determine whether the identifier II is the
420/// name of the class type currently being defined. In the case of
421/// nested classes, this will only return true if II is the name of
422/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000423bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
424 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000425 assert(getLangOptions().CPlusPlus && "No class names in C!");
426
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000434 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000448 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000449 SourceLocation BaseLoc) {
450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 Class->getTagKind() == RecordDecl::TK_class,
461 Access, BaseType);
462
463 // Base specifiers must be record types.
464 if (!BaseType->isRecordType()) {
465 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466 return 0;
467 }
468
469 // C++ [class.union]p1:
470 // A union shall not be used as a base class.
471 if (BaseType->isUnionType()) {
472 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473 return 0;
474 }
475
476 // C++ [class.derived]p2:
477 // The class-name in a base-specifier shall not be an incompletely
478 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000479 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000480 PDiag(diag::err_incomplete_base_class)
481 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 return 0;
483
Eli Friedman1d954f62009-08-15 21:55:26 +0000484 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000485 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000487 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000489 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000491
Sean Huntbbd37c62009-11-21 08:43:09 +0000492 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000495 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000497 return 0;
498 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000499
Eli Friedmand0137332009-12-05 23:03:49 +0000500 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000501
502 // Create the base specifier.
503 // FIXME: Allocate via ASTContext?
504 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505 Class->getTagKind() == RecordDecl::TK_class,
506 Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510 const CXXRecordDecl *BaseClass,
511 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000512 // A class with a non-empty base class is not empty.
513 // FIXME: Standard ref?
514 if (!BaseClass->isEmpty())
515 Class->setEmpty(false);
516
517 // C++ [class.virtual]p1:
518 // A class that [...] inherits a virtual function is called a polymorphic
519 // class.
520 if (BaseClass->isPolymorphic())
521 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000522
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is [...] a class with [...] no base classes [...].
525 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000526
527 // C++ [class]p4:
528 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 Class->setPOD(false);
530
Anders Carlsson51f94042009-12-03 17:49:57 +0000531 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000532 // C++ [class.ctor]p5:
533 // A constructor is trivial if its class has no virtual base classes.
534 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000535
536 // C++ [class.copy]p6:
537 // A copy constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialCopyConstructor(false);
539
540 // C++ [class.copy]p11:
541 // A copy assignment operator is trivial if its class has no virtual
542 // base classes.
543 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000544
545 // C++0x [meta.unary.prop] is_empty:
546 // T is a class type, but not a union type, with ... no virtual base
547 // classes
548 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000549 } else {
550 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000551 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000552 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000553 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000554 Class->setHasTrivialConstructor(false);
555
556 // C++ [class.copy]p6:
557 // A copy constructor is trivial if all the direct base classes of its
558 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialCopyConstructor(false);
561
562 // C++ [class.copy]p11:
563 // A copy assignment operator is trivial if all the direct base classes
564 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000567 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000568
569 // C++ [class.ctor]p3:
570 // A destructor is trivial if all the direct base classes of its class
571 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000572 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000573 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000574}
575
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000578/// example:
579/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000580/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000581Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000583 bool Virtual, AccessSpecifier Access,
584 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000585 if (!classdecl)
586 return true;
587
Douglas Gregor40808ce2009-03-09 23:48:35 +0000588 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000589 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
590 if (!Class)
591 return true;
592
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000593 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000594 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
595 Virtual, Access,
596 BaseType, BaseLoc))
597 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000600}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000601
Douglas Gregor2943aed2009-03-03 04:44:36 +0000602/// \brief Performs the actual work of attaching the given base class
603/// specifiers to a C++ class.
604bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
605 unsigned NumBases) {
606 if (NumBases == 0)
607 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000608
609 // Used to keep track of which base types we have already seen, so
610 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000611 // that the key is always the unqualified canonical type of the base
612 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000613 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
614
615 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000616 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000618 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000619 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000620 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000621 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000622
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000623 if (KnownBaseTypes[NewBaseType]) {
624 // C++ [class.mi]p3:
625 // A class shall not be specified as a direct base class of a
626 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000628 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000629 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000630 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000631
632 // Delete the duplicate base class specifier; we're going to
633 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000634 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000635
636 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000637 } else {
638 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 KnownBaseTypes[NewBaseType] = Bases[idx];
640 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000641 }
642 }
643
644 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000645 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000646
647 // Delete the remaining (good) base class specifiers, since their
648 // data has been copied into the CXXRecordDecl.
649 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000650 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651
652 return Invalid;
653}
654
655/// ActOnBaseSpecifiers - Attach the given base specifiers to the
656/// class, after checking whether there are any duplicate base
657/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000658void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000659 unsigned NumBases) {
660 if (!ClassDecl || !Bases || !NumBases)
661 return;
662
663 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000664 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000665 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000666}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000667
John McCall3cb0ebd2010-03-10 03:28:59 +0000668static CXXRecordDecl *GetClassForType(QualType T) {
669 if (const RecordType *RT = T->getAs<RecordType>())
670 return cast<CXXRecordDecl>(RT->getDecl());
671 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
672 return ICT->getDecl();
673 else
674 return 0;
675}
676
Douglas Gregora8f32e02009-10-06 17:59:45 +0000677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
680 if (!getLangOptions().CPlusPlus)
681 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000682
683 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000685 return false;
686
John McCall3cb0ebd2010-03-10 03:28:59 +0000687 CXXRecordDecl *BaseRD = GetClassForType(Base);
688 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689 return false;
690
John McCall86ff3082010-02-04 22:26:26 +0000691 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
692 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000693}
694
695/// \brief Determine whether the type \p Derived is a C++ class that is
696/// derived from the type \p Base.
697bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
698 if (!getLangOptions().CPlusPlus)
699 return false;
700
John McCall3cb0ebd2010-03-10 03:28:59 +0000701 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
702 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000703 return false;
704
John McCall3cb0ebd2010-03-10 03:28:59 +0000705 CXXRecordDecl *BaseRD = GetClassForType(Base);
706 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000707 return false;
708
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709 return DerivedRD->isDerivedFrom(BaseRD, Paths);
710}
711
712/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
713/// conversion (where Derived and Base are class types) is
714/// well-formed, meaning that the conversion is unambiguous (and
715/// that all of the base classes are accessible). Returns true
716/// and emits a diagnostic if the code is ill-formed, returns false
717/// otherwise. Loc is the location where this routine should point to
718/// if there is an error, and Range is the source range to highlight
719/// if there is an error.
720bool
721Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000722 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000723 unsigned AmbigiousBaseConvID,
724 SourceLocation Loc, SourceRange Range,
725 DeclarationName Name) {
726 // First, determine whether the path from Derived to Base is
727 // ambiguous. This is slightly more expensive than checking whether
728 // the Derived to Base conversion exists, because here we need to
729 // explore multiple paths to determine if there is an ambiguity.
730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
731 /*DetectVirtual=*/false);
732 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
733 assert(DerivationOkay &&
734 "Can only be used with a derived-to-base conversion");
735 (void)DerivationOkay;
736
737 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000738 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000739 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000740
Douglas Gregora8f32e02009-10-06 17:59:45 +0000741 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000742 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
743 Base, Derived, Paths.front(),
744 /*force*/ false,
745 /*unprivileged*/ false,
746 ADK)) {
747 case AR_accessible: return false;
748 case AR_inaccessible: return true;
749 case AR_dependent: return false;
750 case AR_delayed: return false;
751 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000752 }
753
754 // We know that the derived-to-base conversion is ambiguous, and
755 // we're going to produce a diagnostic. Perform the derived-to-base
756 // search just one more time to compute all of the possible paths so
757 // that we can print them out. This is more expensive than any of
758 // the previous derived-to-base checks we've done, but at this point
759 // performance isn't as much of an issue.
760 Paths.clear();
761 Paths.setRecordingPaths(true);
762 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
763 assert(StillOkay && "Can only be used with a derived-to-base conversion");
764 (void)StillOkay;
765
766 // Build up a textual representation of the ambiguous paths, e.g.,
767 // D -> B -> A, that will be used to illustrate the ambiguous
768 // conversions in the diagnostic. We only print one of the paths
769 // to each base class subobject.
770 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
771
772 Diag(Loc, AmbigiousBaseConvID)
773 << Derived << Base << PathDisplayStr << Range << Name;
774 return true;
775}
776
777bool
778Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000779 SourceLocation Loc, SourceRange Range,
780 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000781 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000782 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000783 diag::err_ambiguous_derived_to_base_conv,
784 Loc, Range, DeclarationName());
785}
786
787
788/// @brief Builds a string representing ambiguous paths from a
789/// specific derived class to different subobjects of the same base
790/// class.
791///
792/// This function builds a string that can be used in error messages
793/// to show the different paths that one can take through the
794/// inheritance hierarchy to go from the derived class to different
795/// subobjects of a base class. The result looks something like this:
796/// @code
797/// struct D -> struct B -> struct A
798/// struct D -> struct C -> struct A
799/// @endcode
800std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
801 std::string PathDisplayStr;
802 std::set<unsigned> DisplayedPaths;
803 for (CXXBasePaths::paths_iterator Path = Paths.begin();
804 Path != Paths.end(); ++Path) {
805 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
806 // We haven't displayed a path to this particular base
807 // class subobject yet.
808 PathDisplayStr += "\n ";
809 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
810 for (CXXBasePath::const_iterator Element = Path->begin();
811 Element != Path->end(); ++Element)
812 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
813 }
814 }
815
816 return PathDisplayStr;
817}
818
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000819//===----------------------------------------------------------------------===//
820// C++ class member Handling
821//===----------------------------------------------------------------------===//
822
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000823/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
824/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
825/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000826/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000827Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000828Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000829 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000830 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
831 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000832 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000833 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000834 Expr *BitWidth = static_cast<Expr*>(BW);
835 Expr *Init = static_cast<Expr*>(InitExpr);
836 SourceLocation Loc = D.getIdentifierLoc();
837
Sebastian Redl669d5d72008-11-14 23:42:31 +0000838 bool isFunc = D.isFunctionDeclarator();
839
John McCall67d1a672009-08-06 02:15:43 +0000840 assert(!DS.isFriendSpecified());
841
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 // C++ 9.2p6: A member shall not be declared to have automatic storage
843 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000844 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
845 // data members and cannot be applied to names declared const or static,
846 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000847 switch (DS.getStorageClassSpec()) {
848 case DeclSpec::SCS_unspecified:
849 case DeclSpec::SCS_typedef:
850 case DeclSpec::SCS_static:
851 // FALL THROUGH.
852 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000853 case DeclSpec::SCS_mutable:
854 if (isFunc) {
855 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000856 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000858 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Sebastian Redla11f42f2008-11-17 23:24:37 +0000860 // FIXME: It would be nicer if the keyword was ignored only for this
861 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000862 D.getMutableDeclSpec().ClearStorageClassSpecs();
863 } else {
864 QualType T = GetTypeForDeclarator(D, S);
865 diag::kind err = static_cast<diag::kind>(0);
866 if (T->isReferenceType())
867 err = diag::err_mutable_reference;
868 else if (T.isConstQualified())
869 err = diag::err_mutable_const;
870 if (err != 0) {
871 if (DS.getStorageClassSpecLoc().isValid())
872 Diag(DS.getStorageClassSpecLoc(), err);
873 else
874 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000875 // FIXME: It would be nicer if the keyword was ignored only for this
876 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000877 D.getMutableDeclSpec().ClearStorageClassSpecs();
878 }
879 }
880 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000881 default:
882 if (DS.getStorageClassSpecLoc().isValid())
883 Diag(DS.getStorageClassSpecLoc(),
884 diag::err_storageclass_invalid_for_member);
885 else
886 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
887 D.getMutableDeclSpec().ClearStorageClassSpecs();
888 }
889
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000890 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000891 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000892 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000893 // Check also for this case:
894 //
895 // typedef int f();
896 // f a;
897 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000898 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000899 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000900 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901
Sebastian Redl669d5d72008-11-14 23:42:31 +0000902 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
903 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000904 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000905
906 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000907 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000908 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000909 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
910 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000911 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000912 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000913 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000914 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000915 if (!Member) {
916 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000917 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000918 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000919
920 // Non-instance-fields can't have a bitfield.
921 if (BitWidth) {
922 if (Member->isInvalidDecl()) {
923 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000924 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000925 // C++ 9.6p3: A bit-field shall not be a static member.
926 // "static member 'A' cannot be a bit-field"
927 Diag(Loc, diag::err_static_not_bitfield)
928 << Name << BitWidth->getSourceRange();
929 } else if (isa<TypedefDecl>(Member)) {
930 // "typedef member 'x' cannot be a bit-field"
931 Diag(Loc, diag::err_typedef_not_bitfield)
932 << Name << BitWidth->getSourceRange();
933 } else {
934 // A function typedef ("typedef int f(); f a;").
935 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
936 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000937 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000938 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000939 }
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Chris Lattner8b963ef2009-03-05 23:01:03 +0000941 DeleteExpr(BitWidth);
942 BitWidth = 0;
943 Member->setInvalidDecl();
944 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000945
946 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor37b372b2009-08-20 22:52:58 +0000948 // If we have declared a member function template, set the access of the
949 // templated declaration as well.
950 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
951 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000952 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000953
Douglas Gregor10bd3682008-11-17 22:58:34 +0000954 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955
Douglas Gregor021c3b32009-03-11 23:00:04 +0000956 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000957 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000958 if (Deleted) // FIXME: Source location is not very good.
959 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000960
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000962 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000963 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000964 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000965 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000966}
967
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000968/// \brief Find the direct and/or virtual base specifiers that
969/// correspond to the given base type, for use in base initialization
970/// within a constructor.
971static bool FindBaseInitializer(Sema &SemaRef,
972 CXXRecordDecl *ClassDecl,
973 QualType BaseType,
974 const CXXBaseSpecifier *&DirectBaseSpec,
975 const CXXBaseSpecifier *&VirtualBaseSpec) {
976 // First, check for a direct base class.
977 DirectBaseSpec = 0;
978 for (CXXRecordDecl::base_class_const_iterator Base
979 = ClassDecl->bases_begin();
980 Base != ClassDecl->bases_end(); ++Base) {
981 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
982 // We found a direct base of this type. That's what we're
983 // initializing.
984 DirectBaseSpec = &*Base;
985 break;
986 }
987 }
988
989 // Check for a virtual base class.
990 // FIXME: We might be able to short-circuit this if we know in advance that
991 // there are no virtual bases.
992 VirtualBaseSpec = 0;
993 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
994 // We haven't found a base yet; search the class hierarchy for a
995 // virtual base class.
996 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
997 /*DetectVirtual=*/false);
998 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
999 BaseType, Paths)) {
1000 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1001 Path != Paths.end(); ++Path) {
1002 if (Path->back().Base->isVirtual()) {
1003 VirtualBaseSpec = Path->back().Base;
1004 break;
1005 }
1006 }
1007 }
1008 }
1009
1010 return DirectBaseSpec || VirtualBaseSpec;
1011}
1012
Douglas Gregor7ad83902008-11-05 04:29:56 +00001013/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001014Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001015Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001016 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001017 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001018 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001019 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001020 SourceLocation IdLoc,
1021 SourceLocation LParenLoc,
1022 ExprTy **Args, unsigned NumArgs,
1023 SourceLocation *CommaLocs,
1024 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001025 if (!ConstructorD)
1026 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001028 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
1030 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001031 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001032 if (!Constructor) {
1033 // The user wrote a constructor initializer on a function that is
1034 // not a C++ constructor. Ignore the error for now, because we may
1035 // have more member initializers coming; we'll diagnose it just
1036 // once in ActOnMemInitializers.
1037 return true;
1038 }
1039
1040 CXXRecordDecl *ClassDecl = Constructor->getParent();
1041
1042 // C++ [class.base.init]p2:
1043 // Names in a mem-initializer-id are looked up in the scope of the
1044 // constructor’s class and, if not found in that scope, are looked
1045 // up in the scope containing the constructor’s
1046 // definition. [Note: if the constructor’s class contains a member
1047 // with the same name as a direct or virtual base class of the
1048 // class, a mem-initializer-id naming the member or base class and
1049 // composed of a single identifier refers to the class member. A
1050 // mem-initializer-id for the hidden base class may be specified
1051 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001052 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001053 // Look for a member, first.
1054 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001055 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001056 = ClassDecl->lookup(MemberOrBase);
1057 if (Result.first != Result.second)
1058 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001059
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001060 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061
Eli Friedman59c04372009-07-29 19:44:27 +00001062 if (Member)
1063 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001064 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001065 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001066 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001067 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001068 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001069
1070 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001071 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001072 } else {
1073 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1074 LookupParsedName(R, S, &SS);
1075
1076 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1077 if (!TyD) {
1078 if (R.isAmbiguous()) return true;
1079
Douglas Gregor7a886e12010-01-19 06:46:48 +00001080 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1081 bool NotUnknownSpecialization = false;
1082 DeclContext *DC = computeDeclContext(SS, false);
1083 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1084 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1085
1086 if (!NotUnknownSpecialization) {
1087 // When the scope specifier can refer to a member of an unknown
1088 // specialization, we take it as a type name.
1089 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1090 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001091 if (BaseType.isNull())
1092 return true;
1093
Douglas Gregor7a886e12010-01-19 06:46:48 +00001094 R.clear();
1095 }
1096 }
1097
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001098 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001099 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001100 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1101 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1102 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1103 // We have found a non-static data member with a similar
1104 // name to what was typed; complain and initialize that
1105 // member.
1106 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1107 << MemberOrBase << true << R.getLookupName()
1108 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1109 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001110 Diag(Member->getLocation(), diag::note_previous_decl)
1111 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001112
1113 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1114 LParenLoc, RParenLoc);
1115 }
1116 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1117 const CXXBaseSpecifier *DirectBaseSpec;
1118 const CXXBaseSpecifier *VirtualBaseSpec;
1119 if (FindBaseInitializer(*this, ClassDecl,
1120 Context.getTypeDeclType(Type),
1121 DirectBaseSpec, VirtualBaseSpec)) {
1122 // We have found a direct or virtual base class with a
1123 // similar name to what was typed; complain and initialize
1124 // that base class.
1125 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1126 << MemberOrBase << false << R.getLookupName()
1127 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1128 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001129
1130 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1131 : VirtualBaseSpec;
1132 Diag(BaseSpec->getSourceRange().getBegin(),
1133 diag::note_base_class_specified_here)
1134 << BaseSpec->getType()
1135 << BaseSpec->getSourceRange();
1136
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001137 TyD = Type;
1138 }
1139 }
1140 }
1141
Douglas Gregor7a886e12010-01-19 06:46:48 +00001142 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001143 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1144 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1145 return true;
1146 }
John McCall2b194412009-12-21 10:41:20 +00001147 }
1148
Douglas Gregor7a886e12010-01-19 06:46:48 +00001149 if (BaseType.isNull()) {
1150 BaseType = Context.getTypeDeclType(TyD);
1151 if (SS.isSet()) {
1152 NestedNameSpecifier *Qualifier =
1153 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001154
Douglas Gregor7a886e12010-01-19 06:46:48 +00001155 // FIXME: preserve source range information
1156 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1157 }
John McCall2b194412009-12-21 10:41:20 +00001158 }
1159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCalla93c9342009-12-07 02:54:59 +00001161 if (!TInfo)
1162 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001163
John McCalla93c9342009-12-07 02:54:59 +00001164 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001165 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001166}
1167
John McCallb4190042009-11-04 23:02:40 +00001168/// Checks an initializer expression for use of uninitialized fields, such as
1169/// containing the field that is being initialized. Returns true if there is an
1170/// uninitialized field was used an updates the SourceLocation parameter; false
1171/// otherwise.
1172static bool InitExprContainsUninitializedFields(const Stmt* S,
1173 const FieldDecl* LhsField,
1174 SourceLocation* L) {
1175 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1176 if (ME) {
1177 const NamedDecl* RhsField = ME->getMemberDecl();
1178 if (RhsField == LhsField) {
1179 // Initializing a field with itself. Throw a warning.
1180 // But wait; there are exceptions!
1181 // Exception #1: The field may not belong to this record.
1182 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1183 const Expr* base = ME->getBase();
1184 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1185 // Even though the field matches, it does not belong to this record.
1186 return false;
1187 }
1188 // None of the exceptions triggered; return true to indicate an
1189 // uninitialized field was used.
1190 *L = ME->getMemberLoc();
1191 return true;
1192 }
1193 }
1194 bool found = false;
1195 for (Stmt::const_child_iterator it = S->child_begin();
1196 it != S->child_end() && found == false;
1197 ++it) {
1198 if (isa<CallExpr>(S)) {
1199 // Do not descend into function calls or constructors, as the use
1200 // of an uninitialized field may be valid. One would have to inspect
1201 // the contents of the function/ctor to determine if it is safe or not.
1202 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1203 // may be safe, depending on what the function/ctor does.
1204 continue;
1205 }
1206 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1207 }
1208 return found;
1209}
1210
Eli Friedman59c04372009-07-29 19:44:27 +00001211Sema::MemInitResult
1212Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1213 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001214 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001215 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001216 // Diagnose value-uses of fields to initialize themselves, e.g.
1217 // foo(foo)
1218 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001219 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001220 for (unsigned i = 0; i < NumArgs; ++i) {
1221 SourceLocation L;
1222 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1223 // FIXME: Return true in the case when other fields are used before being
1224 // uninitialized. For example, let this field be the i'th field. When
1225 // initializing the i'th field, throw a warning if any of the >= i'th
1226 // fields are used, as they are not yet initialized.
1227 // Right now we are only handling the case where the i'th field uses
1228 // itself in its initializer.
1229 Diag(L, diag::warn_field_is_uninit);
1230 }
1231 }
1232
Eli Friedman59c04372009-07-29 19:44:27 +00001233 bool HasDependentArg = false;
1234 for (unsigned i = 0; i < NumArgs; i++)
1235 HasDependentArg |= Args[i]->isTypeDependent();
1236
Eli Friedman59c04372009-07-29 19:44:27 +00001237 QualType FieldType = Member->getType();
1238 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1239 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001240 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001241 if (FieldType->isDependentType() || HasDependentArg) {
1242 // Can't check initialization for a member of dependent type or when
1243 // any of the arguments are type-dependent expressions.
1244 OwningExprResult Init
1245 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1246 RParenLoc));
1247
1248 // Erase any temporaries within this evaluation context; we're not
1249 // going to track them in the AST, since we'll be rebuilding the
1250 // ASTs during template instantiation.
1251 ExprTemporaries.erase(
1252 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1253 ExprTemporaries.end());
1254
1255 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1256 LParenLoc,
1257 Init.takeAs<Expr>(),
1258 RParenLoc);
1259
Douglas Gregor7ad83902008-11-05 04:29:56 +00001260 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001261
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001262 if (Member->isInvalidDecl())
1263 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001264
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001265 // Initialize the member.
1266 InitializedEntity MemberEntity =
1267 InitializedEntity::InitializeMember(Member, 0);
1268 InitializationKind Kind =
1269 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1270
1271 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1272
1273 OwningExprResult MemberInit =
1274 InitSeq.Perform(*this, MemberEntity, Kind,
1275 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1276 if (MemberInit.isInvalid())
1277 return true;
1278
1279 // C++0x [class.base.init]p7:
1280 // The initialization of each base and member constitutes a
1281 // full-expression.
1282 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1283 if (MemberInit.isInvalid())
1284 return true;
1285
1286 // If we are in a dependent context, template instantiation will
1287 // perform this type-checking again. Just save the arguments that we
1288 // received in a ParenListExpr.
1289 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1290 // of the information that we have about the member
1291 // initializer. However, deconstructing the ASTs is a dicey process,
1292 // and this approach is far more likely to get the corner cases right.
1293 if (CurContext->isDependentContext()) {
1294 // Bump the reference count of all of the arguments.
1295 for (unsigned I = 0; I != NumArgs; ++I)
1296 Args[I]->Retain();
1297
1298 OwningExprResult Init
1299 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1300 RParenLoc));
1301 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1302 LParenLoc,
1303 Init.takeAs<Expr>(),
1304 RParenLoc);
1305 }
1306
Douglas Gregor802ab452009-12-02 22:36:29 +00001307 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001308 LParenLoc,
1309 MemberInit.takeAs<Expr>(),
1310 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001311}
1312
1313Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001314Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001315 Expr **Args, unsigned NumArgs,
1316 SourceLocation LParenLoc, SourceLocation RParenLoc,
1317 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001318 bool HasDependentArg = false;
1319 for (unsigned i = 0; i < NumArgs; i++)
1320 HasDependentArg |= Args[i]->isTypeDependent();
1321
John McCalla93c9342009-12-07 02:54:59 +00001322 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001323 if (BaseType->isDependentType() || HasDependentArg) {
1324 // Can't check initialization for a base of dependent type or when
1325 // any of the arguments are type-dependent expressions.
1326 OwningExprResult BaseInit
1327 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1328 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001329
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001330 // Erase any temporaries within this evaluation context; we're not
1331 // going to track them in the AST, since we'll be rebuilding the
1332 // ASTs during template instantiation.
1333 ExprTemporaries.erase(
1334 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1335 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001337 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1338 LParenLoc,
1339 BaseInit.takeAs<Expr>(),
1340 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001341 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001342
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001343 if (!BaseType->isRecordType())
1344 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1345 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1346
1347 // C++ [class.base.init]p2:
1348 // [...] Unless the mem-initializer-id names a nonstatic data
1349 // member of the constructor’s class or a direct or virtual base
1350 // of that class, the mem-initializer is ill-formed. A
1351 // mem-initializer-list can initialize a base class using any
1352 // name that denotes that base class type.
1353
1354 // Check for direct and virtual base classes.
1355 const CXXBaseSpecifier *DirectBaseSpec = 0;
1356 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1357 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1358 VirtualBaseSpec);
1359
1360 // C++ [base.class.init]p2:
1361 // If a mem-initializer-id is ambiguous because it designates both
1362 // a direct non-virtual base class and an inherited virtual base
1363 // class, the mem-initializer is ill-formed.
1364 if (DirectBaseSpec && VirtualBaseSpec)
1365 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1366 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1367 // C++ [base.class.init]p2:
1368 // Unless the mem-initializer-id names a nonstatic data membeer of the
1369 // constructor's class ot a direst or virtual base of that class, the
1370 // mem-initializer is ill-formed.
1371 if (!DirectBaseSpec && !VirtualBaseSpec)
1372 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1373 << BaseType << ClassDecl->getNameAsCString()
1374 << BaseTInfo->getTypeLoc().getSourceRange();
1375
1376 CXXBaseSpecifier *BaseSpec
1377 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1378 if (!BaseSpec)
1379 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1380
1381 // Initialize the base.
1382 InitializedEntity BaseEntity =
1383 InitializedEntity::InitializeBase(Context, BaseSpec);
1384 InitializationKind Kind =
1385 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1386
1387 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1388
1389 OwningExprResult BaseInit =
1390 InitSeq.Perform(*this, BaseEntity, Kind,
1391 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1392 if (BaseInit.isInvalid())
1393 return true;
1394
1395 // C++0x [class.base.init]p7:
1396 // The initialization of each base and member constitutes a
1397 // full-expression.
1398 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1399 if (BaseInit.isInvalid())
1400 return true;
1401
1402 // If we are in a dependent context, template instantiation will
1403 // perform this type-checking again. Just save the arguments that we
1404 // received in a ParenListExpr.
1405 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1406 // of the information that we have about the base
1407 // initializer. However, deconstructing the ASTs is a dicey process,
1408 // and this approach is far more likely to get the corner cases right.
1409 if (CurContext->isDependentContext()) {
1410 // Bump the reference count of all of the arguments.
1411 for (unsigned I = 0; I != NumArgs; ++I)
1412 Args[I]->Retain();
1413
1414 OwningExprResult Init
1415 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1416 RParenLoc));
1417 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1418 LParenLoc,
1419 Init.takeAs<Expr>(),
1420 RParenLoc);
1421 }
1422
1423 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1424 LParenLoc,
1425 BaseInit.takeAs<Expr>(),
1426 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001427}
1428
Eli Friedman80c30da2009-11-09 19:20:36 +00001429bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001430Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001431 CXXBaseOrMemberInitializer **Initializers,
1432 unsigned NumInitializers,
1433 bool IsImplicitConstructor,
1434 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 // We need to build the initializer AST according to order of construction
1436 // and not what user specified in the Initializers list.
1437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1438 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1439 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1440 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001441 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001443 for (unsigned i = 0; i < NumInitializers; i++) {
1444 CXXBaseOrMemberInitializer *Member = Initializers[i];
1445 if (Member->isBaseInitializer()) {
1446 if (Member->getBaseClass()->isDependentType())
1447 HasDependentBaseInit = true;
1448 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1449 } else {
1450 AllBaseFields[Member->getMember()] = Member;
1451 }
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001454 if (HasDependentBaseInit) {
1455 // FIXME. This does not preserve the ordering of the initializers.
1456 // Try (with -Wreorder)
1457 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // template<class X> struct B : A<X> {
1459 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 // int x1;
1461 // };
1462 // B<int> x;
1463 // On seeing one dependent type, we should essentially exit this routine
1464 // while preserving user-declared initializer list. When this routine is
1465 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001466 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001468 // If we have a dependent base initialization, we can't determine the
1469 // association between initializers and bases; just dump the known
1470 // initializers into the list, and don't try to deal with other bases.
1471 for (unsigned i = 0; i < NumInitializers; i++) {
1472 CXXBaseOrMemberInitializer *Member = Initializers[i];
1473 if (Member->isBaseInitializer())
1474 AllToInit.push_back(Member);
1475 }
1476 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1478
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001479 // Push virtual bases before others.
1480 for (CXXRecordDecl::base_class_iterator VBase =
1481 ClassDecl->vbases_begin(),
1482 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1483 if (VBase->getType()->isDependentType())
1484 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001485 if (CXXBaseOrMemberInitializer *Value
1486 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001487 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001488 } else if (!AnyErrors) {
1489 InitializedEntity InitEntity
1490 = InitializedEntity::InitializeBase(Context, VBase);
1491 InitializationKind InitKind
1492 = InitializationKind::CreateDefault(Constructor->getLocation());
1493 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1494 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1495 MultiExprArg(*this, 0, 0));
1496 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1497 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001498 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001499 continue;
1500 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001501
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001502 // Don't attach synthesized base initializers in a dependent
1503 // context; they'll be checked again at template instantiation
1504 // time.
1505 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001506 continue;
1507
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001508 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001509 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001510 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001511 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001512 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001513 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001514 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001515 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001516 }
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001519 for (CXXRecordDecl::base_class_iterator Base =
1520 ClassDecl->bases_begin(),
1521 E = ClassDecl->bases_end(); Base != E; ++Base) {
1522 // Virtuals are in the virtual base list and already constructed.
1523 if (Base->isVirtual())
1524 continue;
1525 // Skip dependent types.
1526 if (Base->getType()->isDependentType())
1527 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001528 if (CXXBaseOrMemberInitializer *Value
1529 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001530 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001531 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001532 else if (!AnyErrors) {
1533 InitializedEntity InitEntity
1534 = InitializedEntity::InitializeBase(Context, Base);
1535 InitializationKind InitKind
1536 = InitializationKind::CreateDefault(Constructor->getLocation());
1537 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1538 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1539 MultiExprArg(*this, 0, 0));
1540 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1541 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001542 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001543 continue;
1544 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001545
1546 // Don't attach synthesized base initializers in a dependent
1547 // context; they'll be regenerated at template instantiation
1548 // time.
1549 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001550 continue;
1551
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001552 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001553 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001554 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001555 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001556 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001557 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001558 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001559 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001560 }
1561 }
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001564 // non-static data members.
1565 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1566 E = ClassDecl->field_end(); Field != E; ++Field) {
1567 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001568 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001569 Field->getType()->getAs<RecordType>()) {
1570 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001571 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001572 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001573 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1574 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1575 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1576 // set to the anonymous union data member used in the initializer
1577 // list.
1578 Value->setMember(*Field);
1579 Value->setAnonUnionMember(*FA);
1580 AllToInit.push_back(Value);
1581 break;
1582 }
1583 }
1584 }
1585 continue;
1586 }
1587 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1588 AllToInit.push_back(Value);
1589 continue;
1590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001592 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001593 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001594
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001595 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001596 if (FT->getAs<RecordType>()) {
1597 InitializedEntity InitEntity
1598 = InitializedEntity::InitializeMember(*Field);
1599 InitializationKind InitKind
1600 = InitializationKind::CreateDefault(Constructor->getLocation());
1601
1602 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1603 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1604 MultiExprArg(*this, 0, 0));
1605 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1606 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001607 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001608 continue;
1609 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610
1611 // Don't attach synthesized member initializers in a dependent
1612 // context; they'll be regenerated a template instantiation
1613 // time.
1614 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001615 continue;
1616
Mike Stump1eb44332009-09-09 15:08:12 +00001617 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001618 new (Context) CXXBaseOrMemberInitializer(Context,
1619 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001620 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001621 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001622 SourceLocation());
1623
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001624 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001625 }
1626 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001627 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001628 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1629 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001630 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001631 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001632 }
1633 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001634 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001635 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1636 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001637 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001638 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001642 NumInitializers = AllToInit.size();
1643 if (NumInitializers > 0) {
1644 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1645 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1646 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001648 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001649 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1650 CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1651 baseOrMemberInitializers[Idx] = Member;
1652 if (!Member->isBaseInitializer())
1653 continue;
1654 const Type *BaseType = Member->getBaseClass();
1655 const RecordType *RT = BaseType->getAs<RecordType>();
1656 if (!RT)
1657 continue;
1658 CXXRecordDecl *BaseClassDecl =
1659 cast<CXXRecordDecl>(RT->getDecl());
1660 if (BaseClassDecl->hasTrivialDestructor())
1661 continue;
1662 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1663 MarkDeclarationReferenced(Constructor->getLocation(), DD);
1664 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001665 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001666
1667 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001668}
1669
Eli Friedman6347f422009-07-21 19:28:10 +00001670static void *GetKeyForTopLevelField(FieldDecl *Field) {
1671 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001672 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001673 if (RT->getDecl()->isAnonymousStructOrUnion())
1674 return static_cast<void *>(RT->getDecl());
1675 }
1676 return static_cast<void *>(Field);
1677}
1678
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001679static void *GetKeyForBase(QualType BaseType) {
1680 if (const RecordType *RT = BaseType->getAs<RecordType>())
1681 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001683 assert(0 && "Unexpected base type!");
1684 return 0;
1685}
1686
Mike Stump1eb44332009-09-09 15:08:12 +00001687static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001688 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001689 // For fields injected into the class via declaration of an anonymous union,
1690 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001691 if (Member->isMemberInitializer()) {
1692 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Eli Friedman49c16da2009-11-09 01:05:47 +00001694 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001695 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001696 // in AnonUnionMember field.
1697 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1698 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001699 if (Field->getDeclContext()->isRecord()) {
1700 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1701 if (RD->isAnonymousStructOrUnion())
1702 return static_cast<void *>(RD);
1703 }
1704 return static_cast<void *>(Field);
1705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001707 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001708}
1709
John McCall6aee6212009-11-04 23:13:52 +00001710/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001711void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001712 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001713 MemInitTy **MemInits, unsigned NumMemInits,
1714 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001715 if (!ConstructorDecl)
1716 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001717
1718 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
1720 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001721 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Anders Carlssona7b35212009-03-25 02:58:17 +00001723 if (!Constructor) {
1724 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1725 return;
1726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001728 if (!Constructor->isDependentContext()) {
1729 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1730 bool err = false;
1731 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001732 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001733 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1734 void *KeyToMember = GetKeyForMember(Member);
1735 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1736 if (!PrevMember) {
1737 PrevMember = Member;
1738 continue;
1739 }
1740 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001741 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001742 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001743 << Field->getNameAsString()
1744 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001745 else {
1746 Type *BaseClass = Member->getBaseClass();
1747 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001749 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001750 << QualType(BaseClass, 0)
1751 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001752 }
1753 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1754 << 0;
1755 err = true;
1756 }
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001758 if (err)
1759 return;
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Eli Friedman49c16da2009-11-09 01:05:47 +00001762 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001763 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001764 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001766 if (Constructor->isDependentContext())
1767 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
1769 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001770 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001772 Diagnostic::Ignored)
1773 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001775 // Also issue warning if order of ctor-initializer list does not match order
1776 // of 1) base class declarations and 2) order of non-static data members.
1777 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001779 CXXRecordDecl *ClassDecl
1780 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1781 // Push virtual bases before others.
1782 for (CXXRecordDecl::base_class_iterator VBase =
1783 ClassDecl->vbases_begin(),
1784 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001785 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001787 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1788 E = ClassDecl->bases_end(); Base != E; ++Base) {
1789 // Virtuals are alread in the virtual base list and are constructed
1790 // first.
1791 if (Base->isVirtual())
1792 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001793 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001794 }
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001796 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1797 E = ClassDecl->field_end(); Field != E; ++Field)
1798 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 int Last = AllBaseOrMembers.size();
1801 int curIndex = 0;
1802 CXXBaseOrMemberInitializer *PrevMember = 0;
1803 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001804 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1806 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001807
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001808 for (; curIndex < Last; curIndex++)
1809 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1810 break;
1811 if (curIndex == Last) {
1812 assert(PrevMember && "Member not in member list?!");
1813 // Initializer as specified in ctor-initializer list is out of order.
1814 // Issue a warning diagnostic.
1815 if (PrevMember->isBaseInitializer()) {
1816 // Diagnostics is for an initialized base class.
1817 Type *BaseClass = PrevMember->getBaseClass();
1818 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001819 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001820 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001821 } else {
1822 FieldDecl *Field = PrevMember->getMember();
1823 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001824 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001825 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001826 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001827 // Also the note!
1828 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001829 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001830 diag::note_fieldorbase_initialized_here) << 0
1831 << Field->getNameAsString();
1832 else {
1833 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001834 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001835 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001836 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001837 }
1838 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001839 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001840 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001841 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001842 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001843 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001844}
1845
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001846void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001847Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1848 // Ignore dependent destructors.
1849 if (Destructor->isDependentContext())
1850 return;
1851
1852 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Anders Carlsson9f853df2009-11-17 04:44:12 +00001854 // Non-static data members.
1855 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1856 E = ClassDecl->field_end(); I != E; ++I) {
1857 FieldDecl *Field = *I;
1858
1859 QualType FieldType = Context.getBaseElementType(Field->getType());
1860
1861 const RecordType* RT = FieldType->getAs<RecordType>();
1862 if (!RT)
1863 continue;
1864
1865 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1866 if (FieldClassDecl->hasTrivialDestructor())
1867 continue;
1868
1869 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1870 MarkDeclarationReferenced(Destructor->getLocation(),
1871 const_cast<CXXDestructorDecl*>(Dtor));
1872 }
1873
1874 // Bases.
1875 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1876 E = ClassDecl->bases_end(); Base != E; ++Base) {
1877 // Ignore virtual bases.
1878 if (Base->isVirtual())
1879 continue;
1880
1881 // Ignore trivial destructors.
1882 CXXRecordDecl *BaseClassDecl
1883 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1884 if (BaseClassDecl->hasTrivialDestructor())
1885 continue;
1886
1887 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1888 MarkDeclarationReferenced(Destructor->getLocation(),
1889 const_cast<CXXDestructorDecl*>(Dtor));
1890 }
1891
1892 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001893 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1894 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001895 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001896 CXXRecordDecl *BaseClassDecl
1897 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1898 if (BaseClassDecl->hasTrivialDestructor())
1899 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001900
1901 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1902 MarkDeclarationReferenced(Destructor->getLocation(),
1903 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001904 }
1905}
1906
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001907void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001908 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001909 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001911 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
1913 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001914 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001915 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001916}
1917
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001918namespace {
1919 /// PureVirtualMethodCollector - traverses a class and its superclasses
1920 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001921 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001922 ASTContext &Context;
1923
Sebastian Redldfe292d2009-03-22 21:28:55 +00001924 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001925 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001926
1927 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001928 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001930 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001932 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001933 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001934 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001936 MethodList List;
1937 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001939 // Copy the temporary list to methods, and make sure to ignore any
1940 // null entries.
1941 for (size_t i = 0, e = List.size(); i != e; ++i) {
1942 if (List[i])
1943 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001944 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001947 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001949 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1950 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001951 };
Mike Stump1eb44332009-09-09 15:08:12 +00001952
1953 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001954 MethodList& Methods) {
1955 // First, collect the pure virtual methods for the base classes.
1956 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1957 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001958 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001959 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001960 if (BaseDecl && BaseDecl->isAbstract())
1961 Collect(BaseDecl, Methods);
1962 }
1963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001965 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001966 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001968 MethodSetTy OverriddenMethods;
1969 size_t MethodsSize = Methods.size();
1970
Mike Stump1eb44332009-09-09 15:08:12 +00001971 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001972 i != e; ++i) {
1973 // Traverse the record, looking for methods.
1974 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001975 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001976 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001977 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlsson27823022009-10-18 19:34:08 +00001979 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001980 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1981 E = MD->end_overridden_methods(); I != E; ++I) {
1982 // Keep track of the overridden methods.
1983 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001984 }
1985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
1988 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001989 // overridden.
1990 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1991 if (OverriddenMethods.count(Methods[i]))
1992 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001995 }
1996}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001997
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001998
Mike Stump1eb44332009-09-09 15:08:12 +00001999bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002000 unsigned DiagID, AbstractDiagSelID SelID,
2001 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002002 if (SelID == -1)
2003 return RequireNonAbstractType(Loc, T,
2004 PDiag(DiagID), CurrentRD);
2005 else
2006 return RequireNonAbstractType(Loc, T,
2007 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002008}
2009
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002010bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2011 const PartialDiagnostic &PD,
2012 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002013 if (!getLangOptions().CPlusPlus)
2014 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Anders Carlsson11f21a02009-03-23 19:10:31 +00002016 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002017 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002018 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002021 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002022 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002023 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002025 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002026 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenek6217b802009-07-29 21:53:49 +00002029 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002030 if (!RT)
2031 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
John McCall86ff3082010-02-04 22:26:26 +00002033 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002034
Anders Carlssone65a3c82009-03-24 17:23:42 +00002035 if (CurrentRD && CurrentRD != RD)
2036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
John McCall86ff3082010-02-04 22:26:26 +00002038 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002039 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002040 return false;
2041
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002042 if (!RD->isAbstract())
2043 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002045 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002047 // Check if we've already emitted the list of pure virtual functions for this
2048 // class.
2049 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2050 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002052 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
2054 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002055 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2056 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
2058 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002059 MD->getDeclName();
2060 }
2061
2062 if (!PureVirtualClassDiagSet)
2063 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2064 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002066 return true;
2067}
2068
Anders Carlsson8211eff2009-03-24 01:19:16 +00002069namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002070 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002071 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2072 Sema &SemaRef;
2073 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Anders Carlssone65a3c82009-03-24 17:23:42 +00002075 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002076 bool Invalid = false;
2077
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002078 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2079 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002080 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002081
Anders Carlsson8211eff2009-03-24 01:19:16 +00002082 return Invalid;
2083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Anders Carlssone65a3c82009-03-24 17:23:42 +00002085 public:
2086 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2087 : SemaRef(SemaRef), AbstractClass(ac) {
2088 Visit(SemaRef.Context.getTranslationUnitDecl());
2089 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002090
Anders Carlssone65a3c82009-03-24 17:23:42 +00002091 bool VisitFunctionDecl(const FunctionDecl *FD) {
2092 if (FD->isThisDeclarationADefinition()) {
2093 // No need to do the check if we're in a definition, because it requires
2094 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002095 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002096 return VisitDeclContext(FD);
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Anders Carlssone65a3c82009-03-24 17:23:42 +00002099 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002100 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002101 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002102 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2103 diag::err_abstract_type_in_decl,
2104 Sema::AbstractReturnType,
2105 AbstractClass);
2106
Mike Stump1eb44332009-09-09 15:08:12 +00002107 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002108 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002109 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002110 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002111 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002112 VD->getOriginalType(),
2113 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002114 Sema::AbstractParamType,
2115 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002116 }
2117
2118 return Invalid;
2119 }
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Anders Carlssone65a3c82009-03-24 17:23:42 +00002121 bool VisitDecl(const Decl* D) {
2122 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2123 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Anders Carlssone65a3c82009-03-24 17:23:42 +00002125 return false;
2126 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002127 };
2128}
2129
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002130/// \brief Perform semantic checks on a class definition that has been
2131/// completing, introducing implicitly-declared members, checking for
2132/// abstract types, etc.
2133void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2134 if (!Record || Record->isInvalidDecl())
2135 return;
2136
Eli Friedmanff2d8782009-12-16 20:00:27 +00002137 if (!Record->isDependentType())
2138 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002139
Eli Friedmanff2d8782009-12-16 20:00:27 +00002140 if (Record->isInvalidDecl())
2141 return;
2142
John McCall233a6412010-01-28 07:38:46 +00002143 // Set access bits correctly on the directly-declared conversions.
2144 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2145 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2146 Convs->setAccess(I, (*I)->getAccess());
2147
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002148 if (!Record->isAbstract()) {
2149 // Collect all the pure virtual methods and see if this is an abstract
2150 // class after all.
2151 PureVirtualMethodCollector Collector(Context, Record);
2152 if (!Collector.empty())
2153 Record->setAbstract(true);
2154 }
2155
2156 if (Record->isAbstract())
2157 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002158}
2159
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002160void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002161 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002162 SourceLocation LBrac,
2163 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002164 if (!TagDecl)
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor42af25f2009-05-11 19:58:34 +00002167 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002168
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002169 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002170 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002171 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002172
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002173 CheckCompletedCXXClass(
2174 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002175}
2176
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2178/// special functions, such as the default constructor, copy
2179/// constructor, or destructor, to the given C++ class (C++
2180/// [special]p1). This routine can only be executed just before the
2181/// definition of the class is complete.
2182void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002183 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002184 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002185
Sebastian Redl465226e2009-05-27 22:11:52 +00002186 // FIXME: Implicit declarations have exception specifications, which are
2187 // the union of the specifications of the implicitly called functions.
2188
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002189 if (!ClassDecl->hasUserDeclaredConstructor()) {
2190 // C++ [class.ctor]p5:
2191 // A default constructor for a class X is a constructor of class X
2192 // that can be called without an argument. If there is no
2193 // user-declared constructor for class X, a default constructor is
2194 // implicitly declared. An implicitly-declared default constructor
2195 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002196 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002197 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002198 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002199 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002200 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002201 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002202 0, 0, false, 0,
2203 /*FIXME*/false, false,
2204 0, 0, false,
2205 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002206 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002207 /*isExplicit=*/false,
2208 /*isInline=*/true,
2209 /*isImplicitlyDeclared=*/true);
2210 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002211 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002212 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002213 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002214 }
2215
2216 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2217 // C++ [class.copy]p4:
2218 // If the class definition does not explicitly declare a copy
2219 // constructor, one is declared implicitly.
2220
2221 // C++ [class.copy]p5:
2222 // The implicitly-declared copy constructor for a class X will
2223 // have the form
2224 //
2225 // X::X(const X&)
2226 //
2227 // if
2228 bool HasConstCopyConstructor = true;
2229
2230 // -- each direct or virtual base class B of X has a copy
2231 // constructor whose first parameter is of type const B& or
2232 // const volatile B&, and
2233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2234 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2235 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002236 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002237 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002238 = BaseClassDecl->hasConstCopyConstructor(Context);
2239 }
2240
2241 // -- for all the nonstatic data members of X that are of a
2242 // class type M (or array thereof), each such class type
2243 // has a copy constructor whose first parameter is of type
2244 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002245 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2246 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002247 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002248 QualType FieldType = (*Field)->getType();
2249 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2250 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002251 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002252 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002253 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002254 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002255 = FieldClassDecl->hasConstCopyConstructor(Context);
2256 }
2257 }
2258
Sebastian Redl64b45f72009-01-05 20:52:13 +00002259 // Otherwise, the implicitly declared copy constructor will have
2260 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002261 //
2262 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002263 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002264 if (HasConstCopyConstructor)
2265 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002266 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002267
Sebastian Redl64b45f72009-01-05 20:52:13 +00002268 // An implicitly-declared copy constructor is an inline public
2269 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002270 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002271 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002272 CXXConstructorDecl *CopyConstructor
2273 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002274 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002275 Context.getFunctionType(Context.VoidTy,
2276 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002277 false, 0,
2278 /*FIXME:*/false,
2279 false, 0, 0, false,
2280 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002281 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002282 /*isExplicit=*/false,
2283 /*isInline=*/true,
2284 /*isImplicitlyDeclared=*/true);
2285 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002286 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002287 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002288
2289 // Add the parameter to the constructor.
2290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2291 ClassDecl->getLocation(),
2292 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002293 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002294 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002295 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002296 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002297 }
2298
Sebastian Redl64b45f72009-01-05 20:52:13 +00002299 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2300 // Note: The following rules are largely analoguous to the copy
2301 // constructor rules. Note that virtual bases are not taken into account
2302 // for determining the argument type of the operator. Note also that
2303 // operators taking an object instead of a reference are allowed.
2304 //
2305 // C++ [class.copy]p10:
2306 // If the class definition does not explicitly declare a copy
2307 // assignment operator, one is declared implicitly.
2308 // The implicitly-defined copy assignment operator for a class X
2309 // will have the form
2310 //
2311 // X& X::operator=(const X&)
2312 //
2313 // if
2314 bool HasConstCopyAssignment = true;
2315
2316 // -- each direct base class B of X has a copy assignment operator
2317 // whose parameter is of type const B&, const volatile B& or B,
2318 // and
2319 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2320 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002321 assert(!Base->getType()->isDependentType() &&
2322 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002323 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002324 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002325 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002326 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002327 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002328 }
2329
2330 // -- for all the nonstatic data members of X that are of a class
2331 // type M (or array thereof), each such class type has a copy
2332 // assignment operator whose parameter is of type const M&,
2333 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2335 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002336 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002337 QualType FieldType = (*Field)->getType();
2338 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2339 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002340 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002341 const CXXRecordDecl *FieldClassDecl
2342 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002343 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002344 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002345 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002346 }
2347 }
2348
2349 // Otherwise, the implicitly declared copy assignment operator will
2350 // have the form
2351 //
2352 // X& X::operator=(X&)
2353 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002354 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002355 if (HasConstCopyAssignment)
2356 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002357 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002358
2359 // An implicitly-declared copy assignment operator is an inline public
2360 // member of its class.
2361 DeclarationName Name =
2362 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2363 CXXMethodDecl *CopyAssignment =
2364 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2365 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002366 false, 0,
2367 /*FIXME:*/false,
2368 false, 0, 0, false,
2369 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002370 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002371 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002372 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002373 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002374 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002375
2376 // Add the parameter to the operator.
2377 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2378 ClassDecl->getLocation(),
2379 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002380 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002381 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002382 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002383
2384 // Don't call addedAssignmentOperator. There is no way to distinguish an
2385 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002386 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002387 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002388 }
2389
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002390 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002391 // C++ [class.dtor]p2:
2392 // If a class has no user-declared destructor, a destructor is
2393 // declared implicitly. An implicitly-declared destructor is an
2394 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002395 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002396 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002397 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002398 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002399 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002400 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002401 0, 0, false, 0,
2402 /*FIXME:*/false,
2403 false, 0, 0, false,
2404 CC_Default),
Douglas Gregor42a552f2008-11-05 20:51:48 +00002405 /*isInline=*/true,
2406 /*isImplicitlyDeclared=*/true);
2407 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002408 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002409 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002410 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002411
2412 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002413 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002414}
2415
Douglas Gregor6569d682009-05-27 23:11:45 +00002416void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002417 Decl *D = TemplateD.getAs<Decl>();
2418 if (!D)
2419 return;
2420
2421 TemplateParameterList *Params = 0;
2422 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2423 Params = Template->getTemplateParameters();
2424 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2425 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2426 Params = PartialSpec->getTemplateParameters();
2427 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002428 return;
2429
Douglas Gregor6569d682009-05-27 23:11:45 +00002430 for (TemplateParameterList::iterator Param = Params->begin(),
2431 ParamEnd = Params->end();
2432 Param != ParamEnd; ++Param) {
2433 NamedDecl *Named = cast<NamedDecl>(*Param);
2434 if (Named->getDeclName()) {
2435 S->AddDecl(DeclPtrTy::make(Named));
2436 IdResolver.AddDecl(Named);
2437 }
2438 }
2439}
2440
John McCall7a1dc562009-12-19 10:49:29 +00002441void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2442 if (!RecordD) return;
2443 AdjustDeclIfTemplate(RecordD);
2444 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2445 PushDeclContext(S, Record);
2446}
2447
2448void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2449 if (!RecordD) return;
2450 PopDeclContext();
2451}
2452
Douglas Gregor72b505b2008-12-16 21:30:33 +00002453/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2454/// parsing a top-level (non-nested) C++ class, and we are now
2455/// parsing those parts of the given Method declaration that could
2456/// not be parsed earlier (C++ [class.mem]p2), such as default
2457/// arguments. This action should enter the scope of the given
2458/// Method declaration as if we had just parsed the qualified method
2459/// name. However, it should not bring the parameters into scope;
2460/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002461void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002462}
2463
2464/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2465/// C++ method declaration. We're (re-)introducing the given
2466/// function parameter into scope for use in parsing later parts of
2467/// the method declaration. For example, we could see an
2468/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002469void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002470 if (!ParamD)
2471 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Chris Lattnerb28317a2009-03-28 19:18:32 +00002473 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002474
2475 // If this parameter has an unparsed default argument, clear it out
2476 // to make way for the parsed default argument.
2477 if (Param->hasUnparsedDefaultArg())
2478 Param->setDefaultArg(0);
2479
Chris Lattnerb28317a2009-03-28 19:18:32 +00002480 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002481 if (Param->getDeclName())
2482 IdResolver.AddDecl(Param);
2483}
2484
2485/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2486/// processing the delayed method declaration for Method. The method
2487/// declaration is now considered finished. There may be a separate
2488/// ActOnStartOfFunctionDef action later (not necessarily
2489/// immediately!) for this method, if it was also defined inside the
2490/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002491void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002492 if (!MethodD)
2493 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002495 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Chris Lattnerb28317a2009-03-28 19:18:32 +00002497 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002498
2499 // Now that we have our default arguments, check the constructor
2500 // again. It could produce additional diagnostics or affect whether
2501 // the class has implicitly-declared destructors, among other
2502 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002503 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2504 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002505
2506 // Check the default arguments, which we may have added.
2507 if (!Method->isInvalidDecl())
2508 CheckCXXDefaultArguments(Method);
2509}
2510
Douglas Gregor42a552f2008-11-05 20:51:48 +00002511/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002512/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002513/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002514/// emit diagnostics and set the invalid bit to true. In any case, the type
2515/// will be updated to reflect a well-formed type for the constructor and
2516/// returned.
2517QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2518 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002519 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002520
2521 // C++ [class.ctor]p3:
2522 // A constructor shall not be virtual (10.3) or static (9.4). A
2523 // constructor can be invoked for a const, volatile or const
2524 // volatile object. A constructor shall not be declared const,
2525 // volatile, or const volatile (9.3.2).
2526 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002527 if (!D.isInvalidType())
2528 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2529 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2530 << SourceRange(D.getIdentifierLoc());
2531 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002532 }
2533 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002534 if (!D.isInvalidType())
2535 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2536 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2537 << SourceRange(D.getIdentifierLoc());
2538 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002539 SC = FunctionDecl::None;
2540 }
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Chris Lattner65401802009-04-25 08:28:21 +00002542 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2543 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002544 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002545 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2546 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002547 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002548 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2549 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002550 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002551 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2552 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002553 }
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Douglas Gregor42a552f2008-11-05 20:51:48 +00002555 // Rebuild the function type "R" without any type qualifiers (in
2556 // case any of the errors above fired) and with "void" as the
2557 // return type, since constructors don't have return types. We
2558 // *always* have to do this, because GetTypeForDeclarator will
2559 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002560 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002561 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2562 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002563 Proto->isVariadic(), 0,
2564 Proto->hasExceptionSpec(),
2565 Proto->hasAnyExceptionSpec(),
2566 Proto->getNumExceptions(),
2567 Proto->exception_begin(),
2568 Proto->getNoReturnAttr(),
2569 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002570}
2571
Douglas Gregor72b505b2008-12-16 21:30:33 +00002572/// CheckConstructor - Checks a fully-formed constructor for
2573/// well-formedness, issuing any diagnostics required. Returns true if
2574/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002575void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002576 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002577 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2578 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002579 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002580
2581 // C++ [class.copy]p3:
2582 // A declaration of a constructor for a class X is ill-formed if
2583 // its first parameter is of type (optionally cv-qualified) X and
2584 // either there are no other parameters or else all other
2585 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002586 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002587 ((Constructor->getNumParams() == 1) ||
2588 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002589 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2590 Constructor->getTemplateSpecializationKind()
2591 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002592 QualType ParamType = Constructor->getParamDecl(0)->getType();
2593 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2594 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002595 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2596 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002597 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002598
2599 // FIXME: Rather that making the constructor invalid, we should endeavor
2600 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002601 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002602 }
2603 }
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Douglas Gregor72b505b2008-12-16 21:30:33 +00002605 // Notify the class that we've added a constructor.
2606 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002607}
2608
Anders Carlsson37909802009-11-30 21:24:50 +00002609/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2610/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002611bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002612 CXXRecordDecl *RD = Destructor->getParent();
2613
2614 if (Destructor->isVirtual()) {
2615 SourceLocation Loc;
2616
2617 if (!Destructor->isImplicit())
2618 Loc = Destructor->getLocation();
2619 else
2620 Loc = RD->getLocation();
2621
2622 // If we have a virtual destructor, look up the deallocation function
2623 FunctionDecl *OperatorDelete = 0;
2624 DeclarationName Name =
2625 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002626 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002627 return true;
2628
2629 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002630 }
Anders Carlsson37909802009-11-30 21:24:50 +00002631
2632 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002633}
2634
Mike Stump1eb44332009-09-09 15:08:12 +00002635static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002636FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2637 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2638 FTI.ArgInfo[0].Param &&
2639 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2640}
2641
Douglas Gregor42a552f2008-11-05 20:51:48 +00002642/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2643/// the well-formednes of the destructor declarator @p D with type @p
2644/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002645/// emit diagnostics and set the declarator to invalid. Even if this happens,
2646/// will be updated to reflect a well-formed type for the destructor and
2647/// returned.
2648QualType Sema::CheckDestructorDeclarator(Declarator &D,
2649 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002650 // C++ [class.dtor]p1:
2651 // [...] A typedef-name that names a class is a class-name
2652 // (7.1.3); however, a typedef-name that names a class shall not
2653 // be used as the identifier in the declarator for a destructor
2654 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002655 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002656 if (isa<TypedefType>(DeclaratorType)) {
2657 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002658 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002659 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002660 }
2661
2662 // C++ [class.dtor]p2:
2663 // A destructor is used to destroy objects of its class type. A
2664 // destructor takes no parameters, and no return type can be
2665 // specified for it (not even void). The address of a destructor
2666 // shall not be taken. A destructor shall not be static. A
2667 // destructor can be invoked for a const, volatile or const
2668 // volatile object. A destructor shall not be declared const,
2669 // volatile or const volatile (9.3.2).
2670 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002671 if (!D.isInvalidType())
2672 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2673 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2674 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002675 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002676 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002677 }
Chris Lattner65401802009-04-25 08:28:21 +00002678 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002679 // Destructors don't have return types, but the parser will
2680 // happily parse something like:
2681 //
2682 // class X {
2683 // float ~X();
2684 // };
2685 //
2686 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002687 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2688 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2689 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002690 }
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Chris Lattner65401802009-04-25 08:28:21 +00002692 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2693 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002694 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002695 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2696 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002697 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002698 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2699 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002700 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002701 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2702 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002703 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002704 }
2705
2706 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002707 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002708 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2709
2710 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002711 FTI.freeArgs();
2712 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002713 }
2714
Mike Stump1eb44332009-09-09 15:08:12 +00002715 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002716 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002717 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002718 D.setInvalidType();
2719 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002720
2721 // Rebuild the function type "R" without any type qualifiers or
2722 // parameters (in case any of the errors above fired) and with
2723 // "void" as the return type, since destructors don't have return
2724 // types. We *always* have to do this, because GetTypeForDeclarator
2725 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002726 // FIXME: Exceptions!
2727 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2728 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002729}
2730
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002731/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2732/// well-formednes of the conversion function declarator @p D with
2733/// type @p R. If there are any errors in the declarator, this routine
2734/// will emit diagnostics and return true. Otherwise, it will return
2735/// false. Either way, the type @p R will be updated to reflect a
2736/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002737void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002738 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002739 // C++ [class.conv.fct]p1:
2740 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002741 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002742 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002743 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002744 if (!D.isInvalidType())
2745 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2746 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2747 << SourceRange(D.getIdentifierLoc());
2748 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002749 SC = FunctionDecl::None;
2750 }
Chris Lattner6e475012009-04-25 08:35:12 +00002751 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002752 // Conversion functions don't have return types, but the parser will
2753 // happily parse something like:
2754 //
2755 // class X {
2756 // float operator bool();
2757 // };
2758 //
2759 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002760 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2761 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2762 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002763 }
2764
2765 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002766 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002767 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2768
2769 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002770 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002771 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002772 }
2773
Mike Stump1eb44332009-09-09 15:08:12 +00002774 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002775 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002776 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002777 D.setInvalidType();
2778 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002779
2780 // C++ [class.conv.fct]p4:
2781 // The conversion-type-id shall not represent a function type nor
2782 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002783 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002784 if (ConvType->isArrayType()) {
2785 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2786 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002787 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002788 } else if (ConvType->isFunctionType()) {
2789 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2790 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002791 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002792 }
2793
2794 // Rebuild the function type "R" without any parameters (in case any
2795 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002796 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002797 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002798 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002799 Proto->getTypeQuals(),
2800 Proto->hasExceptionSpec(),
2801 Proto->hasAnyExceptionSpec(),
2802 Proto->getNumExceptions(),
2803 Proto->exception_begin(),
2804 Proto->getNoReturnAttr(),
2805 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002806
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002807 // C++0x explicit conversion operators.
2808 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002809 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002810 diag::warn_explicit_conversion_functions)
2811 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002812}
2813
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002814/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2815/// the declaration of the given C++ conversion function. This routine
2816/// is responsible for recording the conversion function in the C++
2817/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002818Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002819 assert(Conversion && "Expected to receive a conversion function declaration");
2820
Douglas Gregor9d350972008-12-12 08:25:50 +00002821 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002822
2823 // Make sure we aren't redeclaring the conversion function.
2824 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002825
2826 // C++ [class.conv.fct]p1:
2827 // [...] A conversion function is never used to convert a
2828 // (possibly cv-qualified) object to the (possibly cv-qualified)
2829 // same object type (or a reference to it), to a (possibly
2830 // cv-qualified) base class of that type (or a reference to it),
2831 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002832 // FIXME: Suppress this warning if the conversion function ends up being a
2833 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002834 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002835 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002836 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002837 ConvType = ConvTypeRef->getPointeeType();
2838 if (ConvType->isRecordType()) {
2839 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2840 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002841 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002842 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002843 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002844 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002845 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002846 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002847 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002848 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002849 }
2850
Douglas Gregor48026d22010-01-11 18:40:55 +00002851 if (Conversion->getPrimaryTemplate()) {
2852 // ignore specializations
2853 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002854 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002855 = Conversion->getDescribedFunctionTemplate()) {
2856 if (ClassDecl->replaceConversion(
2857 ConversionTemplate->getPreviousDeclaration(),
2858 ConversionTemplate))
2859 return DeclPtrTy::make(ConversionTemplate);
2860 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2861 Conversion))
John McCallba135432009-11-21 08:51:07 +00002862 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002863 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002864 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002865 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002866 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002867 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002868 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002869
Chris Lattnerb28317a2009-03-28 19:18:32 +00002870 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002871}
2872
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002873//===----------------------------------------------------------------------===//
2874// Namespace Handling
2875//===----------------------------------------------------------------------===//
2876
2877/// ActOnStartNamespaceDef - This is called at the start of a namespace
2878/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002879Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2880 SourceLocation IdentLoc,
2881 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002882 SourceLocation LBrace,
2883 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002884 NamespaceDecl *Namespc =
2885 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2886 Namespc->setLBracLoc(LBrace);
2887
2888 Scope *DeclRegionScope = NamespcScope->getParent();
2889
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002890 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2891
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002892 if (II) {
2893 // C++ [namespace.def]p2:
2894 // The identifier in an original-namespace-definition shall not have been
2895 // previously defined in the declarative region in which the
2896 // original-namespace-definition appears. The identifier in an
2897 // original-namespace-definition is the name of the namespace. Subsequently
2898 // in that declarative region, it is treated as an original-namespace-name.
2899
John McCallf36e02d2009-10-09 21:13:30 +00002900 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002901 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002902 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Douglas Gregor44b43212008-12-11 16:49:14 +00002904 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2905 // This is an extended namespace definition.
2906 // Attach this namespace decl to the chain of extended namespace
2907 // definitions.
2908 OrigNS->setNextNamespace(Namespc);
2909 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002910
Mike Stump1eb44332009-09-09 15:08:12 +00002911 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002912 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002913 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002914 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002915 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002916 } else if (PrevDecl) {
2917 // This is an invalid name redefinition.
2918 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2919 << Namespc->getDeclName();
2920 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2921 Namespc->setInvalidDecl();
2922 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002923 } else if (II->isStr("std") &&
2924 CurContext->getLookupContext()->isTranslationUnit()) {
2925 // This is the first "real" definition of the namespace "std", so update
2926 // our cache of the "std" namespace to point at this definition.
2927 if (StdNamespace) {
2928 // We had already defined a dummy namespace "std". Link this new
2929 // namespace definition to the dummy namespace "std".
2930 StdNamespace->setNextNamespace(Namespc);
2931 StdNamespace->setLocation(IdentLoc);
2932 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2933 }
2934
2935 // Make our StdNamespace cache point at the first real definition of the
2936 // "std" namespace.
2937 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002938 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002939
2940 PushOnScopeChains(Namespc, DeclRegionScope);
2941 } else {
John McCall9aeed322009-10-01 00:25:31 +00002942 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002943 assert(Namespc->isAnonymousNamespace());
2944 CurContext->addDecl(Namespc);
2945
2946 // Link the anonymous namespace into its parent.
2947 NamespaceDecl *PrevDecl;
2948 DeclContext *Parent = CurContext->getLookupContext();
2949 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2950 PrevDecl = TU->getAnonymousNamespace();
2951 TU->setAnonymousNamespace(Namespc);
2952 } else {
2953 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2954 PrevDecl = ND->getAnonymousNamespace();
2955 ND->setAnonymousNamespace(Namespc);
2956 }
2957
2958 // Link the anonymous namespace with its previous declaration.
2959 if (PrevDecl) {
2960 assert(PrevDecl->isAnonymousNamespace());
2961 assert(!PrevDecl->getNextNamespace());
2962 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2963 PrevDecl->setNextNamespace(Namespc);
2964 }
John McCall9aeed322009-10-01 00:25:31 +00002965
2966 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2967 // behaves as if it were replaced by
2968 // namespace unique { /* empty body */ }
2969 // using namespace unique;
2970 // namespace unique { namespace-body }
2971 // where all occurrences of 'unique' in a translation unit are
2972 // replaced by the same identifier and this identifier differs
2973 // from all other identifiers in the entire program.
2974
2975 // We just create the namespace with an empty name and then add an
2976 // implicit using declaration, just like the standard suggests.
2977 //
2978 // CodeGen enforces the "universally unique" aspect by giving all
2979 // declarations semantically contained within an anonymous
2980 // namespace internal linkage.
2981
John McCall5fdd7642009-12-16 02:06:49 +00002982 if (!PrevDecl) {
2983 UsingDirectiveDecl* UD
2984 = UsingDirectiveDecl::Create(Context, CurContext,
2985 /* 'using' */ LBrace,
2986 /* 'namespace' */ SourceLocation(),
2987 /* qualifier */ SourceRange(),
2988 /* NNS */ NULL,
2989 /* identifier */ SourceLocation(),
2990 Namespc,
2991 /* Ancestor */ CurContext);
2992 UD->setImplicit();
2993 CurContext->addDecl(UD);
2994 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002995 }
2996
2997 // Although we could have an invalid decl (i.e. the namespace name is a
2998 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002999 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3000 // for the namespace has the declarations that showed up in that particular
3001 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003002 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003003 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003004}
3005
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003006/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3007/// is a namespace alias, returns the namespace it points to.
3008static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3009 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3010 return AD->getNamespace();
3011 return dyn_cast_or_null<NamespaceDecl>(D);
3012}
3013
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003014/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3015/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003016void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3017 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003018 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3019 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3020 Namespc->setRBracLoc(RBrace);
3021 PopDeclContext();
3022}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003023
Chris Lattnerb28317a2009-03-28 19:18:32 +00003024Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3025 SourceLocation UsingLoc,
3026 SourceLocation NamespcLoc,
3027 const CXXScopeSpec &SS,
3028 SourceLocation IdentLoc,
3029 IdentifierInfo *NamespcName,
3030 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003031 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3032 assert(NamespcName && "Invalid NamespcName.");
3033 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003034 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003035
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003036 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003037
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003038 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003039 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3040 LookupParsedName(R, S, &SS);
3041 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003042 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003043
John McCallf36e02d2009-10-09 21:13:30 +00003044 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003045 NamedDecl *Named = R.getFoundDecl();
3046 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3047 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003048 // C++ [namespace.udir]p1:
3049 // A using-directive specifies that the names in the nominated
3050 // namespace can be used in the scope in which the
3051 // using-directive appears after the using-directive. During
3052 // unqualified name lookup (3.4.1), the names appear as if they
3053 // were declared in the nearest enclosing namespace which
3054 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003055 // namespace. [Note: in this context, "contains" means "contains
3056 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003057
3058 // Find enclosing context containing both using-directive and
3059 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003060 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003061 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3062 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3063 CommonAncestor = CommonAncestor->getParent();
3064
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003065 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003066 SS.getRange(),
3067 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003068 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003069 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003070 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003071 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003072 }
3073
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003074 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003075 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003076 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003077}
3078
3079void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3080 // If scope has associated entity, then using directive is at namespace
3081 // or translation unit scope. We add UsingDirectiveDecls, into
3082 // it's lookup structure.
3083 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003084 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003085 else
3086 // Otherwise it is block-sope. using-directives will affect lookup
3087 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003088 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003089}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003090
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003091
3092Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003093 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003094 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003095 SourceLocation UsingLoc,
3096 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003097 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003098 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003099 bool IsTypeName,
3100 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003101 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Douglas Gregor12c118a2009-11-04 16:30:06 +00003103 switch (Name.getKind()) {
3104 case UnqualifiedId::IK_Identifier:
3105 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003106 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003107 case UnqualifiedId::IK_ConversionFunctionId:
3108 break;
3109
3110 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003111 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003112 // C++0x inherited constructors.
3113 if (getLangOptions().CPlusPlus0x) break;
3114
Douglas Gregor12c118a2009-11-04 16:30:06 +00003115 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3116 << SS.getRange();
3117 return DeclPtrTy();
3118
3119 case UnqualifiedId::IK_DestructorName:
3120 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3121 << SS.getRange();
3122 return DeclPtrTy();
3123
3124 case UnqualifiedId::IK_TemplateId:
3125 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3126 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3127 return DeclPtrTy();
3128 }
3129
3130 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003131 if (!TargetName)
3132 return DeclPtrTy();
3133
John McCall60fa3cf2009-12-11 02:10:03 +00003134 // Warn about using declarations.
3135 // TODO: store that the declaration was written without 'using' and
3136 // talk about access decls instead of using decls in the
3137 // diagnostics.
3138 if (!HasUsingKeyword) {
3139 UsingLoc = Name.getSourceRange().getBegin();
3140
3141 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3142 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3143 "using ");
3144 }
3145
John McCall9488ea12009-11-17 05:59:44 +00003146 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003147 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003148 TargetName, AttrList,
3149 /* IsInstantiation */ false,
3150 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003151 if (UD)
3152 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003153
Anders Carlssonc72160b2009-08-28 05:40:36 +00003154 return DeclPtrTy::make(UD);
3155}
3156
John McCall9f54ad42009-12-10 09:41:52 +00003157/// Determines whether to create a using shadow decl for a particular
3158/// decl, given the set of decls existing prior to this using lookup.
3159bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3160 const LookupResult &Previous) {
3161 // Diagnose finding a decl which is not from a base class of the
3162 // current class. We do this now because there are cases where this
3163 // function will silently decide not to build a shadow decl, which
3164 // will pre-empt further diagnostics.
3165 //
3166 // We don't need to do this in C++0x because we do the check once on
3167 // the qualifier.
3168 //
3169 // FIXME: diagnose the following if we care enough:
3170 // struct A { int foo; };
3171 // struct B : A { using A::foo; };
3172 // template <class T> struct C : A {};
3173 // template <class T> struct D : C<T> { using B::foo; } // <---
3174 // This is invalid (during instantiation) in C++03 because B::foo
3175 // resolves to the using decl in B, which is not a base class of D<T>.
3176 // We can't diagnose it immediately because C<T> is an unknown
3177 // specialization. The UsingShadowDecl in D<T> then points directly
3178 // to A::foo, which will look well-formed when we instantiate.
3179 // The right solution is to not collapse the shadow-decl chain.
3180 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3181 DeclContext *OrigDC = Orig->getDeclContext();
3182
3183 // Handle enums and anonymous structs.
3184 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3185 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3186 while (OrigRec->isAnonymousStructOrUnion())
3187 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3188
3189 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3190 if (OrigDC == CurContext) {
3191 Diag(Using->getLocation(),
3192 diag::err_using_decl_nested_name_specifier_is_current_class)
3193 << Using->getNestedNameRange();
3194 Diag(Orig->getLocation(), diag::note_using_decl_target);
3195 return true;
3196 }
3197
3198 Diag(Using->getNestedNameRange().getBegin(),
3199 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3200 << Using->getTargetNestedNameDecl()
3201 << cast<CXXRecordDecl>(CurContext)
3202 << Using->getNestedNameRange();
3203 Diag(Orig->getLocation(), diag::note_using_decl_target);
3204 return true;
3205 }
3206 }
3207
3208 if (Previous.empty()) return false;
3209
3210 NamedDecl *Target = Orig;
3211 if (isa<UsingShadowDecl>(Target))
3212 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3213
John McCalld7533ec2009-12-11 02:33:26 +00003214 // If the target happens to be one of the previous declarations, we
3215 // don't have a conflict.
3216 //
3217 // FIXME: but we might be increasing its access, in which case we
3218 // should redeclare it.
3219 NamedDecl *NonTag = 0, *Tag = 0;
3220 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3221 I != E; ++I) {
3222 NamedDecl *D = (*I)->getUnderlyingDecl();
3223 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3224 return false;
3225
3226 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3227 }
3228
John McCall9f54ad42009-12-10 09:41:52 +00003229 if (Target->isFunctionOrFunctionTemplate()) {
3230 FunctionDecl *FD;
3231 if (isa<FunctionTemplateDecl>(Target))
3232 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3233 else
3234 FD = cast<FunctionDecl>(Target);
3235
3236 NamedDecl *OldDecl = 0;
3237 switch (CheckOverload(FD, Previous, OldDecl)) {
3238 case Ovl_Overload:
3239 return false;
3240
3241 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003242 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003243 break;
3244
3245 // We found a decl with the exact signature.
3246 case Ovl_Match:
3247 if (isa<UsingShadowDecl>(OldDecl)) {
3248 // Silently ignore the possible conflict.
3249 return false;
3250 }
3251
3252 // If we're in a record, we want to hide the target, so we
3253 // return true (without a diagnostic) to tell the caller not to
3254 // build a shadow decl.
3255 if (CurContext->isRecord())
3256 return true;
3257
3258 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003259 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003260 break;
3261 }
3262
3263 Diag(Target->getLocation(), diag::note_using_decl_target);
3264 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3265 return true;
3266 }
3267
3268 // Target is not a function.
3269
John McCall9f54ad42009-12-10 09:41:52 +00003270 if (isa<TagDecl>(Target)) {
3271 // No conflict between a tag and a non-tag.
3272 if (!Tag) return false;
3273
John McCall41ce66f2009-12-10 19:51:03 +00003274 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003275 Diag(Target->getLocation(), diag::note_using_decl_target);
3276 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3277 return true;
3278 }
3279
3280 // No conflict between a tag and a non-tag.
3281 if (!NonTag) return false;
3282
John McCall41ce66f2009-12-10 19:51:03 +00003283 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003284 Diag(Target->getLocation(), diag::note_using_decl_target);
3285 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3286 return true;
3287}
3288
John McCall9488ea12009-11-17 05:59:44 +00003289/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003290UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003291 UsingDecl *UD,
3292 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003293
3294 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003295 NamedDecl *Target = Orig;
3296 if (isa<UsingShadowDecl>(Target)) {
3297 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3298 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003299 }
3300
3301 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003302 = UsingShadowDecl::Create(Context, CurContext,
3303 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003304 UD->addShadowDecl(Shadow);
3305
3306 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003307 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003308 else
John McCall604e7f12009-12-08 07:46:18 +00003309 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003310 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003311
John McCall604e7f12009-12-08 07:46:18 +00003312 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3313 Shadow->setInvalidDecl();
3314
John McCall9f54ad42009-12-10 09:41:52 +00003315 return Shadow;
3316}
John McCall604e7f12009-12-08 07:46:18 +00003317
John McCall9f54ad42009-12-10 09:41:52 +00003318/// Hides a using shadow declaration. This is required by the current
3319/// using-decl implementation when a resolvable using declaration in a
3320/// class is followed by a declaration which would hide or override
3321/// one or more of the using decl's targets; for example:
3322///
3323/// struct Base { void foo(int); };
3324/// struct Derived : Base {
3325/// using Base::foo;
3326/// void foo(int);
3327/// };
3328///
3329/// The governing language is C++03 [namespace.udecl]p12:
3330///
3331/// When a using-declaration brings names from a base class into a
3332/// derived class scope, member functions in the derived class
3333/// override and/or hide member functions with the same name and
3334/// parameter types in a base class (rather than conflicting).
3335///
3336/// There are two ways to implement this:
3337/// (1) optimistically create shadow decls when they're not hidden
3338/// by existing declarations, or
3339/// (2) don't create any shadow decls (or at least don't make them
3340/// visible) until we've fully parsed/instantiated the class.
3341/// The problem with (1) is that we might have to retroactively remove
3342/// a shadow decl, which requires several O(n) operations because the
3343/// decl structures are (very reasonably) not designed for removal.
3344/// (2) avoids this but is very fiddly and phase-dependent.
3345void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3346 // Remove it from the DeclContext...
3347 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003348
John McCall9f54ad42009-12-10 09:41:52 +00003349 // ...and the scope, if applicable...
3350 if (S) {
3351 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3352 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003353 }
3354
John McCall9f54ad42009-12-10 09:41:52 +00003355 // ...and the using decl.
3356 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3357
3358 // TODO: complain somehow if Shadow was used. It shouldn't
3359 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003360}
3361
John McCall7ba107a2009-11-18 02:36:19 +00003362/// Builds a using declaration.
3363///
3364/// \param IsInstantiation - Whether this call arises from an
3365/// instantiation of an unresolved using declaration. We treat
3366/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003367NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3368 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003369 const CXXScopeSpec &SS,
3370 SourceLocation IdentLoc,
3371 DeclarationName Name,
3372 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003373 bool IsInstantiation,
3374 bool IsTypeName,
3375 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003376 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3377 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003378
Anders Carlsson550b14b2009-08-28 05:49:21 +00003379 // FIXME: We ignore attributes for now.
3380 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003382 if (SS.isEmpty()) {
3383 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003384 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003385 }
Mike Stump1eb44332009-09-09 15:08:12 +00003386
John McCall9f54ad42009-12-10 09:41:52 +00003387 // Do the redeclaration lookup in the current scope.
3388 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3389 ForRedeclaration);
3390 Previous.setHideTags(false);
3391 if (S) {
3392 LookupName(Previous, S);
3393
3394 // It is really dumb that we have to do this.
3395 LookupResult::Filter F = Previous.makeFilter();
3396 while (F.hasNext()) {
3397 NamedDecl *D = F.next();
3398 if (!isDeclInScope(D, CurContext, S))
3399 F.erase();
3400 }
3401 F.done();
3402 } else {
3403 assert(IsInstantiation && "no scope in non-instantiation");
3404 assert(CurContext->isRecord() && "scope not record in instantiation");
3405 LookupQualifiedName(Previous, CurContext);
3406 }
3407
Mike Stump1eb44332009-09-09 15:08:12 +00003408 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003409 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3410
John McCall9f54ad42009-12-10 09:41:52 +00003411 // Check for invalid redeclarations.
3412 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3413 return 0;
3414
3415 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003416 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3417 return 0;
3418
John McCallaf8e6ed2009-11-12 03:15:40 +00003419 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003420 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003421 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003422 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003423 // FIXME: not all declaration name kinds are legal here
3424 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3425 UsingLoc, TypenameLoc,
3426 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003427 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003428 } else {
3429 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3430 UsingLoc, SS.getRange(), NNS,
3431 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003432 }
John McCalled976492009-12-04 22:46:56 +00003433 } else {
3434 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3435 SS.getRange(), UsingLoc, NNS, Name,
3436 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003437 }
John McCalled976492009-12-04 22:46:56 +00003438 D->setAccess(AS);
3439 CurContext->addDecl(D);
3440
3441 if (!LookupContext) return D;
3442 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003443
John McCall604e7f12009-12-08 07:46:18 +00003444 if (RequireCompleteDeclContext(SS)) {
3445 UD->setInvalidDecl();
3446 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003447 }
3448
John McCall604e7f12009-12-08 07:46:18 +00003449 // Look up the target name.
3450
John McCalla24dc2e2009-11-17 02:14:36 +00003451 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003452
John McCall604e7f12009-12-08 07:46:18 +00003453 // Unlike most lookups, we don't always want to hide tag
3454 // declarations: tag names are visible through the using declaration
3455 // even if hidden by ordinary names, *except* in a dependent context
3456 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003457 if (!IsInstantiation)
3458 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003459
John McCalla24dc2e2009-11-17 02:14:36 +00003460 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003461
John McCallf36e02d2009-10-09 21:13:30 +00003462 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003463 Diag(IdentLoc, diag::err_no_member)
3464 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003465 UD->setInvalidDecl();
3466 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003467 }
3468
John McCalled976492009-12-04 22:46:56 +00003469 if (R.isAmbiguous()) {
3470 UD->setInvalidDecl();
3471 return UD;
3472 }
Mike Stump1eb44332009-09-09 15:08:12 +00003473
John McCall7ba107a2009-11-18 02:36:19 +00003474 if (IsTypeName) {
3475 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003476 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003477 Diag(IdentLoc, diag::err_using_typename_non_type);
3478 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3479 Diag((*I)->getUnderlyingDecl()->getLocation(),
3480 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003481 UD->setInvalidDecl();
3482 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003483 }
3484 } else {
3485 // If we asked for a non-typename and we got a type, error out,
3486 // but only if this is an instantiation of an unresolved using
3487 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003488 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003489 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3490 Diag(R.getFoundDecl()->getLocation(), 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 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003494 }
3495
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003496 // C++0x N2914 [namespace.udecl]p6:
3497 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003498 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003499 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3500 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003501 UD->setInvalidDecl();
3502 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
John McCall9f54ad42009-12-10 09:41:52 +00003505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3506 if (!CheckUsingShadowDecl(UD, *I, Previous))
3507 BuildUsingShadowDecl(S, UD, *I);
3508 }
John McCall9488ea12009-11-17 05:59:44 +00003509
3510 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003511}
3512
John McCall9f54ad42009-12-10 09:41:52 +00003513/// Checks that the given using declaration is not an invalid
3514/// redeclaration. Note that this is checking only for the using decl
3515/// itself, not for any ill-formedness among the UsingShadowDecls.
3516bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3517 bool isTypeName,
3518 const CXXScopeSpec &SS,
3519 SourceLocation NameLoc,
3520 const LookupResult &Prev) {
3521 // C++03 [namespace.udecl]p8:
3522 // C++0x [namespace.udecl]p10:
3523 // A using-declaration is a declaration and can therefore be used
3524 // repeatedly where (and only where) multiple declarations are
3525 // allowed.
3526 // That's only in file contexts.
3527 if (CurContext->getLookupContext()->isFileContext())
3528 return false;
3529
3530 NestedNameSpecifier *Qual
3531 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3532
3533 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3534 NamedDecl *D = *I;
3535
3536 bool DTypename;
3537 NestedNameSpecifier *DQual;
3538 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3539 DTypename = UD->isTypeName();
3540 DQual = UD->getTargetNestedNameDecl();
3541 } else if (UnresolvedUsingValueDecl *UD
3542 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3543 DTypename = false;
3544 DQual = UD->getTargetNestedNameSpecifier();
3545 } else if (UnresolvedUsingTypenameDecl *UD
3546 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3547 DTypename = true;
3548 DQual = UD->getTargetNestedNameSpecifier();
3549 } else continue;
3550
3551 // using decls differ if one says 'typename' and the other doesn't.
3552 // FIXME: non-dependent using decls?
3553 if (isTypeName != DTypename) continue;
3554
3555 // using decls differ if they name different scopes (but note that
3556 // template instantiation can cause this check to trigger when it
3557 // didn't before instantiation).
3558 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3559 Context.getCanonicalNestedNameSpecifier(DQual))
3560 continue;
3561
3562 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003563 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003564 return true;
3565 }
3566
3567 return false;
3568}
3569
John McCall604e7f12009-12-08 07:46:18 +00003570
John McCalled976492009-12-04 22:46:56 +00003571/// Checks that the given nested-name qualifier used in a using decl
3572/// in the current context is appropriately related to the current
3573/// scope. If an error is found, diagnoses it and returns true.
3574bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3575 const CXXScopeSpec &SS,
3576 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003577 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003578
John McCall604e7f12009-12-08 07:46:18 +00003579 if (!CurContext->isRecord()) {
3580 // C++03 [namespace.udecl]p3:
3581 // C++0x [namespace.udecl]p8:
3582 // A using-declaration for a class member shall be a member-declaration.
3583
3584 // If we weren't able to compute a valid scope, it must be a
3585 // dependent class scope.
3586 if (!NamedContext || NamedContext->isRecord()) {
3587 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3588 << SS.getRange();
3589 return true;
3590 }
3591
3592 // Otherwise, everything is known to be fine.
3593 return false;
3594 }
3595
3596 // The current scope is a record.
3597
3598 // If the named context is dependent, we can't decide much.
3599 if (!NamedContext) {
3600 // FIXME: in C++0x, we can diagnose if we can prove that the
3601 // nested-name-specifier does not refer to a base class, which is
3602 // still possible in some cases.
3603
3604 // Otherwise we have to conservatively report that things might be
3605 // okay.
3606 return false;
3607 }
3608
3609 if (!NamedContext->isRecord()) {
3610 // Ideally this would point at the last name in the specifier,
3611 // but we don't have that level of source info.
3612 Diag(SS.getRange().getBegin(),
3613 diag::err_using_decl_nested_name_specifier_is_not_class)
3614 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3615 return true;
3616 }
3617
3618 if (getLangOptions().CPlusPlus0x) {
3619 // C++0x [namespace.udecl]p3:
3620 // In a using-declaration used as a member-declaration, the
3621 // nested-name-specifier shall name a base class of the class
3622 // being defined.
3623
3624 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3625 cast<CXXRecordDecl>(NamedContext))) {
3626 if (CurContext == NamedContext) {
3627 Diag(NameLoc,
3628 diag::err_using_decl_nested_name_specifier_is_current_class)
3629 << SS.getRange();
3630 return true;
3631 }
3632
3633 Diag(SS.getRange().getBegin(),
3634 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3635 << (NestedNameSpecifier*) SS.getScopeRep()
3636 << cast<CXXRecordDecl>(CurContext)
3637 << SS.getRange();
3638 return true;
3639 }
3640
3641 return false;
3642 }
3643
3644 // C++03 [namespace.udecl]p4:
3645 // A using-declaration used as a member-declaration shall refer
3646 // to a member of a base class of the class being defined [etc.].
3647
3648 // Salient point: SS doesn't have to name a base class as long as
3649 // lookup only finds members from base classes. Therefore we can
3650 // diagnose here only if we can prove that that can't happen,
3651 // i.e. if the class hierarchies provably don't intersect.
3652
3653 // TODO: it would be nice if "definitely valid" results were cached
3654 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3655 // need to be repeated.
3656
3657 struct UserData {
3658 llvm::DenseSet<const CXXRecordDecl*> Bases;
3659
3660 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3661 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3662 Data->Bases.insert(Base);
3663 return true;
3664 }
3665
3666 bool hasDependentBases(const CXXRecordDecl *Class) {
3667 return !Class->forallBases(collect, this);
3668 }
3669
3670 /// Returns true if the base is dependent or is one of the
3671 /// accumulated base classes.
3672 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3673 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3674 return !Data->Bases.count(Base);
3675 }
3676
3677 bool mightShareBases(const CXXRecordDecl *Class) {
3678 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3679 }
3680 };
3681
3682 UserData Data;
3683
3684 // Returns false if we find a dependent base.
3685 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3686 return false;
3687
3688 // Returns false if the class has a dependent base or if it or one
3689 // of its bases is present in the base set of the current context.
3690 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3691 return false;
3692
3693 Diag(SS.getRange().getBegin(),
3694 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3695 << (NestedNameSpecifier*) SS.getScopeRep()
3696 << cast<CXXRecordDecl>(CurContext)
3697 << SS.getRange();
3698
3699 return true;
John McCalled976492009-12-04 22:46:56 +00003700}
3701
Mike Stump1eb44332009-09-09 15:08:12 +00003702Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003703 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003704 SourceLocation AliasLoc,
3705 IdentifierInfo *Alias,
3706 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003707 SourceLocation IdentLoc,
3708 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Anders Carlsson81c85c42009-03-28 23:53:49 +00003710 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003711 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3712 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003713
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003714 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003715 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003716 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003717 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003718 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003719 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003720 if (!R.isAmbiguous() && !R.empty() &&
3721 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003722 return DeclPtrTy();
3723 }
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003725 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3726 diag::err_redefinition_different_kind;
3727 Diag(AliasLoc, DiagID) << Alias;
3728 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003729 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003730 }
3731
John McCalla24dc2e2009-11-17 02:14:36 +00003732 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003733 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003734
John McCallf36e02d2009-10-09 21:13:30 +00003735 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003736 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003737 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003738 }
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003740 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003741 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3742 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003743 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003744 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003745
John McCall3dbd3d52010-02-16 06:53:13 +00003746 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003747 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003748}
3749
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003750void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3751 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003752 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3753 !Constructor->isUsed()) &&
3754 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003755
Eli Friedman80c30da2009-11-09 19:20:36 +00003756 CXXRecordDecl *ClassDecl
3757 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3758 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003759
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003760 DeclContext *PreviousContext = CurContext;
3761 CurContext = Constructor;
3762 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003763 Diag(CurrentLocation, diag::note_member_synthesized_at)
3764 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003765 Constructor->setInvalidDecl();
3766 } else {
3767 Constructor->setUsed();
3768 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003769 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003770}
3771
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003772void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003773 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003774 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3775 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003776 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003777 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003778
3779 DeclContext *PreviousContext = CurContext;
3780 CurContext = Destructor;
3781
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003782 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003783 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003784 // implicitly defined, all the implicitly-declared default destructors
3785 // for its base class and its non-static data members shall have been
3786 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003787 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3788 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003789 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003790 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003791 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003792 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003793 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3794 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3795 else
Mike Stump1eb44332009-09-09 15:08:12 +00003796 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003797 "DefineImplicitDestructor - missing dtor in a base class");
3798 }
3799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003801 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3802 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003803 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3804 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3805 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003806 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003807 CXXRecordDecl *FieldClassDecl
3808 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3809 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003810 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003811 const_cast<CXXDestructorDecl*>(
3812 FieldClassDecl->getDestructor(Context)))
3813 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3814 else
Mike Stump1eb44332009-09-09 15:08:12 +00003815 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003816 "DefineImplicitDestructor - missing dtor in class of a data member");
3817 }
3818 }
3819 }
Anders Carlsson37909802009-11-30 21:24:50 +00003820
3821 // FIXME: If CheckDestructor fails, we should emit a note about where the
3822 // implicit destructor was needed.
3823 if (CheckDestructor(Destructor)) {
3824 Diag(CurrentLocation, diag::note_member_synthesized_at)
3825 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3826
3827 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003828 CurContext = PreviousContext;
3829
Anders Carlsson37909802009-11-30 21:24:50 +00003830 return;
3831 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003832 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003833
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003834 Destructor->setUsed();
3835}
3836
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003837void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3838 CXXMethodDecl *MethodDecl) {
3839 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3840 MethodDecl->getOverloadedOperator() == OO_Equal &&
3841 !MethodDecl->isUsed()) &&
3842 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003844 CXXRecordDecl *ClassDecl
3845 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003847 DeclContext *PreviousContext = CurContext;
3848 CurContext = MethodDecl;
3849
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003850 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003851 // Before the implicitly-declared copy assignment operator for a class is
3852 // implicitly defined, all implicitly-declared copy assignment operators
3853 // for its direct base classes and its nonstatic data members shall have
3854 // been implicitly defined.
3855 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003856 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3857 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003858 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003859 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003860 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003861 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3862 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003863 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3864 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003865 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3866 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003867 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3868 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3869 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003870 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003871 CXXRecordDecl *FieldClassDecl
3872 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003873 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003874 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3875 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003876 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003877 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003878 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003879 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3880 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003881 Diag(CurrentLocation, diag::note_first_required_here);
3882 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003883 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003884 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003885 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3886 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003887 Diag(CurrentLocation, diag::note_first_required_here);
3888 err = true;
3889 }
3890 }
3891 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003892 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003893
3894 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003895}
3896
3897CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003898Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3899 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003900 CXXRecordDecl *ClassDecl) {
3901 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3902 QualType RHSType(LHSType);
3903 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003904 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003905 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003906 RHSType = Context.getCVRQualifiedType(RHSType,
3907 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003908 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003909 LHSType,
3910 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003911 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003912 RHSType,
3913 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003914 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003915 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003916 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003917 CandidateSet);
3918 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003919 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003920 return cast<CXXMethodDecl>(Best->Function);
3921 assert(false &&
3922 "getAssignOperatorMethod - copy assignment operator method not found");
3923 return 0;
3924}
3925
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003926void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3927 CXXConstructorDecl *CopyConstructor,
3928 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003929 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003930 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003931 !CopyConstructor->isUsed()) &&
3932 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003934 CXXRecordDecl *ClassDecl
3935 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3936 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003937
3938 DeclContext *PreviousContext = CurContext;
3939 CurContext = CopyConstructor;
3940
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003941 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003942 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003943 // implicitly defined, all the implicitly-declared copy constructors
3944 // for its base class and its non-static data members shall have been
3945 // implicitly defined.
3946 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3947 Base != ClassDecl->bases_end(); ++Base) {
3948 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003949 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003950 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003951 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003952 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003953 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003954 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3955 FieldEnd = ClassDecl->field_end();
3956 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003957 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3958 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3959 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003960 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003961 CXXRecordDecl *FieldClassDecl
3962 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003963 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003964 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003965 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003966 }
3967 }
3968 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003969
3970 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003971}
3972
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003973Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003974Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003975 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003976 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003977 bool RequiresZeroInit,
3978 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003979 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Douglas Gregor39da0b82009-09-09 23:08:42 +00003981 // C++ [class.copy]p15:
3982 // Whenever a temporary class object is copied using a copy constructor, and
3983 // this object and the copy have the same cv-unqualified type, an
3984 // implementation is permitted to treat the original and the copy as two
3985 // different ways of referring to the same object and not perform a copy at
3986 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003988 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003989 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003990 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003991 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3992 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3993 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003994 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3995 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003996 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3997 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003998 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3999 if (ICE->getCastKind() == CastExpr::CK_NoOp)
4000 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00004001
4002 if (CallExpr *CE = dyn_cast<CallExpr>(E))
4003 Elidable = !CE->getCallReturnType()->isReferenceType();
4004 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004005 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00004006 else if (isa<CXXConstructExpr>(E))
4007 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004008 }
Mike Stump1eb44332009-09-09 15:08:12 +00004009
4010 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004011 Elidable, move(ExprArgs), RequiresZeroInit,
4012 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004013}
4014
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004015/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4016/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004017Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004018Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4019 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004020 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004021 bool RequiresZeroInit,
4022 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004023 unsigned NumExprs = ExprArgs.size();
4024 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Douglas Gregor7edfb692009-11-23 12:27:39 +00004026 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004027 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004028 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004029 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004030}
4031
Mike Stump1eb44332009-09-09 15:08:12 +00004032bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004033 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004034 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004035 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004036 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004037 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004038 if (TempResult.isInvalid())
4039 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004041 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004042 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004043 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004044 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Anders Carlssonfe2de492009-08-25 05:18:00 +00004046 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004047}
4048
John McCall68c6c9a2010-02-02 09:10:11 +00004049void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4050 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004051 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4052 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004053 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4054 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004055 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004056 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004057}
4058
Mike Stump1eb44332009-09-09 15:08:12 +00004059/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004060/// ActOnDeclarator, when a C++ direct initializer is present.
4061/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004062void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4063 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004064 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004065 SourceLocation *CommaLocs,
4066 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004067 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004068 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004069
4070 // If there is no declaration, there was an error parsing it. Just ignore
4071 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004072 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004073 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004075 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4076 if (!VDecl) {
4077 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4078 RealDecl->setInvalidDecl();
4079 return;
4080 }
4081
Douglas Gregor83ddad32009-08-26 21:14:46 +00004082 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004083 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004084 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4085 //
4086 // Clients that want to distinguish between the two forms, can check for
4087 // direct initializer using VarDecl::hasCXXDirectInitializer().
4088 // A major benefit is that clients that don't particularly care about which
4089 // exactly form was it (like the CodeGen) can handle both cases without
4090 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004091
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004092 // C++ 8.5p11:
4093 // The form of initialization (using parentheses or '=') is generally
4094 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004095 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004096 QualType DeclInitType = VDecl->getType();
4097 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004098 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004099
Douglas Gregor4dffad62010-02-11 22:55:30 +00004100 if (!VDecl->getType()->isDependentType() &&
4101 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004102 diag::err_typecheck_decl_incomplete_type)) {
4103 VDecl->setInvalidDecl();
4104 return;
4105 }
4106
Douglas Gregor90f93822009-12-22 22:17:25 +00004107 // The variable can not have an abstract class type.
4108 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4109 diag::err_abstract_type_in_decl,
4110 AbstractVariableType))
4111 VDecl->setInvalidDecl();
4112
Sebastian Redl31310a22010-02-01 20:16:42 +00004113 const VarDecl *Def;
4114 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004115 Diag(VDecl->getLocation(), diag::err_redefinition)
4116 << VDecl->getDeclName();
4117 Diag(Def->getLocation(), diag::note_previous_definition);
4118 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004119 return;
4120 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004121
4122 // If either the declaration has a dependent type or if any of the
4123 // expressions is type-dependent, we represent the initialization
4124 // via a ParenListExpr for later use during template instantiation.
4125 if (VDecl->getType()->isDependentType() ||
4126 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4127 // Let clients know that initialization was done with a direct initializer.
4128 VDecl->setCXXDirectInitializer(true);
4129
4130 // Store the initialization expressions as a ParenListExpr.
4131 unsigned NumExprs = Exprs.size();
4132 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4133 (Expr **)Exprs.release(),
4134 NumExprs, RParenLoc));
4135 return;
4136 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004137
4138 // Capture the variable that is being initialized and the style of
4139 // initialization.
4140 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4141
4142 // FIXME: Poor source location information.
4143 InitializationKind Kind
4144 = InitializationKind::CreateDirect(VDecl->getLocation(),
4145 LParenLoc, RParenLoc);
4146
4147 InitializationSequence InitSeq(*this, Entity, Kind,
4148 (Expr**)Exprs.get(), Exprs.size());
4149 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4150 if (Result.isInvalid()) {
4151 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004152 return;
4153 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004154
4155 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004156 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004157 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004158
John McCall68c6c9a2010-02-02 09:10:11 +00004159 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4160 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004161}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004162
Douglas Gregor19aeac62009-11-14 03:27:21 +00004163/// \brief Add the applicable constructor candidates for an initialization
4164/// by constructor.
4165static void AddConstructorInitializationCandidates(Sema &SemaRef,
4166 QualType ClassType,
4167 Expr **Args,
4168 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004169 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004170 OverloadCandidateSet &CandidateSet) {
4171 // C++ [dcl.init]p14:
4172 // If the initialization is direct-initialization, or if it is
4173 // copy-initialization where the cv-unqualified version of the
4174 // source type is the same class as, or a derived class of, the
4175 // class of the destination, constructors are considered. The
4176 // applicable constructors are enumerated (13.3.1.3), and the
4177 // best one is chosen through overload resolution (13.3). The
4178 // constructor so selected is called to initialize the object,
4179 // with the initializer expression(s) as its argument(s). If no
4180 // constructor applies, or the overload resolution is ambiguous,
4181 // the initialization is ill-formed.
4182 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4183 assert(ClassRec && "Can only initialize a class type here");
4184
4185 // FIXME: When we decide not to synthesize the implicitly-declared
4186 // constructors, we'll need to make them appear here.
4187
4188 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4189 DeclarationName ConstructorName
4190 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4191 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4192 DeclContext::lookup_const_iterator Con, ConEnd;
4193 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4194 Con != ConEnd; ++Con) {
4195 // Find the constructor (which may be a template).
4196 CXXConstructorDecl *Constructor = 0;
4197 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4198 if (ConstructorTmpl)
4199 Constructor
4200 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4201 else
4202 Constructor = cast<CXXConstructorDecl>(*Con);
4203
Douglas Gregor20093b42009-12-09 23:02:17 +00004204 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4205 (Kind.getKind() == InitializationKind::IK_Value) ||
4206 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004207 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004208 ((Kind.getKind() == InitializationKind::IK_Default) &&
4209 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004210 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004211 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004212 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004213 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004214 Args, NumArgs, CandidateSet);
4215 else
John McCall86820f52010-01-26 01:37:31 +00004216 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4217 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004218 }
4219 }
4220}
4221
4222/// \brief Attempt to perform initialization by constructor
4223/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4224/// copy-initialization.
4225///
4226/// This routine determines whether initialization by constructor is possible,
4227/// but it does not emit any diagnostics in the case where the initialization
4228/// is ill-formed.
4229///
4230/// \param ClassType the type of the object being initialized, which must have
4231/// class type.
4232///
4233/// \param Args the arguments provided to initialize the object
4234///
4235/// \param NumArgs the number of arguments provided to initialize the object
4236///
4237/// \param Kind the type of initialization being performed
4238///
4239/// \returns the constructor used to initialize the object, if successful.
4240/// Otherwise, emits a diagnostic and returns NULL.
4241CXXConstructorDecl *
4242Sema::TryInitializationByConstructor(QualType ClassType,
4243 Expr **Args, unsigned NumArgs,
4244 SourceLocation Loc,
4245 InitializationKind Kind) {
4246 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004247 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004248 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4249 CandidateSet);
4250
4251 // Determine whether we found a constructor we can use.
4252 OverloadCandidateSet::iterator Best;
4253 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4254 case OR_Success:
4255 case OR_Deleted:
4256 // We found a constructor. Return it.
4257 return cast<CXXConstructorDecl>(Best->Function);
4258
4259 case OR_No_Viable_Function:
4260 case OR_Ambiguous:
4261 // Overload resolution failed. Return nothing.
4262 return 0;
4263 }
4264
4265 // Silence GCC warning
4266 return 0;
4267}
4268
Douglas Gregor39da0b82009-09-09 23:08:42 +00004269/// \brief Given a constructor and the set of arguments provided for the
4270/// constructor, convert the arguments and add any required default arguments
4271/// to form a proper call to this constructor.
4272///
4273/// \returns true if an error occurred, false otherwise.
4274bool
4275Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4276 MultiExprArg ArgsPtr,
4277 SourceLocation Loc,
4278 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4279 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4280 unsigned NumArgs = ArgsPtr.size();
4281 Expr **Args = (Expr **)ArgsPtr.get();
4282
4283 const FunctionProtoType *Proto
4284 = Constructor->getType()->getAs<FunctionProtoType>();
4285 assert(Proto && "Constructor without a prototype?");
4286 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004287
4288 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004289 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004290 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004291 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004292 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004293
4294 VariadicCallType CallType =
4295 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4296 llvm::SmallVector<Expr *, 8> AllArgs;
4297 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4298 Proto, 0, Args, NumArgs, AllArgs,
4299 CallType);
4300 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4301 ConvertedArgs.push_back(AllArgs[i]);
4302 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004303}
4304
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004305/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4306/// determine whether they are reference-related,
4307/// reference-compatible, reference-compatible with added
4308/// qualification, or incompatible, for use in C++ initialization by
4309/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4310/// type, and the first type (T1) is the pointee type of the reference
4311/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004312Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004313Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004314 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004315 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004316 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004317 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004318 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004319
Douglas Gregor393896f2009-11-05 13:06:35 +00004320 QualType T1 = Context.getCanonicalType(OrigT1);
4321 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004322 Qualifiers T1Quals, T2Quals;
4323 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4324 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004325
4326 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004327 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004328 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004329 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004330 if (UnqualT1 == UnqualT2)
4331 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004332 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4333 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4334 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004335 DerivedToBase = true;
4336 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004337 return Ref_Incompatible;
4338
4339 // At this point, we know that T1 and T2 are reference-related (at
4340 // least).
4341
Chandler Carruth28e318c2009-12-29 07:16:59 +00004342 // If the type is an array type, promote the element qualifiers to the type
4343 // for comparison.
4344 if (isa<ArrayType>(T1) && T1Quals)
4345 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4346 if (isa<ArrayType>(T2) && T2Quals)
4347 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4348
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004349 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004350 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004351 // reference-related to T2 and cv1 is the same cv-qualification
4352 // as, or greater cv-qualification than, cv2. For purposes of
4353 // overload resolution, cases for which cv1 is greater
4354 // cv-qualification than cv2 are identified as
4355 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004356 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004357 return Ref_Compatible;
4358 else if (T1.isMoreQualifiedThan(T2))
4359 return Ref_Compatible_With_Added_Qualification;
4360 else
4361 return Ref_Related;
4362}
4363
4364/// CheckReferenceInit - Check the initialization of a reference
4365/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4366/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004367/// list), and DeclType is the type of the declaration. When ICS is
4368/// non-null, this routine will compute the implicit conversion
4369/// sequence according to C++ [over.ics.ref] and will not produce any
4370/// diagnostics; when ICS is null, it will emit diagnostics when any
4371/// errors are found. Either way, a return value of true indicates
4372/// that there was a failure, a return value of false indicates that
4373/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004374///
4375/// When @p SuppressUserConversions, user-defined conversions are
4376/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004377/// When @p AllowExplicit, we also permit explicit user-defined
4378/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004379/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004380/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4381/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004382bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004383Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004384 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004385 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004386 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004387 ImplicitConversionSequence *ICS,
4388 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004389 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4390
Ted Kremenek6217b802009-07-29 21:53:49 +00004391 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004392 QualType T2 = Init->getType();
4393
Douglas Gregor904eed32008-11-10 20:40:00 +00004394 // If the initializer is the address of an overloaded function, try
4395 // to resolve the overloaded function. If all goes well, T2 is the
4396 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004397 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004398 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004399 ICS != 0);
4400 if (Fn) {
4401 // Since we're performing this reference-initialization for
4402 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004403 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004404 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004405 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004406
Anders Carlsson96ad5332009-10-21 17:16:23 +00004407 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004408 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004409
4410 T2 = Fn->getType();
4411 }
4412 }
4413
Douglas Gregor15da57e2008-10-29 02:00:59 +00004414 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004415 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004416 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004417 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4418 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004419 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004420 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004421
4422 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004423 if (ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00004424 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCalladbb8f82010-01-13 09:16:55 +00004425 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004426
4427 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004428 // A reference to type "cv1 T1" is initialized by an expression
4429 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004430
4431 // -- If the initializer expression
4432
Sebastian Redla9845802009-03-29 15:27:50 +00004433 // Rvalue references cannot bind to lvalues (N2812).
4434 // There is absolutely no situation where they can. In particular, note that
4435 // this is ill-formed, even if B has a user-defined conversion to A&&:
4436 // B b;
4437 // A&& r = b;
4438 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4439 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004440 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004441 << Init->getSourceRange();
4442 return true;
4443 }
4444
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004445 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004446 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4447 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004448 //
4449 // Note that the bit-field check is skipped if we are just computing
4450 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004451 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004452 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004453 BindsDirectly = true;
4454
Douglas Gregor15da57e2008-10-29 02:00:59 +00004455 if (ICS) {
4456 // C++ [over.ics.ref]p1:
4457 // When a parameter of reference type binds directly (8.5.3)
4458 // to an argument expression, the implicit conversion sequence
4459 // is the identity conversion, unless the argument expression
4460 // has a type that is a derived class of the parameter type,
4461 // in which case the implicit conversion sequence is a
4462 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004463 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004464 ICS->Standard.First = ICK_Identity;
4465 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4466 ICS->Standard.Third = ICK_Identity;
4467 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004468 ICS->Standard.setToType(0, T2);
4469 ICS->Standard.setToType(1, T1);
4470 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004471 ICS->Standard.ReferenceBinding = true;
4472 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004473 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004474 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004475
4476 // Nothing more to do: the inaccessibility/ambiguity check for
4477 // derived-to-base conversions is suppressed when we're
4478 // computing the implicit conversion sequence (C++
4479 // [over.best.ics]p2).
4480 return false;
4481 } else {
4482 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004483 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4484 if (DerivedToBase)
4485 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004486 else if(CheckExceptionSpecCompatibility(Init, T1))
4487 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004488 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004489 }
4490 }
4491
4492 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004493 // implicitly converted to an lvalue of type "cv3 T3,"
4494 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004495 // 92) (this conversion is selected by enumerating the
4496 // applicable conversion functions (13.3.1.6) and choosing
4497 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004498 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004499 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004500 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004501 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004502
John McCall5769d612010-02-08 23:07:23 +00004503 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004504 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004505 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004506 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004507 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004508 NamedDecl *D = *I;
4509 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4510 if (isa<UsingShadowDecl>(D))
4511 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4512
Mike Stump1eb44332009-09-09 15:08:12 +00004513 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004514 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004515 CXXConversionDecl *Conv;
4516 if (ConvTemplate)
4517 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4518 else
John McCall701c89e2009-12-03 04:06:58 +00004519 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004520
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004521 // If the conversion function doesn't return a reference type,
4522 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004523 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004524 (AllowExplicit || !Conv->isExplicit())) {
4525 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004526 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004527 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004528 else
John McCall86820f52010-01-26 01:37:31 +00004529 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4530 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004531 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004532 }
4533
4534 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004535 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004536 case OR_Success:
Douglas Gregora1a9f032010-03-07 23:17:44 +00004537 // C++ [over.ics.ref]p1:
4538 //
4539 // [...] If the parameter binds directly to the result of
4540 // applying a conversion function to the argument
4541 // expression, the implicit conversion sequence is a
4542 // user-defined conversion sequence (13.3.3.1.2), with the
4543 // second standard conversion sequence either an identity
4544 // conversion or, if the conversion function returns an
4545 // entity of a type that is a derived class of the parameter
4546 // type, a derived-to-base Conversion.
4547 if (!Best->FinalConversion.DirectBinding)
4548 break;
4549
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004550 // This is a direct binding.
4551 BindsDirectly = true;
4552
4553 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004554 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004555 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4556 ICS->UserDefined.After = Best->FinalConversion;
4557 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004558 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004559 assert(ICS->UserDefined.After.ReferenceBinding &&
4560 ICS->UserDefined.After.DirectBinding &&
4561 "Expected a direct reference binding!");
4562 return false;
4563 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004564 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004565 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004566 CastExpr::CK_UserDefinedConversion,
4567 cast<CXXMethodDecl>(Best->Function),
4568 Owned(Init));
4569 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004570
4571 if (CheckExceptionSpecCompatibility(Init, T1))
4572 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004573 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4574 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004575 }
4576 break;
4577
4578 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004579 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004580 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004581 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4582 Cand != CandidateSet.end(); ++Cand)
4583 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004584 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004585 break;
4586 }
4587 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4588 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004589 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004590 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004592 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004593 case OR_Deleted:
4594 // There was no suitable conversion, or we found a deleted
4595 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004596 break;
4597 }
4598 }
Mike Stump1eb44332009-09-09 15:08:12 +00004599
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004600 if (BindsDirectly) {
4601 // C++ [dcl.init.ref]p4:
4602 // [...] In all cases where the reference-related or
4603 // reference-compatible relationship of two types is used to
4604 // establish the validity of a reference binding, and T1 is a
4605 // base class of T2, a program that necessitates such a binding
4606 // is ill-formed if T1 is an inaccessible (clause 11) or
4607 // ambiguous (10.2) base class of T2.
4608 //
4609 // Note that we only check this condition when we're allowed to
4610 // complain about errors, because we should not be checking for
4611 // ambiguity (or inaccessibility) unless the reference binding
4612 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004613 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004614 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004615 Init->getSourceRange(),
4616 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004617 else
4618 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004619 }
4620
4621 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004622 // type (i.e., cv1 shall be const), or the reference shall be an
4623 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004624 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004625 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004626 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004627 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004628 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004629 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004630 return true;
4631 }
4632
4633 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004634 // class type, and "cv1 T1" is reference-compatible with
4635 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004636 // following ways (the choice is implementation-defined):
4637 //
4638 // -- The reference is bound to the object represented by
4639 // the rvalue (see 3.10) or to a sub-object within that
4640 // object.
4641 //
Eli Friedman33a31382009-08-05 19:21:58 +00004642 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004643 // a constructor is called to copy the entire rvalue
4644 // object into the temporary. The reference is bound to
4645 // the temporary or to a sub-object within the
4646 // temporary.
4647 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004648 // The constructor that would be used to make the copy
4649 // shall be callable whether or not the copy is actually
4650 // done.
4651 //
Sebastian Redla9845802009-03-29 15:27:50 +00004652 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004653 // freedom, so we will always take the first option and never build
4654 // a temporary in this case. FIXME: We will, however, have to check
4655 // for the presence of a copy constructor in C++98/03 mode.
4656 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004657 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4658 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004659 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004660 ICS->Standard.First = ICK_Identity;
4661 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4662 ICS->Standard.Third = ICK_Identity;
4663 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004664 ICS->Standard.setToType(0, T2);
4665 ICS->Standard.setToType(1, T1);
4666 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004667 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004668 ICS->Standard.DirectBinding = false;
4669 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004670 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004671 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004672 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4673 if (DerivedToBase)
4674 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004675 else if(CheckExceptionSpecCompatibility(Init, T1))
4676 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004677 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004678 }
4679 return false;
4680 }
4681
Eli Friedman33a31382009-08-05 19:21:58 +00004682 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004683 // initialized from the initializer expression using the
4684 // rules for a non-reference copy initialization (8.5). The
4685 // reference is then bound to the temporary. If T1 is
4686 // reference-related to T2, cv1 must be the same
4687 // cv-qualification as, or greater cv-qualification than,
4688 // cv2; otherwise, the program is ill-formed.
4689 if (RefRelationship == Ref_Related) {
4690 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4691 // we would be reference-compatible or reference-compatible with
4692 // added qualification. But that wasn't the case, so the reference
4693 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004694 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004695 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004696 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004697 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004698 return true;
4699 }
4700
Douglas Gregor734d9862009-01-30 23:27:23 +00004701 // If at least one of the types is a class type, the types are not
4702 // related, and we aren't allowed any user conversions, the
4703 // reference binding fails. This case is important for breaking
4704 // recursion, since TryImplicitConversion below will attempt to
4705 // create a temporary through the use of a copy constructor.
4706 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4707 (T1->isRecordType() || T2->isRecordType())) {
4708 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004709 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004710 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004711 return true;
4712 }
4713
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004714 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004715 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004716 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004717 //
Sebastian Redla9845802009-03-29 15:27:50 +00004718 // When a parameter of reference type is not bound directly to
4719 // an argument expression, the conversion sequence is the one
4720 // required to convert the argument expression to the
4721 // underlying type of the reference according to
4722 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4723 // to copy-initializing a temporary of the underlying type with
4724 // the argument expression. Any difference in top-level
4725 // cv-qualification is subsumed by the initialization itself
4726 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004727 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4728 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004729 /*ForceRValue=*/false,
4730 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004731
Sebastian Redla9845802009-03-29 15:27:50 +00004732 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004733 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004734 ICS->Standard.ReferenceBinding = true;
4735 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004736 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004737 ICS->UserDefined.After.ReferenceBinding = true;
4738 ICS->UserDefined.After.RRefBinding = isRValRef;
4739 }
John McCall1d318332010-01-12 00:44:57 +00004740 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004741 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004742 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004743 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004744 false, false,
4745 Conversions);
4746 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004747 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004748 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004749 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004750 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004751 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004752 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004753 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004754 }
4755 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004756 else {
4757 if (isRValRef)
4758 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4759 << Init->getSourceRange();
4760 else
4761 Diag(DeclLoc, diag::err_invalid_initialization)
4762 << DeclType << Init->getType() << Init->getSourceRange();
4763 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004764 }
4765 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004766 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004767}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004768
Anders Carlsson20d45d22009-12-12 00:32:00 +00004769static inline bool
4770CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4771 const FunctionDecl *FnDecl) {
4772 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4773 if (isa<NamespaceDecl>(DC)) {
4774 return SemaRef.Diag(FnDecl->getLocation(),
4775 diag::err_operator_new_delete_declared_in_namespace)
4776 << FnDecl->getDeclName();
4777 }
4778
4779 if (isa<TranslationUnitDecl>(DC) &&
4780 FnDecl->getStorageClass() == FunctionDecl::Static) {
4781 return SemaRef.Diag(FnDecl->getLocation(),
4782 diag::err_operator_new_delete_declared_static)
4783 << FnDecl->getDeclName();
4784 }
4785
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004786 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004787}
4788
Anders Carlsson156c78e2009-12-13 17:53:43 +00004789static inline bool
4790CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4791 CanQualType ExpectedResultType,
4792 CanQualType ExpectedFirstParamType,
4793 unsigned DependentParamTypeDiag,
4794 unsigned InvalidParamTypeDiag) {
4795 QualType ResultType =
4796 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4797
4798 // Check that the result type is not dependent.
4799 if (ResultType->isDependentType())
4800 return SemaRef.Diag(FnDecl->getLocation(),
4801 diag::err_operator_new_delete_dependent_result_type)
4802 << FnDecl->getDeclName() << ExpectedResultType;
4803
4804 // Check that the result type is what we expect.
4805 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4806 return SemaRef.Diag(FnDecl->getLocation(),
4807 diag::err_operator_new_delete_invalid_result_type)
4808 << FnDecl->getDeclName() << ExpectedResultType;
4809
4810 // A function template must have at least 2 parameters.
4811 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4812 return SemaRef.Diag(FnDecl->getLocation(),
4813 diag::err_operator_new_delete_template_too_few_parameters)
4814 << FnDecl->getDeclName();
4815
4816 // The function decl must have at least 1 parameter.
4817 if (FnDecl->getNumParams() == 0)
4818 return SemaRef.Diag(FnDecl->getLocation(),
4819 diag::err_operator_new_delete_too_few_parameters)
4820 << FnDecl->getDeclName();
4821
4822 // Check the the first parameter type is not dependent.
4823 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4824 if (FirstParamType->isDependentType())
4825 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4826 << FnDecl->getDeclName() << ExpectedFirstParamType;
4827
4828 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004829 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004830 ExpectedFirstParamType)
4831 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4832 << FnDecl->getDeclName() << ExpectedFirstParamType;
4833
4834 return false;
4835}
4836
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004837static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004838CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004839 // C++ [basic.stc.dynamic.allocation]p1:
4840 // A program is ill-formed if an allocation function is declared in a
4841 // namespace scope other than global scope or declared static in global
4842 // scope.
4843 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4844 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004845
4846 CanQualType SizeTy =
4847 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4848
4849 // C++ [basic.stc.dynamic.allocation]p1:
4850 // The return type shall be void*. The first parameter shall have type
4851 // std::size_t.
4852 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4853 SizeTy,
4854 diag::err_operator_new_dependent_param_type,
4855 diag::err_operator_new_param_type))
4856 return true;
4857
4858 // C++ [basic.stc.dynamic.allocation]p1:
4859 // The first parameter shall not have an associated default argument.
4860 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004861 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004862 diag::err_operator_new_default_arg)
4863 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4864
4865 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004866}
4867
4868static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004869CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4870 // C++ [basic.stc.dynamic.deallocation]p1:
4871 // A program is ill-formed if deallocation functions are declared in a
4872 // namespace scope other than global scope or declared static in global
4873 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004874 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4875 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004876
4877 // C++ [basic.stc.dynamic.deallocation]p2:
4878 // Each deallocation function shall return void and its first parameter
4879 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004880 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4881 SemaRef.Context.VoidPtrTy,
4882 diag::err_operator_delete_dependent_param_type,
4883 diag::err_operator_delete_param_type))
4884 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004885
Anders Carlsson46991d62009-12-12 00:16:02 +00004886 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4887 if (FirstParamType->isDependentType())
4888 return SemaRef.Diag(FnDecl->getLocation(),
4889 diag::err_operator_delete_dependent_param_type)
4890 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4891
4892 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4893 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004894 return SemaRef.Diag(FnDecl->getLocation(),
4895 diag::err_operator_delete_param_type)
4896 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004897
4898 return false;
4899}
4900
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004901/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4902/// of this overloaded operator is well-formed. If so, returns false;
4903/// otherwise, emits appropriate diagnostics and returns true.
4904bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004905 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004906 "Expected an overloaded operator declaration");
4907
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004908 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4909
Mike Stump1eb44332009-09-09 15:08:12 +00004910 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004911 // The allocation and deallocation functions, operator new,
4912 // operator new[], operator delete and operator delete[], are
4913 // described completely in 3.7.3. The attributes and restrictions
4914 // found in the rest of this subclause do not apply to them unless
4915 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004916 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004917 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004918
Anders Carlssona3ccda52009-12-12 00:26:23 +00004919 if (Op == OO_New || Op == OO_Array_New)
4920 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004921
4922 // C++ [over.oper]p6:
4923 // An operator function shall either be a non-static member
4924 // function or be a non-member function and have at least one
4925 // parameter whose type is a class, a reference to a class, an
4926 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004927 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4928 if (MethodDecl->isStatic())
4929 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004930 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004931 } else {
4932 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004933 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4934 ParamEnd = FnDecl->param_end();
4935 Param != ParamEnd; ++Param) {
4936 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004937 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4938 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004939 ClassOrEnumParam = true;
4940 break;
4941 }
4942 }
4943
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004944 if (!ClassOrEnumParam)
4945 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004946 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004947 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004948 }
4949
4950 // C++ [over.oper]p8:
4951 // An operator function cannot have default arguments (8.3.6),
4952 // except where explicitly stated below.
4953 //
Mike Stump1eb44332009-09-09 15:08:12 +00004954 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004955 // (C++ [over.call]p1).
4956 if (Op != OO_Call) {
4957 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4958 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004959 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004960 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004961 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004962 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004963 }
4964 }
4965
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004966 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4967 { false, false, false }
4968#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4969 , { Unary, Binary, MemberOnly }
4970#include "clang/Basic/OperatorKinds.def"
4971 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004972
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004973 bool CanBeUnaryOperator = OperatorUses[Op][0];
4974 bool CanBeBinaryOperator = OperatorUses[Op][1];
4975 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004976
4977 // C++ [over.oper]p8:
4978 // [...] Operator functions cannot have more or fewer parameters
4979 // than the number required for the corresponding operator, as
4980 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004981 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004982 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004983 if (Op != OO_Call &&
4984 ((NumParams == 1 && !CanBeUnaryOperator) ||
4985 (NumParams == 2 && !CanBeBinaryOperator) ||
4986 (NumParams < 1) || (NumParams > 2))) {
4987 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004988 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004989 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004990 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004991 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004992 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004993 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004994 assert(CanBeBinaryOperator &&
4995 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004996 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004997 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004998
Chris Lattner416e46f2008-11-21 07:57:12 +00004999 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005000 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005001 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005002
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005003 // Overloaded operators other than operator() cannot be variadic.
5004 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005005 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005006 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005007 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005008 }
5009
5010 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005011 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5012 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005013 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005014 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005015 }
5016
5017 // C++ [over.inc]p1:
5018 // The user-defined function called operator++ implements the
5019 // prefix and postfix ++ operator. If this function is a member
5020 // function with no parameters, or a non-member function with one
5021 // parameter of class or enumeration type, it defines the prefix
5022 // increment operator ++ for objects of that type. If the function
5023 // is a member function with one parameter (which shall be of type
5024 // int) or a non-member function with two parameters (the second
5025 // of which shall be of type int), it defines the postfix
5026 // increment operator ++ for objects of that type.
5027 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5028 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5029 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005030 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005031 ParamIsInt = BT->getKind() == BuiltinType::Int;
5032
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005033 if (!ParamIsInt)
5034 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005035 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005036 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005037 }
5038
Sebastian Redl64b45f72009-01-05 20:52:13 +00005039 // Notify the class if it got an assignment operator.
5040 if (Op == OO_Equal) {
5041 // Would have returned earlier otherwise.
5042 assert(isa<CXXMethodDecl>(FnDecl) &&
5043 "Overloaded = not member, but not filtered.");
5044 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5045 Method->getParent()->addedAssignmentOperator(Context, Method);
5046 }
5047
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005048 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005049}
Chris Lattner5a003a42008-12-17 07:09:26 +00005050
Sean Hunta6c058d2010-01-13 09:01:02 +00005051/// CheckLiteralOperatorDeclaration - Check whether the declaration
5052/// of this literal operator function is well-formed. If so, returns
5053/// false; otherwise, emits appropriate diagnostics and returns true.
5054bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5055 DeclContext *DC = FnDecl->getDeclContext();
5056 Decl::Kind Kind = DC->getDeclKind();
5057 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5058 Kind != Decl::LinkageSpec) {
5059 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5060 << FnDecl->getDeclName();
5061 return true;
5062 }
5063
5064 bool Valid = false;
5065
5066 // FIXME: Check for the one valid template signature
5067 // template <char...> type operator "" name();
5068
5069 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5070 // Check the first parameter
5071 QualType T = (*Param)->getType();
5072
5073 // unsigned long long int and long double are allowed, but only
5074 // alone.
5075 // We also allow any character type; their omission seems to be a bug
5076 // in n3000
5077 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5078 Context.hasSameType(T, Context.LongDoubleTy) ||
5079 Context.hasSameType(T, Context.CharTy) ||
5080 Context.hasSameType(T, Context.WCharTy) ||
5081 Context.hasSameType(T, Context.Char16Ty) ||
5082 Context.hasSameType(T, Context.Char32Ty)) {
5083 if (++Param == FnDecl->param_end())
5084 Valid = true;
5085 goto FinishedParams;
5086 }
5087
5088 // Otherwise it must be a pointer to const; let's strip those.
5089 const PointerType *PT = T->getAs<PointerType>();
5090 if (!PT)
5091 goto FinishedParams;
5092 T = PT->getPointeeType();
5093 if (!T.isConstQualified())
5094 goto FinishedParams;
5095 T = T.getUnqualifiedType();
5096
5097 // Move on to the second parameter;
5098 ++Param;
5099
5100 // If there is no second parameter, the first must be a const char *
5101 if (Param == FnDecl->param_end()) {
5102 if (Context.hasSameType(T, Context.CharTy))
5103 Valid = true;
5104 goto FinishedParams;
5105 }
5106
5107 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5108 // are allowed as the first parameter to a two-parameter function
5109 if (!(Context.hasSameType(T, Context.CharTy) ||
5110 Context.hasSameType(T, Context.WCharTy) ||
5111 Context.hasSameType(T, Context.Char16Ty) ||
5112 Context.hasSameType(T, Context.Char32Ty)))
5113 goto FinishedParams;
5114
5115 // The second and final parameter must be an std::size_t
5116 T = (*Param)->getType().getUnqualifiedType();
5117 if (Context.hasSameType(T, Context.getSizeType()) &&
5118 ++Param == FnDecl->param_end())
5119 Valid = true;
5120 }
5121
5122 // FIXME: This diagnostic is absolutely terrible.
5123FinishedParams:
5124 if (!Valid) {
5125 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5126 << FnDecl->getDeclName();
5127 return true;
5128 }
5129
5130 return false;
5131}
5132
Douglas Gregor074149e2009-01-05 19:45:36 +00005133/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5134/// linkage specification, including the language and (if present)
5135/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5136/// the location of the language string literal, which is provided
5137/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5138/// the '{' brace. Otherwise, this linkage specification does not
5139/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005140Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5141 SourceLocation ExternLoc,
5142 SourceLocation LangLoc,
5143 const char *Lang,
5144 unsigned StrSize,
5145 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005146 LinkageSpecDecl::LanguageIDs Language;
5147 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5148 Language = LinkageSpecDecl::lang_c;
5149 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5150 Language = LinkageSpecDecl::lang_cxx;
5151 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005152 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005153 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005154 }
Mike Stump1eb44332009-09-09 15:08:12 +00005155
Chris Lattnercc98eac2008-12-17 07:13:27 +00005156 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005157
Douglas Gregor074149e2009-01-05 19:45:36 +00005158 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005159 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005160 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005161 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005162 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005163 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005164}
5165
Douglas Gregor074149e2009-01-05 19:45:36 +00005166/// ActOnFinishLinkageSpecification - Completely the definition of
5167/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5168/// valid, it's the position of the closing '}' brace in a linkage
5169/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005170Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5171 DeclPtrTy LinkageSpec,
5172 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005173 if (LinkageSpec)
5174 PopDeclContext();
5175 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005176}
5177
Douglas Gregord308e622009-05-18 20:51:54 +00005178/// \brief Perform semantic analysis for the variable declaration that
5179/// occurs within a C++ catch clause, returning the newly-created
5180/// variable.
5181VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005182 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005183 IdentifierInfo *Name,
5184 SourceLocation Loc,
5185 SourceRange Range) {
5186 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005187
5188 // Arrays and functions decay.
5189 if (ExDeclType->isArrayType())
5190 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5191 else if (ExDeclType->isFunctionType())
5192 ExDeclType = Context.getPointerType(ExDeclType);
5193
5194 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5195 // The exception-declaration shall not denote a pointer or reference to an
5196 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005197 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005198 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005199 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005200 Invalid = true;
5201 }
Douglas Gregord308e622009-05-18 20:51:54 +00005202
Douglas Gregora2762912010-03-08 01:47:36 +00005203 // GCC allows catching pointers and references to incomplete types
5204 // as an extension; so do we, but we warn by default.
5205
Sebastian Redl4b07b292008-12-22 19:15:10 +00005206 QualType BaseType = ExDeclType;
5207 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005208 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005209 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005210 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005211 BaseType = Ptr->getPointeeType();
5212 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00005213 DK = diag::ext_catch_incomplete_ptr;
5214 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005215 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005216 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005217 BaseType = Ref->getPointeeType();
5218 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00005219 DK = diag::ext_catch_incomplete_ref;
5220 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005221 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005222 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00005223 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5224 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00005225 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005226
Mike Stump1eb44332009-09-09 15:08:12 +00005227 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005228 RequireNonAbstractType(Loc, ExDeclType,
5229 diag::err_abstract_type_in_decl,
5230 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005231 Invalid = true;
5232
Mike Stump1eb44332009-09-09 15:08:12 +00005233 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005234 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005235
Douglas Gregor6d182892010-03-05 23:38:39 +00005236 if (!Invalid) {
5237 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5238 // C++ [except.handle]p16:
5239 // The object declared in an exception-declaration or, if the
5240 // exception-declaration does not specify a name, a temporary (12.2) is
5241 // copy-initialized (8.5) from the exception object. [...]
5242 // The object is destroyed when the handler exits, after the destruction
5243 // of any automatic objects initialized within the handler.
5244 //
5245 // We just pretend to initialize the object with itself, then make sure
5246 // it can be destroyed later.
5247 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5248 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5249 Loc, ExDeclType, 0);
5250 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5251 SourceLocation());
5252 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5253 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5254 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5255 if (Result.isInvalid())
5256 Invalid = true;
5257 else
5258 FinalizeVarWithDestructor(ExDecl, RecordTy);
5259 }
5260 }
5261
Douglas Gregord308e622009-05-18 20:51:54 +00005262 if (Invalid)
5263 ExDecl->setInvalidDecl();
5264
5265 return ExDecl;
5266}
5267
5268/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5269/// handler.
5270Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005271 TypeSourceInfo *TInfo = 0;
5272 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005273
5274 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005275 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005276 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005277 // The scope should be freshly made just for us. There is just no way
5278 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005279 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005280 if (PrevDecl->isTemplateParameter()) {
5281 // Maybe we will complain about the shadowed template parameter.
5282 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005283 }
5284 }
5285
Chris Lattnereaaebc72009-04-25 08:06:05 +00005286 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005287 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5288 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005289 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005290 }
5291
John McCalla93c9342009-12-07 02:54:59 +00005292 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005293 D.getIdentifier(),
5294 D.getIdentifierLoc(),
5295 D.getDeclSpec().getSourceRange());
5296
Chris Lattnereaaebc72009-04-25 08:06:05 +00005297 if (Invalid)
5298 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005299
Sebastian Redl4b07b292008-12-22 19:15:10 +00005300 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005301 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005302 PushOnScopeChains(ExDecl, S);
5303 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005304 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005305
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005306 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005307 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005308}
Anders Carlssonfb311762009-03-14 00:25:26 +00005309
Mike Stump1eb44332009-09-09 15:08:12 +00005310Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005311 ExprArg assertexpr,
5312 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005313 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005314 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005315 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5316
Anders Carlssonc3082412009-03-14 00:33:21 +00005317 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5318 llvm::APSInt Value(32);
5319 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5320 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5321 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005322 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005323 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005324
Anders Carlssonc3082412009-03-14 00:33:21 +00005325 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005326 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005327 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005328 }
5329 }
Mike Stump1eb44332009-09-09 15:08:12 +00005330
Anders Carlsson77d81422009-03-15 17:35:16 +00005331 assertexpr.release();
5332 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005333 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005334 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005335
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005336 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005337 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005338}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005339
John McCalldd4a3b02009-09-16 22:47:08 +00005340/// Handle a friend type declaration. This works in tandem with
5341/// ActOnTag.
5342///
5343/// Notes on friend class templates:
5344///
5345/// We generally treat friend class declarations as if they were
5346/// declaring a class. So, for example, the elaborated type specifier
5347/// in a friend declaration is required to obey the restrictions of a
5348/// class-head (i.e. no typedefs in the scope chain), template
5349/// parameters are required to match up with simple template-ids, &c.
5350/// However, unlike when declaring a template specialization, it's
5351/// okay to refer to a template specialization without an empty
5352/// template parameter declaration, e.g.
5353/// friend class A<T>::B<unsigned>;
5354/// We permit this as a special case; if there are any template
5355/// parameters present at all, require proper matching, i.e.
5356/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005357Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005358 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005359 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005360
5361 assert(DS.isFriendSpecified());
5362 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5363
John McCalldd4a3b02009-09-16 22:47:08 +00005364 // Try to convert the decl specifier to a type. This works for
5365 // friend templates because ActOnTag never produces a ClassTemplateDecl
5366 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005367 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005368 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5369 if (TheDeclarator.isInvalidType())
5370 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005371
John McCalldd4a3b02009-09-16 22:47:08 +00005372 // This is definitely an error in C++98. It's probably meant to
5373 // be forbidden in C++0x, too, but the specification is just
5374 // poorly written.
5375 //
5376 // The problem is with declarations like the following:
5377 // template <T> friend A<T>::foo;
5378 // where deciding whether a class C is a friend or not now hinges
5379 // on whether there exists an instantiation of A that causes
5380 // 'foo' to equal C. There are restrictions on class-heads
5381 // (which we declare (by fiat) elaborated friend declarations to
5382 // be) that makes this tractable.
5383 //
5384 // FIXME: handle "template <> friend class A<T>;", which
5385 // is possibly well-formed? Who even knows?
5386 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5387 Diag(Loc, diag::err_tagless_friend_type_template)
5388 << DS.getSourceRange();
5389 return DeclPtrTy();
5390 }
5391
John McCall02cace72009-08-28 07:59:38 +00005392 // C++ [class.friend]p2:
5393 // An elaborated-type-specifier shall be used in a friend declaration
5394 // for a class.*
5395 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005396 // This is one of the rare places in Clang where it's legitimate to
5397 // ask about the "spelling" of the type.
5398 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5399 // If we evaluated the type to a record type, suggest putting
5400 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005401 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005402 RecordDecl *RD = RT->getDecl();
5403
5404 std::string InsertionText = std::string(" ") + RD->getKindName();
5405
John McCalle3af0232009-10-07 23:34:25 +00005406 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5407 << (unsigned) RD->getTagKind()
5408 << T
5409 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005410 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5411 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005412 return DeclPtrTy();
5413 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005414 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5415 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005416 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005417 }
5418 }
5419
John McCalle3af0232009-10-07 23:34:25 +00005420 // Enum types cannot be friends.
5421 if (T->getAs<EnumType>()) {
5422 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5423 << SourceRange(DS.getFriendSpecLoc());
5424 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005425 }
John McCall02cace72009-08-28 07:59:38 +00005426
John McCall02cace72009-08-28 07:59:38 +00005427 // C++98 [class.friend]p1: A friend of a class is a function
5428 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005429 // This is fixed in DR77, which just barely didn't make the C++03
5430 // deadline. It's also a very silly restriction that seriously
5431 // affects inner classes and which nobody else seems to implement;
5432 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005433
John McCalldd4a3b02009-09-16 22:47:08 +00005434 Decl *D;
5435 if (TempParams.size())
5436 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5437 TempParams.size(),
5438 (TemplateParameterList**) TempParams.release(),
5439 T.getTypePtr(),
5440 DS.getFriendSpecLoc());
5441 else
5442 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5443 DS.getFriendSpecLoc());
5444 D->setAccess(AS_public);
5445 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005446
John McCalldd4a3b02009-09-16 22:47:08 +00005447 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005448}
5449
John McCallbbbcdd92009-09-11 21:02:39 +00005450Sema::DeclPtrTy
5451Sema::ActOnFriendFunctionDecl(Scope *S,
5452 Declarator &D,
5453 bool IsDefinition,
5454 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005455 const DeclSpec &DS = D.getDeclSpec();
5456
5457 assert(DS.isFriendSpecified());
5458 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5459
5460 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005461 TypeSourceInfo *TInfo = 0;
5462 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005463
5464 // C++ [class.friend]p1
5465 // A friend of a class is a function or class....
5466 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005467 // It *doesn't* see through dependent types, which is correct
5468 // according to [temp.arg.type]p3:
5469 // If a declaration acquires a function type through a
5470 // type dependent on a template-parameter and this causes
5471 // a declaration that does not use the syntactic form of a
5472 // function declarator to have a function type, the program
5473 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005474 if (!T->isFunctionType()) {
5475 Diag(Loc, diag::err_unexpected_friend);
5476
5477 // It might be worthwhile to try to recover by creating an
5478 // appropriate declaration.
5479 return DeclPtrTy();
5480 }
5481
5482 // C++ [namespace.memdef]p3
5483 // - If a friend declaration in a non-local class first declares a
5484 // class or function, the friend class or function is a member
5485 // of the innermost enclosing namespace.
5486 // - The name of the friend is not found by simple name lookup
5487 // until a matching declaration is provided in that namespace
5488 // scope (either before or after the class declaration granting
5489 // friendship).
5490 // - If a friend function is called, its name may be found by the
5491 // name lookup that considers functions from namespaces and
5492 // classes associated with the types of the function arguments.
5493 // - When looking for a prior declaration of a class or a function
5494 // declared as a friend, scopes outside the innermost enclosing
5495 // namespace scope are not considered.
5496
John McCall02cace72009-08-28 07:59:38 +00005497 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5498 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005499 assert(Name);
5500
John McCall67d1a672009-08-06 02:15:43 +00005501 // The context we found the declaration in, or in which we should
5502 // create the declaration.
5503 DeclContext *DC;
5504
5505 // FIXME: handle local classes
5506
5507 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005508 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5509 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005510 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005511 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005512 DC = computeDeclContext(ScopeQual);
5513
5514 // FIXME: handle dependent contexts
5515 if (!DC) return DeclPtrTy();
5516
John McCall68263142009-11-18 22:49:29 +00005517 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005518
5519 // If searching in that context implicitly found a declaration in
5520 // a different context, treat it like it wasn't found at all.
5521 // TODO: better diagnostics for this case. Suggesting the right
5522 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005523 // FIXME: getRepresentativeDecl() is not right here at all
5524 if (Previous.empty() ||
5525 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005526 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005527 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5528 return DeclPtrTy();
5529 }
5530
5531 // C++ [class.friend]p1: A friend of a class is a function or
5532 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005533 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005534 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5535
John McCall67d1a672009-08-06 02:15:43 +00005536 // Otherwise walk out to the nearest namespace scope looking for matches.
5537 } else {
5538 // TODO: handle local class contexts.
5539
5540 DC = CurContext;
5541 while (true) {
5542 // Skip class contexts. If someone can cite chapter and verse
5543 // for this behavior, that would be nice --- it's what GCC and
5544 // EDG do, and it seems like a reasonable intent, but the spec
5545 // really only says that checks for unqualified existing
5546 // declarations should stop at the nearest enclosing namespace,
5547 // not that they should only consider the nearest enclosing
5548 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005549 while (DC->isRecord())
5550 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005551
John McCall68263142009-11-18 22:49:29 +00005552 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005553
5554 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005555 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005556 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005557
John McCall67d1a672009-08-06 02:15:43 +00005558 if (DC->isFileContext()) break;
5559 DC = DC->getParent();
5560 }
5561
5562 // C++ [class.friend]p1: A friend of a class is a function or
5563 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005564 // C++0x changes this for both friend types and functions.
5565 // Most C++ 98 compilers do seem to give an error here, so
5566 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005567 if (!Previous.empty() && DC->Equals(CurContext)
5568 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005569 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5570 }
5571
Douglas Gregor182ddf02009-09-28 00:08:27 +00005572 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005573 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005574 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5575 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5576 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005577 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005578 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5579 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005580 return DeclPtrTy();
5581 }
John McCall67d1a672009-08-06 02:15:43 +00005582 }
5583
Douglas Gregor182ddf02009-09-28 00:08:27 +00005584 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005585 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005586 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005587 IsDefinition,
5588 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005589 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005590
Douglas Gregor182ddf02009-09-28 00:08:27 +00005591 assert(ND->getDeclContext() == DC);
5592 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005593
John McCallab88d972009-08-31 22:39:49 +00005594 // Add the function declaration to the appropriate lookup tables,
5595 // adjusting the redeclarations list as necessary. We don't
5596 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005597 //
John McCallab88d972009-08-31 22:39:49 +00005598 // Also update the scope-based lookup if the target context's
5599 // lookup context is in lexical scope.
5600 if (!CurContext->isDependentContext()) {
5601 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005602 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005603 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005604 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005605 }
John McCall02cace72009-08-28 07:59:38 +00005606
5607 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005608 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005609 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005610 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005611 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005612
Douglas Gregor7557a132009-12-24 20:56:24 +00005613 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5614 FrD->setSpecialization(true);
5615
Douglas Gregor182ddf02009-09-28 00:08:27 +00005616 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005617}
5618
Chris Lattnerb28317a2009-03-28 19:18:32 +00005619void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005620 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005621
Chris Lattnerb28317a2009-03-28 19:18:32 +00005622 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005623 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5624 if (!Fn) {
5625 Diag(DelLoc, diag::err_deleted_non_function);
5626 return;
5627 }
5628 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5629 Diag(DelLoc, diag::err_deleted_decl_not_first);
5630 Diag(Prev->getLocation(), diag::note_previous_declaration);
5631 // If the declaration wasn't the first, we delete the function anyway for
5632 // recovery.
5633 }
5634 Fn->setDeleted();
5635}
Sebastian Redl13e88542009-04-27 21:33:24 +00005636
5637static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5638 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5639 ++CI) {
5640 Stmt *SubStmt = *CI;
5641 if (!SubStmt)
5642 continue;
5643 if (isa<ReturnStmt>(SubStmt))
5644 Self.Diag(SubStmt->getSourceRange().getBegin(),
5645 diag::err_return_in_constructor_handler);
5646 if (!isa<Expr>(SubStmt))
5647 SearchForReturnInStmt(Self, SubStmt);
5648 }
5649}
5650
5651void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5652 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5653 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5654 SearchForReturnInStmt(*this, Handler);
5655 }
5656}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005657
Mike Stump1eb44332009-09-09 15:08:12 +00005658bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005659 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005660 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5661 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005662
Chandler Carruth73857792010-02-15 11:53:20 +00005663 if (Context.hasSameType(NewTy, OldTy) ||
5664 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005665 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005666
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005667 // Check if the return types are covariant
5668 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005669
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005670 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005671 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5672 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005673 NewClassTy = NewPT->getPointeeType();
5674 OldClassTy = OldPT->getPointeeType();
5675 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005676 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5677 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5678 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5679 NewClassTy = NewRT->getPointeeType();
5680 OldClassTy = OldRT->getPointeeType();
5681 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005682 }
5683 }
Mike Stump1eb44332009-09-09 15:08:12 +00005684
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005685 // The return types aren't either both pointers or references to a class type.
5686 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005687 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005688 diag::err_different_return_type_for_overriding_virtual_function)
5689 << New->getDeclName() << NewTy << OldTy;
5690 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005691
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005692 return true;
5693 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005694
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005695 // C++ [class.virtual]p6:
5696 // If the return type of D::f differs from the return type of B::f, the
5697 // class type in the return type of D::f shall be complete at the point of
5698 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005699 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5700 if (!RT->isBeingDefined() &&
5701 RequireCompleteType(New->getLocation(), NewClassTy,
5702 PDiag(diag::err_covariant_return_incomplete)
5703 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005704 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005705 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005706
Douglas Gregora4923eb2009-11-16 21:35:15 +00005707 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005708 // Check if the new class derives from the old class.
5709 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5710 Diag(New->getLocation(),
5711 diag::err_covariant_return_not_derived)
5712 << New->getDeclName() << NewTy << OldTy;
5713 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5714 return true;
5715 }
Mike Stump1eb44332009-09-09 15:08:12 +00005716
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005717 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005718 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005719 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5720 // FIXME: Should this point to the return type?
5721 New->getLocation(), SourceRange(), New->getDeclName())) {
5722 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5723 return true;
5724 }
5725 }
Mike Stump1eb44332009-09-09 15:08:12 +00005726
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005727 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005728 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005729 Diag(New->getLocation(),
5730 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005731 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005732 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5733 return true;
5734 };
Mike Stump1eb44332009-09-09 15:08:12 +00005735
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005736
5737 // The new class type must have the same or less qualifiers as the old type.
5738 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5739 Diag(New->getLocation(),
5740 diag::err_covariant_return_type_class_type_more_qualified)
5741 << New->getDeclName() << NewTy << OldTy;
5742 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 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005747}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005748
Sean Huntbbd37c62009-11-21 08:43:09 +00005749bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5750 const CXXMethodDecl *Old)
5751{
5752 if (Old->hasAttr<FinalAttr>()) {
5753 Diag(New->getLocation(), diag::err_final_function_overridden)
5754 << New->getDeclName();
5755 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5756 return true;
5757 }
5758
5759 return false;
5760}
5761
Douglas Gregor4ba31362009-12-01 17:24:26 +00005762/// \brief Mark the given method pure.
5763///
5764/// \param Method the method to be marked pure.
5765///
5766/// \param InitRange the source range that covers the "0" initializer.
5767bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5768 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5769 Method->setPure();
5770
5771 // A class is abstract if at least one function is pure virtual.
5772 Method->getParent()->setAbstract(true);
5773 return false;
5774 }
5775
5776 if (!Method->isInvalidDecl())
5777 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5778 << Method->getDeclName() << InitRange;
5779 return true;
5780}
5781
John McCall731ad842009-12-19 09:28:58 +00005782/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5783/// an initializer for the out-of-line declaration 'Dcl'. The scope
5784/// is a fresh scope pushed for just this purpose.
5785///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005786/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5787/// static data member of class X, names should be looked up in the scope of
5788/// class X.
5789void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005790 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005791 Decl *D = Dcl.getAs<Decl>();
5792 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005793
John McCall731ad842009-12-19 09:28:58 +00005794 // We should only get called for declarations with scope specifiers, like:
5795 // int foo::bar;
5796 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005797 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005798}
5799
5800/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005801/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005802void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005803 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005804 Decl *D = Dcl.getAs<Decl>();
5805 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005806
John McCall731ad842009-12-19 09:28:58 +00005807 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005808 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005809}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005810
5811/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5812/// C++ if/switch/while/for statement.
5813/// e.g: "if (int x = f()) {...}"
5814Action::DeclResult
5815Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5816 // C++ 6.4p2:
5817 // The declarator shall not specify a function or an array.
5818 // The type-specifier-seq shall not contain typedef and shall not declare a
5819 // new class or enumeration.
5820 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5821 "Parser allowed 'typedef' as storage class of condition decl.");
5822
John McCalla93c9342009-12-07 02:54:59 +00005823 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005824 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005825 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005826
5827 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5828 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5829 // would be created and CXXConditionDeclExpr wants a VarDecl.
5830 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5831 << D.getSourceRange();
5832 return DeclResult();
5833 } else if (OwnedTag && OwnedTag->isDefinition()) {
5834 // The type-specifier-seq shall not declare a new class or enumeration.
5835 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5836 }
5837
5838 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5839 if (!Dcl)
5840 return DeclResult();
5841
5842 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5843 VD->setDeclaredInCondition(true);
5844 return Dcl;
5845}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005846
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005847static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005848 // Ignore dependent types.
5849 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005850 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005851
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005852 // Ignore declarations that are not definitions.
5853 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005854 return false;
5855
5856 CXXRecordDecl *RD = MD->getParent();
5857
5858 // Ignore classes without a vtable.
5859 if (!RD->isDynamicClass())
5860 return false;
5861
5862 switch (MD->getParent()->getTemplateSpecializationKind()) {
5863 case TSK_Undeclared:
5864 case TSK_ExplicitSpecialization:
5865 // Classes that aren't instantiations of templates don't need their
5866 // virtual methods marked until we see the definition of the key
5867 // function.
5868 break;
5869
5870 case TSK_ImplicitInstantiation:
5871 // This is a constructor of a class template; mark all of the virtual
5872 // members as referenced to ensure that they get instantiatied.
5873 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5874 return true;
5875 break;
5876
5877 case TSK_ExplicitInstantiationDeclaration:
5878 return true; //FIXME: This looks wrong.
5879
5880 case TSK_ExplicitInstantiationDefinition:
5881 // This is method of a explicit instantiation; mark all of the virtual
5882 // members as referenced to ensure that they get instantiatied.
5883 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005884 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005885
5886 // Consider only out-of-line definitions of member functions. When we see
5887 // an inline definition, it's too early to compute the key function.
5888 if (!MD->isOutOfLine())
5889 return false;
5890
5891 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5892
5893 // If there is no key function, we will need a copy of the vtable.
5894 if (!KeyFunction)
5895 return true;
5896
5897 // If this is the key function, we need to mark virtual members.
5898 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5899 return true;
5900
5901 return false;
5902}
5903
5904void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5905 CXXMethodDecl *MD) {
5906 CXXRecordDecl *RD = MD->getParent();
5907
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005908 // We will need to mark all of the virtual members as referenced to build the
5909 // vtable.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005910 if (!needsVtable(MD, Context))
5911 return;
5912
5913 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5914 if (kind == TSK_ImplicitInstantiation)
5915 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5916 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005917 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005918}
5919
5920bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5921 if (ClassesWithUnmarkedVirtualMembers.empty())
5922 return false;
5923
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005924 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5925 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5926 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5927 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005928 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005929 }
5930
Anders Carlssond6a637f2009-12-07 08:24:59 +00005931 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005932}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005933
5934void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5935 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5936 e = RD->method_end(); i != e; ++i) {
5937 CXXMethodDecl *MD = *i;
5938
5939 // C++ [basic.def.odr]p2:
5940 // [...] A virtual member function is used if it is not pure. [...]
5941 if (MD->isVirtual() && !MD->isPure())
5942 MarkDeclarationReferenced(Loc, MD);
5943 }
5944}