blob: 20a8303ba42f611a8681ba1cfbda29908a436f25 [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
Douglas Gregora8f32e02009-10-06 17:59:45 +0000668/// \brief Determine whether the type \p Derived is a C++ class that is
669/// derived from the type \p Base.
670bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
671 if (!getLangOptions().CPlusPlus)
672 return false;
673
674 const RecordType *DerivedRT = Derived->getAs<RecordType>();
675 if (!DerivedRT)
676 return false;
677
678 const RecordType *BaseRT = Base->getAs<RecordType>();
679 if (!BaseRT)
680 return false;
681
682 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
683 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall86ff3082010-02-04 22:26:26 +0000684 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
685 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686}
687
688/// \brief Determine whether the type \p Derived is a C++ class that is
689/// derived from the type \p Base.
690bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
691 if (!getLangOptions().CPlusPlus)
692 return false;
693
694 const RecordType *DerivedRT = Derived->getAs<RecordType>();
695 if (!DerivedRT)
696 return false;
697
698 const RecordType *BaseRT = Base->getAs<RecordType>();
699 if (!BaseRT)
700 return false;
701
702 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
703 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
704 return DerivedRD->isDerivedFrom(BaseRD, Paths);
705}
706
707/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
708/// conversion (where Derived and Base are class types) is
709/// well-formed, meaning that the conversion is unambiguous (and
710/// that all of the base classes are accessible). Returns true
711/// and emits a diagnostic if the code is ill-formed, returns false
712/// otherwise. Loc is the location where this routine should point to
713/// if there is an error, and Range is the source range to highlight
714/// if there is an error.
715bool
716Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000717 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000718 unsigned AmbigiousBaseConvID,
719 SourceLocation Loc, SourceRange Range,
720 DeclarationName Name) {
721 // First, determine whether the path from Derived to Base is
722 // ambiguous. This is slightly more expensive than checking whether
723 // the Derived to Base conversion exists, because here we need to
724 // explore multiple paths to determine if there is an ambiguity.
725 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
726 /*DetectVirtual=*/false);
727 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
728 assert(DerivationOkay &&
729 "Can only be used with a derived-to-base conversion");
730 (void)DerivationOkay;
731
732 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000733 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000734 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000735
Douglas Gregora8f32e02009-10-06 17:59:45 +0000736 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000737 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
738 Base, Derived, Paths.front(),
739 /*force*/ false,
740 /*unprivileged*/ false,
741 ADK)) {
742 case AR_accessible: return false;
743 case AR_inaccessible: return true;
744 case AR_dependent: return false;
745 case AR_delayed: return false;
746 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 }
748
749 // We know that the derived-to-base conversion is ambiguous, and
750 // we're going to produce a diagnostic. Perform the derived-to-base
751 // search just one more time to compute all of the possible paths so
752 // that we can print them out. This is more expensive than any of
753 // the previous derived-to-base checks we've done, but at this point
754 // performance isn't as much of an issue.
755 Paths.clear();
756 Paths.setRecordingPaths(true);
757 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
758 assert(StillOkay && "Can only be used with a derived-to-base conversion");
759 (void)StillOkay;
760
761 // Build up a textual representation of the ambiguous paths, e.g.,
762 // D -> B -> A, that will be used to illustrate the ambiguous
763 // conversions in the diagnostic. We only print one of the paths
764 // to each base class subobject.
765 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
766
767 Diag(Loc, AmbigiousBaseConvID)
768 << Derived << Base << PathDisplayStr << Range << Name;
769 return true;
770}
771
772bool
773Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000774 SourceLocation Loc, SourceRange Range,
775 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000776 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000777 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000778 diag::err_ambiguous_derived_to_base_conv,
779 Loc, Range, DeclarationName());
780}
781
782
783/// @brief Builds a string representing ambiguous paths from a
784/// specific derived class to different subobjects of the same base
785/// class.
786///
787/// This function builds a string that can be used in error messages
788/// to show the different paths that one can take through the
789/// inheritance hierarchy to go from the derived class to different
790/// subobjects of a base class. The result looks something like this:
791/// @code
792/// struct D -> struct B -> struct A
793/// struct D -> struct C -> struct A
794/// @endcode
795std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
796 std::string PathDisplayStr;
797 std::set<unsigned> DisplayedPaths;
798 for (CXXBasePaths::paths_iterator Path = Paths.begin();
799 Path != Paths.end(); ++Path) {
800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
801 // We haven't displayed a path to this particular base
802 // class subobject yet.
803 PathDisplayStr += "\n ";
804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
805 for (CXXBasePath::const_iterator Element = Path->begin();
806 Element != Path->end(); ++Element)
807 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
808 }
809 }
810
811 return PathDisplayStr;
812}
813
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000814//===----------------------------------------------------------------------===//
815// C++ class member Handling
816//===----------------------------------------------------------------------===//
817
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000818/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
819/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
820/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000821/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000822Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000823Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000824 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000825 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
826 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000827 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000828 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000829 Expr *BitWidth = static_cast<Expr*>(BW);
830 Expr *Init = static_cast<Expr*>(InitExpr);
831 SourceLocation Loc = D.getIdentifierLoc();
832
Sebastian Redl669d5d72008-11-14 23:42:31 +0000833 bool isFunc = D.isFunctionDeclarator();
834
John McCall67d1a672009-08-06 02:15:43 +0000835 assert(!DS.isFriendSpecified());
836
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000837 // C++ 9.2p6: A member shall not be declared to have automatic storage
838 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000839 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
840 // data members and cannot be applied to names declared const or static,
841 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 switch (DS.getStorageClassSpec()) {
843 case DeclSpec::SCS_unspecified:
844 case DeclSpec::SCS_typedef:
845 case DeclSpec::SCS_static:
846 // FALL THROUGH.
847 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000848 case DeclSpec::SCS_mutable:
849 if (isFunc) {
850 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000851 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000852 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000853 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Sebastian Redla11f42f2008-11-17 23:24:37 +0000855 // FIXME: It would be nicer if the keyword was ignored only for this
856 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000857 D.getMutableDeclSpec().ClearStorageClassSpecs();
858 } else {
859 QualType T = GetTypeForDeclarator(D, S);
860 diag::kind err = static_cast<diag::kind>(0);
861 if (T->isReferenceType())
862 err = diag::err_mutable_reference;
863 else if (T.isConstQualified())
864 err = diag::err_mutable_const;
865 if (err != 0) {
866 if (DS.getStorageClassSpecLoc().isValid())
867 Diag(DS.getStorageClassSpecLoc(), err);
868 else
869 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000870 // FIXME: It would be nicer if the keyword was ignored only for this
871 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000872 D.getMutableDeclSpec().ClearStorageClassSpecs();
873 }
874 }
875 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000876 default:
877 if (DS.getStorageClassSpecLoc().isValid())
878 Diag(DS.getStorageClassSpecLoc(),
879 diag::err_storageclass_invalid_for_member);
880 else
881 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
882 D.getMutableDeclSpec().ClearStorageClassSpecs();
883 }
884
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000885 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000886 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000887 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000888 // Check also for this case:
889 //
890 // typedef int f();
891 // f a;
892 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000893 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000894 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000895 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000896
Sebastian Redl669d5d72008-11-14 23:42:31 +0000897 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
898 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000899 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900
901 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000902 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000903 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000904 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
905 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000906 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000907 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000908 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000909 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000910 if (!Member) {
911 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000912 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000913 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000914
915 // Non-instance-fields can't have a bitfield.
916 if (BitWidth) {
917 if (Member->isInvalidDecl()) {
918 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000919 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000920 // C++ 9.6p3: A bit-field shall not be a static member.
921 // "static member 'A' cannot be a bit-field"
922 Diag(Loc, diag::err_static_not_bitfield)
923 << Name << BitWidth->getSourceRange();
924 } else if (isa<TypedefDecl>(Member)) {
925 // "typedef member 'x' cannot be a bit-field"
926 Diag(Loc, diag::err_typedef_not_bitfield)
927 << Name << BitWidth->getSourceRange();
928 } else {
929 // A function typedef ("typedef int f(); f a;").
930 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
931 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000932 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000933 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner8b963ef2009-03-05 23:01:03 +0000936 DeleteExpr(BitWidth);
937 BitWidth = 0;
938 Member->setInvalidDecl();
939 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000940
941 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregor37b372b2009-08-20 22:52:58 +0000943 // If we have declared a member function template, set the access of the
944 // templated declaration as well.
945 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
946 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000947 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000948
Douglas Gregor10bd3682008-11-17 22:58:34 +0000949 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000950
Douglas Gregor021c3b32009-03-11 23:00:04 +0000951 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000952 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000953 if (Deleted) // FIXME: Source location is not very good.
954 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000955
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000957 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000958 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000959 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000960 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961}
962
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000963/// \brief Find the direct and/or virtual base specifiers that
964/// correspond to the given base type, for use in base initialization
965/// within a constructor.
966static bool FindBaseInitializer(Sema &SemaRef,
967 CXXRecordDecl *ClassDecl,
968 QualType BaseType,
969 const CXXBaseSpecifier *&DirectBaseSpec,
970 const CXXBaseSpecifier *&VirtualBaseSpec) {
971 // First, check for a direct base class.
972 DirectBaseSpec = 0;
973 for (CXXRecordDecl::base_class_const_iterator Base
974 = ClassDecl->bases_begin();
975 Base != ClassDecl->bases_end(); ++Base) {
976 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
977 // We found a direct base of this type. That's what we're
978 // initializing.
979 DirectBaseSpec = &*Base;
980 break;
981 }
982 }
983
984 // Check for a virtual base class.
985 // FIXME: We might be able to short-circuit this if we know in advance that
986 // there are no virtual bases.
987 VirtualBaseSpec = 0;
988 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
989 // We haven't found a base yet; search the class hierarchy for a
990 // virtual base class.
991 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
992 /*DetectVirtual=*/false);
993 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
994 BaseType, Paths)) {
995 for (CXXBasePaths::paths_iterator Path = Paths.begin();
996 Path != Paths.end(); ++Path) {
997 if (Path->back().Base->isVirtual()) {
998 VirtualBaseSpec = Path->back().Base;
999 break;
1000 }
1001 }
1002 }
1003 }
1004
1005 return DirectBaseSpec || VirtualBaseSpec;
1006}
1007
Douglas Gregor7ad83902008-11-05 04:29:56 +00001008/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001009Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001010Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001011 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001012 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001013 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001014 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001015 SourceLocation IdLoc,
1016 SourceLocation LParenLoc,
1017 ExprTy **Args, unsigned NumArgs,
1018 SourceLocation *CommaLocs,
1019 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001020 if (!ConstructorD)
1021 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001023 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
1025 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001026 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001027 if (!Constructor) {
1028 // The user wrote a constructor initializer on a function that is
1029 // not a C++ constructor. Ignore the error for now, because we may
1030 // have more member initializers coming; we'll diagnose it just
1031 // once in ActOnMemInitializers.
1032 return true;
1033 }
1034
1035 CXXRecordDecl *ClassDecl = Constructor->getParent();
1036
1037 // C++ [class.base.init]p2:
1038 // Names in a mem-initializer-id are looked up in the scope of the
1039 // constructor’s class and, if not found in that scope, are looked
1040 // up in the scope containing the constructor’s
1041 // definition. [Note: if the constructor’s class contains a member
1042 // with the same name as a direct or virtual base class of the
1043 // class, a mem-initializer-id naming the member or base class and
1044 // composed of a single identifier refers to the class member. A
1045 // mem-initializer-id for the hidden base class may be specified
1046 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001047 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001048 // Look for a member, first.
1049 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001050 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001051 = ClassDecl->lookup(MemberOrBase);
1052 if (Result.first != Result.second)
1053 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001054
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001055 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001056
Eli Friedman59c04372009-07-29 19:44:27 +00001057 if (Member)
1058 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001059 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001060 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001062 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001063 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001064
1065 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001066 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001067 } else {
1068 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1069 LookupParsedName(R, S, &SS);
1070
1071 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1072 if (!TyD) {
1073 if (R.isAmbiguous()) return true;
1074
Douglas Gregor7a886e12010-01-19 06:46:48 +00001075 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1076 bool NotUnknownSpecialization = false;
1077 DeclContext *DC = computeDeclContext(SS, false);
1078 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1079 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1080
1081 if (!NotUnknownSpecialization) {
1082 // When the scope specifier can refer to a member of an unknown
1083 // specialization, we take it as a type name.
1084 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1085 *MemberOrBase, SS.getRange());
1086 R.clear();
1087 }
1088 }
1089
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001090 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001091 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001092 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1093 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1094 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1095 // We have found a non-static data member with a similar
1096 // name to what was typed; complain and initialize that
1097 // member.
1098 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1099 << MemberOrBase << true << R.getLookupName()
1100 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1101 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001102 Diag(Member->getLocation(), diag::note_previous_decl)
1103 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001104
1105 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1106 LParenLoc, RParenLoc);
1107 }
1108 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1109 const CXXBaseSpecifier *DirectBaseSpec;
1110 const CXXBaseSpecifier *VirtualBaseSpec;
1111 if (FindBaseInitializer(*this, ClassDecl,
1112 Context.getTypeDeclType(Type),
1113 DirectBaseSpec, VirtualBaseSpec)) {
1114 // We have found a direct or virtual base class with a
1115 // similar name to what was typed; complain and initialize
1116 // that base class.
1117 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1118 << MemberOrBase << false << R.getLookupName()
1119 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1120 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001121
1122 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1123 : VirtualBaseSpec;
1124 Diag(BaseSpec->getSourceRange().getBegin(),
1125 diag::note_base_class_specified_here)
1126 << BaseSpec->getType()
1127 << BaseSpec->getSourceRange();
1128
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001129 TyD = Type;
1130 }
1131 }
1132 }
1133
Douglas Gregor7a886e12010-01-19 06:46:48 +00001134 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001135 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1136 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1137 return true;
1138 }
John McCall2b194412009-12-21 10:41:20 +00001139 }
1140
Douglas Gregor7a886e12010-01-19 06:46:48 +00001141 if (BaseType.isNull()) {
1142 BaseType = Context.getTypeDeclType(TyD);
1143 if (SS.isSet()) {
1144 NestedNameSpecifier *Qualifier =
1145 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001146
Douglas Gregor7a886e12010-01-19 06:46:48 +00001147 // FIXME: preserve source range information
1148 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1149 }
John McCall2b194412009-12-21 10:41:20 +00001150 }
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCalla93c9342009-12-07 02:54:59 +00001153 if (!TInfo)
1154 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001155
John McCalla93c9342009-12-07 02:54:59 +00001156 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001157 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001158}
1159
John McCallb4190042009-11-04 23:02:40 +00001160/// Checks an initializer expression for use of uninitialized fields, such as
1161/// containing the field that is being initialized. Returns true if there is an
1162/// uninitialized field was used an updates the SourceLocation parameter; false
1163/// otherwise.
1164static bool InitExprContainsUninitializedFields(const Stmt* S,
1165 const FieldDecl* LhsField,
1166 SourceLocation* L) {
1167 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1168 if (ME) {
1169 const NamedDecl* RhsField = ME->getMemberDecl();
1170 if (RhsField == LhsField) {
1171 // Initializing a field with itself. Throw a warning.
1172 // But wait; there are exceptions!
1173 // Exception #1: The field may not belong to this record.
1174 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1175 const Expr* base = ME->getBase();
1176 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1177 // Even though the field matches, it does not belong to this record.
1178 return false;
1179 }
1180 // None of the exceptions triggered; return true to indicate an
1181 // uninitialized field was used.
1182 *L = ME->getMemberLoc();
1183 return true;
1184 }
1185 }
1186 bool found = false;
1187 for (Stmt::const_child_iterator it = S->child_begin();
1188 it != S->child_end() && found == false;
1189 ++it) {
1190 if (isa<CallExpr>(S)) {
1191 // Do not descend into function calls or constructors, as the use
1192 // of an uninitialized field may be valid. One would have to inspect
1193 // the contents of the function/ctor to determine if it is safe or not.
1194 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1195 // may be safe, depending on what the function/ctor does.
1196 continue;
1197 }
1198 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1199 }
1200 return found;
1201}
1202
Eli Friedman59c04372009-07-29 19:44:27 +00001203Sema::MemInitResult
1204Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1205 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001206 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001207 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001208 // Diagnose value-uses of fields to initialize themselves, e.g.
1209 // foo(foo)
1210 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001211 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001212 for (unsigned i = 0; i < NumArgs; ++i) {
1213 SourceLocation L;
1214 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1215 // FIXME: Return true in the case when other fields are used before being
1216 // uninitialized. For example, let this field be the i'th field. When
1217 // initializing the i'th field, throw a warning if any of the >= i'th
1218 // fields are used, as they are not yet initialized.
1219 // Right now we are only handling the case where the i'th field uses
1220 // itself in its initializer.
1221 Diag(L, diag::warn_field_is_uninit);
1222 }
1223 }
1224
Eli Friedman59c04372009-07-29 19:44:27 +00001225 bool HasDependentArg = false;
1226 for (unsigned i = 0; i < NumArgs; i++)
1227 HasDependentArg |= Args[i]->isTypeDependent();
1228
Eli Friedman59c04372009-07-29 19:44:27 +00001229 QualType FieldType = Member->getType();
1230 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1231 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001232 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001233 if (FieldType->isDependentType() || HasDependentArg) {
1234 // Can't check initialization for a member of dependent type or when
1235 // any of the arguments are type-dependent expressions.
1236 OwningExprResult Init
1237 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1238 RParenLoc));
1239
1240 // Erase any temporaries within this evaluation context; we're not
1241 // going to track them in the AST, since we'll be rebuilding the
1242 // ASTs during template instantiation.
1243 ExprTemporaries.erase(
1244 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1245 ExprTemporaries.end());
1246
1247 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1248 LParenLoc,
1249 Init.takeAs<Expr>(),
1250 RParenLoc);
1251
Douglas Gregor7ad83902008-11-05 04:29:56 +00001252 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001253
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001254 if (Member->isInvalidDecl())
1255 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001256
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001257 // Initialize the member.
1258 InitializedEntity MemberEntity =
1259 InitializedEntity::InitializeMember(Member, 0);
1260 InitializationKind Kind =
1261 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1262
1263 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1264
1265 OwningExprResult MemberInit =
1266 InitSeq.Perform(*this, MemberEntity, Kind,
1267 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1268 if (MemberInit.isInvalid())
1269 return true;
1270
1271 // C++0x [class.base.init]p7:
1272 // The initialization of each base and member constitutes a
1273 // full-expression.
1274 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1275 if (MemberInit.isInvalid())
1276 return true;
1277
1278 // If we are in a dependent context, template instantiation will
1279 // perform this type-checking again. Just save the arguments that we
1280 // received in a ParenListExpr.
1281 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1282 // of the information that we have about the member
1283 // initializer. However, deconstructing the ASTs is a dicey process,
1284 // and this approach is far more likely to get the corner cases right.
1285 if (CurContext->isDependentContext()) {
1286 // Bump the reference count of all of the arguments.
1287 for (unsigned I = 0; I != NumArgs; ++I)
1288 Args[I]->Retain();
1289
1290 OwningExprResult Init
1291 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1292 RParenLoc));
1293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1294 LParenLoc,
1295 Init.takeAs<Expr>(),
1296 RParenLoc);
1297 }
1298
Douglas Gregor802ab452009-12-02 22:36:29 +00001299 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001300 LParenLoc,
1301 MemberInit.takeAs<Expr>(),
1302 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001303}
1304
1305Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001306Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001307 Expr **Args, unsigned NumArgs,
1308 SourceLocation LParenLoc, SourceLocation RParenLoc,
1309 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001310 bool HasDependentArg = false;
1311 for (unsigned i = 0; i < NumArgs; i++)
1312 HasDependentArg |= Args[i]->isTypeDependent();
1313
John McCalla93c9342009-12-07 02:54:59 +00001314 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315 if (BaseType->isDependentType() || HasDependentArg) {
1316 // Can't check initialization for a base of dependent type or when
1317 // any of the arguments are type-dependent expressions.
1318 OwningExprResult BaseInit
1319 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1320 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001321
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001322 // Erase any temporaries within this evaluation context; we're not
1323 // going to track them in the AST, since we'll be rebuilding the
1324 // ASTs during template instantiation.
1325 ExprTemporaries.erase(
1326 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1327 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001329 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1330 LParenLoc,
1331 BaseInit.takeAs<Expr>(),
1332 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001333 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001334
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001335 if (!BaseType->isRecordType())
1336 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1337 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1338
1339 // C++ [class.base.init]p2:
1340 // [...] Unless the mem-initializer-id names a nonstatic data
1341 // member of the constructor’s class or a direct or virtual base
1342 // of that class, the mem-initializer is ill-formed. A
1343 // mem-initializer-list can initialize a base class using any
1344 // name that denotes that base class type.
1345
1346 // Check for direct and virtual base classes.
1347 const CXXBaseSpecifier *DirectBaseSpec = 0;
1348 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1349 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1350 VirtualBaseSpec);
1351
1352 // C++ [base.class.init]p2:
1353 // If a mem-initializer-id is ambiguous because it designates both
1354 // a direct non-virtual base class and an inherited virtual base
1355 // class, the mem-initializer is ill-formed.
1356 if (DirectBaseSpec && VirtualBaseSpec)
1357 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1358 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1359 // C++ [base.class.init]p2:
1360 // Unless the mem-initializer-id names a nonstatic data membeer of the
1361 // constructor's class ot a direst or virtual base of that class, the
1362 // mem-initializer is ill-formed.
1363 if (!DirectBaseSpec && !VirtualBaseSpec)
1364 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1365 << BaseType << ClassDecl->getNameAsCString()
1366 << BaseTInfo->getTypeLoc().getSourceRange();
1367
1368 CXXBaseSpecifier *BaseSpec
1369 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1370 if (!BaseSpec)
1371 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1372
1373 // Initialize the base.
1374 InitializedEntity BaseEntity =
1375 InitializedEntity::InitializeBase(Context, BaseSpec);
1376 InitializationKind Kind =
1377 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1378
1379 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1380
1381 OwningExprResult BaseInit =
1382 InitSeq.Perform(*this, BaseEntity, Kind,
1383 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1384 if (BaseInit.isInvalid())
1385 return true;
1386
1387 // C++0x [class.base.init]p7:
1388 // The initialization of each base and member constitutes a
1389 // full-expression.
1390 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1391 if (BaseInit.isInvalid())
1392 return true;
1393
1394 // If we are in a dependent context, template instantiation will
1395 // perform this type-checking again. Just save the arguments that we
1396 // received in a ParenListExpr.
1397 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1398 // of the information that we have about the base
1399 // initializer. However, deconstructing the ASTs is a dicey process,
1400 // and this approach is far more likely to get the corner cases right.
1401 if (CurContext->isDependentContext()) {
1402 // Bump the reference count of all of the arguments.
1403 for (unsigned I = 0; I != NumArgs; ++I)
1404 Args[I]->Retain();
1405
1406 OwningExprResult Init
1407 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1408 RParenLoc));
1409 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1410 LParenLoc,
1411 Init.takeAs<Expr>(),
1412 RParenLoc);
1413 }
1414
1415 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1416 LParenLoc,
1417 BaseInit.takeAs<Expr>(),
1418 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001419}
1420
Eli Friedman80c30da2009-11-09 19:20:36 +00001421bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001422Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 CXXBaseOrMemberInitializer **Initializers,
1424 unsigned NumInitializers,
1425 bool IsImplicitConstructor,
1426 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001427 // We need to build the initializer AST according to order of construction
1428 // and not what user specified in the Initializers list.
1429 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1430 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1431 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1432 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001433 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001435 for (unsigned i = 0; i < NumInitializers; i++) {
1436 CXXBaseOrMemberInitializer *Member = Initializers[i];
1437 if (Member->isBaseInitializer()) {
1438 if (Member->getBaseClass()->isDependentType())
1439 HasDependentBaseInit = true;
1440 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1441 } else {
1442 AllBaseFields[Member->getMember()] = Member;
1443 }
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001446 if (HasDependentBaseInit) {
1447 // FIXME. This does not preserve the ordering of the initializers.
1448 // Try (with -Wreorder)
1449 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001450 // template<class X> struct B : A<X> {
1451 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001452 // int x1;
1453 // };
1454 // B<int> x;
1455 // On seeing one dependent type, we should essentially exit this routine
1456 // while preserving user-declared initializer list. When this routine is
1457 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001458 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001460 // If we have a dependent base initialization, we can't determine the
1461 // association between initializers and bases; just dump the known
1462 // initializers into the list, and don't try to deal with other bases.
1463 for (unsigned i = 0; i < NumInitializers; i++) {
1464 CXXBaseOrMemberInitializer *Member = Initializers[i];
1465 if (Member->isBaseInitializer())
1466 AllToInit.push_back(Member);
1467 }
1468 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001469 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1470
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001471 // Push virtual bases before others.
1472 for (CXXRecordDecl::base_class_iterator VBase =
1473 ClassDecl->vbases_begin(),
1474 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1475 if (VBase->getType()->isDependentType())
1476 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001477 if (CXXBaseOrMemberInitializer *Value
1478 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001479 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001480 } else if (!AnyErrors) {
1481 InitializedEntity InitEntity
1482 = InitializedEntity::InitializeBase(Context, VBase);
1483 InitializationKind InitKind
1484 = InitializationKind::CreateDefault(Constructor->getLocation());
1485 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1486 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1487 MultiExprArg(*this, 0, 0));
1488 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1489 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001490 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001491 continue;
1492 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001493
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001494 // Don't attach synthesized base initializers in a dependent
1495 // context; they'll be checked again at template instantiation
1496 // time.
1497 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001498 continue;
1499
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001500 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001501 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001502 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001503 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001504 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001505 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001506 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001507 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 }
1509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001511 for (CXXRecordDecl::base_class_iterator Base =
1512 ClassDecl->bases_begin(),
1513 E = ClassDecl->bases_end(); Base != E; ++Base) {
1514 // Virtuals are in the virtual base list and already constructed.
1515 if (Base->isVirtual())
1516 continue;
1517 // Skip dependent types.
1518 if (Base->getType()->isDependentType())
1519 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001520 if (CXXBaseOrMemberInitializer *Value
1521 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001522 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001523 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001524 else if (!AnyErrors) {
1525 InitializedEntity InitEntity
1526 = InitializedEntity::InitializeBase(Context, Base);
1527 InitializationKind InitKind
1528 = InitializationKind::CreateDefault(Constructor->getLocation());
1529 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1530 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1531 MultiExprArg(*this, 0, 0));
1532 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1533 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001534 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001535 continue;
1536 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001537
1538 // Don't attach synthesized base initializers in a dependent
1539 // context; they'll be regenerated at template instantiation
1540 // time.
1541 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001542 continue;
1543
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001544 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001545 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001546 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001547 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001548 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001549 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001550 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001551 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001552 }
1553 }
1554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001556 // non-static data members.
1557 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1558 E = ClassDecl->field_end(); Field != E; ++Field) {
1559 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001560 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001561 Field->getType()->getAs<RecordType>()) {
1562 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001563 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001564 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001565 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1566 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1567 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1568 // set to the anonymous union data member used in the initializer
1569 // list.
1570 Value->setMember(*Field);
1571 Value->setAnonUnionMember(*FA);
1572 AllToInit.push_back(Value);
1573 break;
1574 }
1575 }
1576 }
1577 continue;
1578 }
1579 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1580 AllToInit.push_back(Value);
1581 continue;
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001584 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001585 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001586
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001587 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001588 if (FT->getAs<RecordType>()) {
1589 InitializedEntity InitEntity
1590 = InitializedEntity::InitializeMember(*Field);
1591 InitializationKind InitKind
1592 = InitializationKind::CreateDefault(Constructor->getLocation());
1593
1594 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1595 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1596 MultiExprArg(*this, 0, 0));
1597 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1598 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001599 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001600 continue;
1601 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001602
1603 // Don't attach synthesized member initializers in a dependent
1604 // context; they'll be regenerated a template instantiation
1605 // time.
1606 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001607 continue;
1608
Mike Stump1eb44332009-09-09 15:08:12 +00001609 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001610 new (Context) CXXBaseOrMemberInitializer(Context,
1611 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001612 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001613 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001614 SourceLocation());
1615
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001616 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001617 }
1618 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001619 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001620 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1621 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001622 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001623 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001624 }
1625 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001626 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001627 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1628 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001629 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001630 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001631 }
1632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001634 NumInitializers = AllToInit.size();
1635 if (NumInitializers > 0) {
1636 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1637 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1638 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001640 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1641 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1642 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1643 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001644
1645 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001646}
1647
Eli Friedman6347f422009-07-21 19:28:10 +00001648static void *GetKeyForTopLevelField(FieldDecl *Field) {
1649 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001650 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001651 if (RT->getDecl()->isAnonymousStructOrUnion())
1652 return static_cast<void *>(RT->getDecl());
1653 }
1654 return static_cast<void *>(Field);
1655}
1656
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001657static void *GetKeyForBase(QualType BaseType) {
1658 if (const RecordType *RT = BaseType->getAs<RecordType>())
1659 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001661 assert(0 && "Unexpected base type!");
1662 return 0;
1663}
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001666 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001667 // For fields injected into the class via declaration of an anonymous union,
1668 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001669 if (Member->isMemberInitializer()) {
1670 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Eli Friedman49c16da2009-11-09 01:05:47 +00001672 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001673 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001674 // in AnonUnionMember field.
1675 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1676 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001677 if (Field->getDeclContext()->isRecord()) {
1678 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1679 if (RD->isAnonymousStructOrUnion())
1680 return static_cast<void *>(RD);
1681 }
1682 return static_cast<void *>(Field);
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001685 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001686}
1687
John McCall6aee6212009-11-04 23:13:52 +00001688/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001689void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001690 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001691 MemInitTy **MemInits, unsigned NumMemInits,
1692 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001693 if (!ConstructorDecl)
1694 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001695
1696 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001697
1698 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001699 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Anders Carlssona7b35212009-03-25 02:58:17 +00001701 if (!Constructor) {
1702 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1703 return;
1704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001706 if (!Constructor->isDependentContext()) {
1707 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1708 bool err = false;
1709 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001710 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001711 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1712 void *KeyToMember = GetKeyForMember(Member);
1713 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1714 if (!PrevMember) {
1715 PrevMember = Member;
1716 continue;
1717 }
1718 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001719 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001720 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001721 << Field->getNameAsString()
1722 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001723 else {
1724 Type *BaseClass = Member->getBaseClass();
1725 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001726 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001727 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001728 << QualType(BaseClass, 0)
1729 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001730 }
1731 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1732 << 0;
1733 err = true;
1734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001736 if (err)
1737 return;
1738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Eli Friedman49c16da2009-11-09 01:05:47 +00001740 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001741 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001742 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001744 if (Constructor->isDependentContext())
1745 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001746
1747 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001748 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001749 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001750 Diagnostic::Ignored)
1751 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001753 // Also issue warning if order of ctor-initializer list does not match order
1754 // of 1) base class declarations and 2) order of non-static data members.
1755 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001756
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001757 CXXRecordDecl *ClassDecl
1758 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1759 // Push virtual bases before others.
1760 for (CXXRecordDecl::base_class_iterator VBase =
1761 ClassDecl->vbases_begin(),
1762 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001763 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1766 E = ClassDecl->bases_end(); Base != E; ++Base) {
1767 // Virtuals are alread in the virtual base list and are constructed
1768 // first.
1769 if (Base->isVirtual())
1770 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001771 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001774 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1775 E = ClassDecl->field_end(); Field != E; ++Field)
1776 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001778 int Last = AllBaseOrMembers.size();
1779 int curIndex = 0;
1780 CXXBaseOrMemberInitializer *PrevMember = 0;
1781 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001782 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001783 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1784 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001785
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001786 for (; curIndex < Last; curIndex++)
1787 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1788 break;
1789 if (curIndex == Last) {
1790 assert(PrevMember && "Member not in member list?!");
1791 // Initializer as specified in ctor-initializer list is out of order.
1792 // Issue a warning diagnostic.
1793 if (PrevMember->isBaseInitializer()) {
1794 // Diagnostics is for an initialized base class.
1795 Type *BaseClass = PrevMember->getBaseClass();
1796 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001797 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001798 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001799 } else {
1800 FieldDecl *Field = PrevMember->getMember();
1801 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001802 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001803 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001804 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 // Also the note!
1806 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001807 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001808 diag::note_fieldorbase_initialized_here) << 0
1809 << Field->getNameAsString();
1810 else {
1811 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001812 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001813 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001814 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001815 }
1816 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001817 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001818 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001819 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001820 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001821 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001822}
1823
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001824void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001825Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1826 // Ignore dependent destructors.
1827 if (Destructor->isDependentContext())
1828 return;
1829
1830 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anders Carlsson9f853df2009-11-17 04:44:12 +00001832 // Non-static data members.
1833 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1834 E = ClassDecl->field_end(); I != E; ++I) {
1835 FieldDecl *Field = *I;
1836
1837 QualType FieldType = Context.getBaseElementType(Field->getType());
1838
1839 const RecordType* RT = FieldType->getAs<RecordType>();
1840 if (!RT)
1841 continue;
1842
1843 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1844 if (FieldClassDecl->hasTrivialDestructor())
1845 continue;
1846
1847 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1848 MarkDeclarationReferenced(Destructor->getLocation(),
1849 const_cast<CXXDestructorDecl*>(Dtor));
1850 }
1851
1852 // Bases.
1853 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1854 E = ClassDecl->bases_end(); Base != E; ++Base) {
1855 // Ignore virtual bases.
1856 if (Base->isVirtual())
1857 continue;
1858
1859 // Ignore trivial destructors.
1860 CXXRecordDecl *BaseClassDecl
1861 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1862 if (BaseClassDecl->hasTrivialDestructor())
1863 continue;
1864
1865 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1866 MarkDeclarationReferenced(Destructor->getLocation(),
1867 const_cast<CXXDestructorDecl*>(Dtor));
1868 }
1869
1870 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001871 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1872 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001873 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001874 CXXRecordDecl *BaseClassDecl
1875 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1876 if (BaseClassDecl->hasTrivialDestructor())
1877 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001878
1879 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1880 MarkDeclarationReferenced(Destructor->getLocation(),
1881 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001882 }
1883}
1884
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001885void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001886 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001887 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001889 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
1891 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001892 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001893 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001894}
1895
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001896namespace {
1897 /// PureVirtualMethodCollector - traverses a class and its superclasses
1898 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001899 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001900 ASTContext &Context;
1901
Sebastian Redldfe292d2009-03-22 21:28:55 +00001902 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001903 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001904
1905 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001906 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001908 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001910 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001911 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001912 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001914 MethodList List;
1915 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001917 // Copy the temporary list to methods, and make sure to ignore any
1918 // null entries.
1919 for (size_t i = 0, e = List.size(); i != e; ++i) {
1920 if (List[i])
1921 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001922 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001923 }
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001925 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001927 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1928 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001929 };
Mike Stump1eb44332009-09-09 15:08:12 +00001930
1931 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001932 MethodList& Methods) {
1933 // First, collect the pure virtual methods for the base classes.
1934 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1935 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001936 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001937 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001938 if (BaseDecl && BaseDecl->isAbstract())
1939 Collect(BaseDecl, Methods);
1940 }
1941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001943 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001944 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001946 MethodSetTy OverriddenMethods;
1947 size_t MethodsSize = Methods.size();
1948
Mike Stump1eb44332009-09-09 15:08:12 +00001949 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001950 i != e; ++i) {
1951 // Traverse the record, looking for methods.
1952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001953 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001954 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001955 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Anders Carlsson27823022009-10-18 19:34:08 +00001957 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001958 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1959 E = MD->end_overridden_methods(); I != E; ++I) {
1960 // Keep track of the overridden methods.
1961 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001962 }
1963 }
1964 }
Mike Stump1eb44332009-09-09 15:08:12 +00001965
1966 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001967 // overridden.
1968 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1969 if (OverriddenMethods.count(Methods[i]))
1970 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001973 }
1974}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001975
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001976
Mike Stump1eb44332009-09-09 15:08:12 +00001977bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001978 unsigned DiagID, AbstractDiagSelID SelID,
1979 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001980 if (SelID == -1)
1981 return RequireNonAbstractType(Loc, T,
1982 PDiag(DiagID), CurrentRD);
1983 else
1984 return RequireNonAbstractType(Loc, T,
1985 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001986}
1987
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001988bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1989 const PartialDiagnostic &PD,
1990 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001991 if (!getLangOptions().CPlusPlus)
1992 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Anders Carlsson11f21a02009-03-23 19:10:31 +00001994 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001995 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001996 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenek6217b802009-07-29 21:53:49 +00001998 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001999 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002000 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002001 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002003 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002004 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenek6217b802009-07-29 21:53:49 +00002007 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002008 if (!RT)
2009 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002010
John McCall86ff3082010-02-04 22:26:26 +00002011 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002012
Anders Carlssone65a3c82009-03-24 17:23:42 +00002013 if (CurrentRD && CurrentRD != RD)
2014 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002015
John McCall86ff3082010-02-04 22:26:26 +00002016 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002017 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002018 return false;
2019
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002020 if (!RD->isAbstract())
2021 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002023 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002025 // Check if we've already emitted the list of pure virtual functions for this
2026 // class.
2027 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2028 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002030 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002031
2032 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002033 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2034 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002035
2036 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002037 MD->getDeclName();
2038 }
2039
2040 if (!PureVirtualClassDiagSet)
2041 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2042 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002044 return true;
2045}
2046
Anders Carlsson8211eff2009-03-24 01:19:16 +00002047namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002048 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002049 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2050 Sema &SemaRef;
2051 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Anders Carlssone65a3c82009-03-24 17:23:42 +00002053 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002054 bool Invalid = false;
2055
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002056 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2057 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002058 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002059
Anders Carlsson8211eff2009-03-24 01:19:16 +00002060 return Invalid;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Anders Carlssone65a3c82009-03-24 17:23:42 +00002063 public:
2064 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2065 : SemaRef(SemaRef), AbstractClass(ac) {
2066 Visit(SemaRef.Context.getTranslationUnitDecl());
2067 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002068
Anders Carlssone65a3c82009-03-24 17:23:42 +00002069 bool VisitFunctionDecl(const FunctionDecl *FD) {
2070 if (FD->isThisDeclarationADefinition()) {
2071 // No need to do the check if we're in a definition, because it requires
2072 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002073 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002074 return VisitDeclContext(FD);
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Anders Carlssone65a3c82009-03-24 17:23:42 +00002077 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002078 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002079 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002080 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2081 diag::err_abstract_type_in_decl,
2082 Sema::AbstractReturnType,
2083 AbstractClass);
2084
Mike Stump1eb44332009-09-09 15:08:12 +00002085 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002086 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002087 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002088 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002089 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002090 VD->getOriginalType(),
2091 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002092 Sema::AbstractParamType,
2093 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002094 }
2095
2096 return Invalid;
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Anders Carlssone65a3c82009-03-24 17:23:42 +00002099 bool VisitDecl(const Decl* D) {
2100 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2101 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Anders Carlssone65a3c82009-03-24 17:23:42 +00002103 return false;
2104 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002105 };
2106}
2107
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002108/// \brief Perform semantic checks on a class definition that has been
2109/// completing, introducing implicitly-declared members, checking for
2110/// abstract types, etc.
2111void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2112 if (!Record || Record->isInvalidDecl())
2113 return;
2114
Eli Friedmanff2d8782009-12-16 20:00:27 +00002115 if (!Record->isDependentType())
2116 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002117
Eli Friedmanff2d8782009-12-16 20:00:27 +00002118 if (Record->isInvalidDecl())
2119 return;
2120
John McCall233a6412010-01-28 07:38:46 +00002121 // Set access bits correctly on the directly-declared conversions.
2122 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2123 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2124 Convs->setAccess(I, (*I)->getAccess());
2125
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002126 if (!Record->isAbstract()) {
2127 // Collect all the pure virtual methods and see if this is an abstract
2128 // class after all.
2129 PureVirtualMethodCollector Collector(Context, Record);
2130 if (!Collector.empty())
2131 Record->setAbstract(true);
2132 }
2133
2134 if (Record->isAbstract())
2135 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002136}
2137
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002138void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002139 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002140 SourceLocation LBrac,
2141 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002142 if (!TagDecl)
2143 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Douglas Gregor42af25f2009-05-11 19:58:34 +00002145 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002146
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002147 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002148 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002149 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002150
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002151 CheckCompletedCXXClass(
2152 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002153}
2154
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002155/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2156/// special functions, such as the default constructor, copy
2157/// constructor, or destructor, to the given C++ class (C++
2158/// [special]p1). This routine can only be executed just before the
2159/// definition of the class is complete.
2160void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002161 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002163
Sebastian Redl465226e2009-05-27 22:11:52 +00002164 // FIXME: Implicit declarations have exception specifications, which are
2165 // the union of the specifications of the implicitly called functions.
2166
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002167 if (!ClassDecl->hasUserDeclaredConstructor()) {
2168 // C++ [class.ctor]p5:
2169 // A default constructor for a class X is a constructor of class X
2170 // that can be called without an argument. If there is no
2171 // user-declared constructor for class X, a default constructor is
2172 // implicitly declared. An implicitly-declared default constructor
2173 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002174 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002175 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002176 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002177 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002178 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002179 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002180 0, 0, false, 0,
2181 /*FIXME*/false, false,
2182 0, 0, false,
2183 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002184 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002185 /*isExplicit=*/false,
2186 /*isInline=*/true,
2187 /*isImplicitlyDeclared=*/true);
2188 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002189 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002190 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002191 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002192 }
2193
2194 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2195 // C++ [class.copy]p4:
2196 // If the class definition does not explicitly declare a copy
2197 // constructor, one is declared implicitly.
2198
2199 // C++ [class.copy]p5:
2200 // The implicitly-declared copy constructor for a class X will
2201 // have the form
2202 //
2203 // X::X(const X&)
2204 //
2205 // if
2206 bool HasConstCopyConstructor = true;
2207
2208 // -- each direct or virtual base class B of X has a copy
2209 // constructor whose first parameter is of type const B& or
2210 // const volatile B&, and
2211 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2212 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2213 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002214 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002215 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002216 = BaseClassDecl->hasConstCopyConstructor(Context);
2217 }
2218
2219 // -- for all the nonstatic data members of X that are of a
2220 // class type M (or array thereof), each such class type
2221 // has a copy constructor whose first parameter is of type
2222 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002223 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2224 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002225 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002226 QualType FieldType = (*Field)->getType();
2227 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2228 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002229 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002230 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002231 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002232 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002233 = FieldClassDecl->hasConstCopyConstructor(Context);
2234 }
2235 }
2236
Sebastian Redl64b45f72009-01-05 20:52:13 +00002237 // Otherwise, the implicitly declared copy constructor will have
2238 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002239 //
2240 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002241 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002242 if (HasConstCopyConstructor)
2243 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002244 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002245
Sebastian Redl64b45f72009-01-05 20:52:13 +00002246 // An implicitly-declared copy constructor is an inline public
2247 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002248 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002249 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002250 CXXConstructorDecl *CopyConstructor
2251 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002252 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002253 Context.getFunctionType(Context.VoidTy,
2254 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002255 false, 0,
2256 /*FIXME:*/false,
2257 false, 0, 0, false,
2258 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002259 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002260 /*isExplicit=*/false,
2261 /*isInline=*/true,
2262 /*isImplicitlyDeclared=*/true);
2263 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002264 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002265 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002266
2267 // Add the parameter to the constructor.
2268 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2269 ClassDecl->getLocation(),
2270 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002271 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002272 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002273 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002274 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002275 }
2276
Sebastian Redl64b45f72009-01-05 20:52:13 +00002277 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2278 // Note: The following rules are largely analoguous to the copy
2279 // constructor rules. Note that virtual bases are not taken into account
2280 // for determining the argument type of the operator. Note also that
2281 // operators taking an object instead of a reference are allowed.
2282 //
2283 // C++ [class.copy]p10:
2284 // If the class definition does not explicitly declare a copy
2285 // assignment operator, one is declared implicitly.
2286 // The implicitly-defined copy assignment operator for a class X
2287 // will have the form
2288 //
2289 // X& X::operator=(const X&)
2290 //
2291 // if
2292 bool HasConstCopyAssignment = true;
2293
2294 // -- each direct base class B of X has a copy assignment operator
2295 // whose parameter is of type const B&, const volatile B& or B,
2296 // and
2297 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2298 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002299 assert(!Base->getType()->isDependentType() &&
2300 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002301 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002302 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002303 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002304 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002305 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002306 }
2307
2308 // -- for all the nonstatic data members of X that are of a class
2309 // type M (or array thereof), each such class type has a copy
2310 // assignment operator whose parameter is of type const M&,
2311 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002312 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2313 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002314 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002315 QualType FieldType = (*Field)->getType();
2316 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2317 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002318 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002319 const CXXRecordDecl *FieldClassDecl
2320 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002321 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002322 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002323 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002324 }
2325 }
2326
2327 // Otherwise, the implicitly declared copy assignment operator will
2328 // have the form
2329 //
2330 // X& X::operator=(X&)
2331 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002332 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002333 if (HasConstCopyAssignment)
2334 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002335 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002336
2337 // An implicitly-declared copy assignment operator is an inline public
2338 // member of its class.
2339 DeclarationName Name =
2340 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2341 CXXMethodDecl *CopyAssignment =
2342 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2343 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002344 false, 0,
2345 /*FIXME:*/false,
2346 false, 0, 0, false,
2347 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002348 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002349 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002350 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002351 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002352 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002353
2354 // Add the parameter to the operator.
2355 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2356 ClassDecl->getLocation(),
2357 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002358 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002359 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002360 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002361
2362 // Don't call addedAssignmentOperator. There is no way to distinguish an
2363 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002364 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002365 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002366 }
2367
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002368 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002369 // C++ [class.dtor]p2:
2370 // If a class has no user-declared destructor, a destructor is
2371 // declared implicitly. An implicitly-declared destructor is an
2372 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002373 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002374 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002375 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002376 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002377 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002378 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002379 0, 0, false, 0,
2380 /*FIXME:*/false,
2381 false, 0, 0, false,
2382 CC_Default),
Douglas Gregor42a552f2008-11-05 20:51:48 +00002383 /*isInline=*/true,
2384 /*isImplicitlyDeclared=*/true);
2385 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002386 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002387 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002388 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002389
2390 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002391 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002392}
2393
Douglas Gregor6569d682009-05-27 23:11:45 +00002394void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002395 Decl *D = TemplateD.getAs<Decl>();
2396 if (!D)
2397 return;
2398
2399 TemplateParameterList *Params = 0;
2400 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2401 Params = Template->getTemplateParameters();
2402 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2403 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2404 Params = PartialSpec->getTemplateParameters();
2405 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002406 return;
2407
Douglas Gregor6569d682009-05-27 23:11:45 +00002408 for (TemplateParameterList::iterator Param = Params->begin(),
2409 ParamEnd = Params->end();
2410 Param != ParamEnd; ++Param) {
2411 NamedDecl *Named = cast<NamedDecl>(*Param);
2412 if (Named->getDeclName()) {
2413 S->AddDecl(DeclPtrTy::make(Named));
2414 IdResolver.AddDecl(Named);
2415 }
2416 }
2417}
2418
John McCall7a1dc562009-12-19 10:49:29 +00002419void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2420 if (!RecordD) return;
2421 AdjustDeclIfTemplate(RecordD);
2422 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2423 PushDeclContext(S, Record);
2424}
2425
2426void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2427 if (!RecordD) return;
2428 PopDeclContext();
2429}
2430
Douglas Gregor72b505b2008-12-16 21:30:33 +00002431/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2432/// parsing a top-level (non-nested) C++ class, and we are now
2433/// parsing those parts of the given Method declaration that could
2434/// not be parsed earlier (C++ [class.mem]p2), such as default
2435/// arguments. This action should enter the scope of the given
2436/// Method declaration as if we had just parsed the qualified method
2437/// name. However, it should not bring the parameters into scope;
2438/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002439void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002440}
2441
2442/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2443/// C++ method declaration. We're (re-)introducing the given
2444/// function parameter into scope for use in parsing later parts of
2445/// the method declaration. For example, we could see an
2446/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002447void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002448 if (!ParamD)
2449 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Chris Lattnerb28317a2009-03-28 19:18:32 +00002451 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002452
2453 // If this parameter has an unparsed default argument, clear it out
2454 // to make way for the parsed default argument.
2455 if (Param->hasUnparsedDefaultArg())
2456 Param->setDefaultArg(0);
2457
Chris Lattnerb28317a2009-03-28 19:18:32 +00002458 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002459 if (Param->getDeclName())
2460 IdResolver.AddDecl(Param);
2461}
2462
2463/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2464/// processing the delayed method declaration for Method. The method
2465/// declaration is now considered finished. There may be a separate
2466/// ActOnStartOfFunctionDef action later (not necessarily
2467/// immediately!) for this method, if it was also defined inside the
2468/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002469void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002470 if (!MethodD)
2471 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002473 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Chris Lattnerb28317a2009-03-28 19:18:32 +00002475 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002476
2477 // Now that we have our default arguments, check the constructor
2478 // again. It could produce additional diagnostics or affect whether
2479 // the class has implicitly-declared destructors, among other
2480 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002481 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2482 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002483
2484 // Check the default arguments, which we may have added.
2485 if (!Method->isInvalidDecl())
2486 CheckCXXDefaultArguments(Method);
2487}
2488
Douglas Gregor42a552f2008-11-05 20:51:48 +00002489/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002490/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002491/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002492/// emit diagnostics and set the invalid bit to true. In any case, the type
2493/// will be updated to reflect a well-formed type for the constructor and
2494/// returned.
2495QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2496 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002497 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002498
2499 // C++ [class.ctor]p3:
2500 // A constructor shall not be virtual (10.3) or static (9.4). A
2501 // constructor can be invoked for a const, volatile or const
2502 // volatile object. A constructor shall not be declared const,
2503 // volatile, or const volatile (9.3.2).
2504 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002505 if (!D.isInvalidType())
2506 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2507 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2508 << SourceRange(D.getIdentifierLoc());
2509 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002510 }
2511 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002512 if (!D.isInvalidType())
2513 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2514 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2515 << SourceRange(D.getIdentifierLoc());
2516 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002517 SC = FunctionDecl::None;
2518 }
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Chris Lattner65401802009-04-25 08:28:21 +00002520 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2521 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002522 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002523 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2524 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002525 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002526 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2527 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002528 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002529 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2530 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002531 }
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor42a552f2008-11-05 20:51:48 +00002533 // Rebuild the function type "R" without any type qualifiers (in
2534 // case any of the errors above fired) and with "void" as the
2535 // return type, since constructors don't have return types. We
2536 // *always* have to do this, because GetTypeForDeclarator will
2537 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002538 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002539 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2540 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002541 Proto->isVariadic(), 0,
2542 Proto->hasExceptionSpec(),
2543 Proto->hasAnyExceptionSpec(),
2544 Proto->getNumExceptions(),
2545 Proto->exception_begin(),
2546 Proto->getNoReturnAttr(),
2547 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002548}
2549
Douglas Gregor72b505b2008-12-16 21:30:33 +00002550/// CheckConstructor - Checks a fully-formed constructor for
2551/// well-formedness, issuing any diagnostics required. Returns true if
2552/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002553void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002554 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002555 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2556 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002557 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002558
2559 // C++ [class.copy]p3:
2560 // A declaration of a constructor for a class X is ill-formed if
2561 // its first parameter is of type (optionally cv-qualified) X and
2562 // either there are no other parameters or else all other
2563 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002564 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002565 ((Constructor->getNumParams() == 1) ||
2566 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002567 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2568 Constructor->getTemplateSpecializationKind()
2569 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002570 QualType ParamType = Constructor->getParamDecl(0)->getType();
2571 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2572 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002573 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2574 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002575 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002576
2577 // FIXME: Rather that making the constructor invalid, we should endeavor
2578 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002579 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002580 }
2581 }
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Douglas Gregor72b505b2008-12-16 21:30:33 +00002583 // Notify the class that we've added a constructor.
2584 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002585}
2586
Anders Carlsson37909802009-11-30 21:24:50 +00002587/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2588/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002589bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002590 CXXRecordDecl *RD = Destructor->getParent();
2591
2592 if (Destructor->isVirtual()) {
2593 SourceLocation Loc;
2594
2595 if (!Destructor->isImplicit())
2596 Loc = Destructor->getLocation();
2597 else
2598 Loc = RD->getLocation();
2599
2600 // If we have a virtual destructor, look up the deallocation function
2601 FunctionDecl *OperatorDelete = 0;
2602 DeclarationName Name =
2603 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002604 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002605 return true;
2606
2607 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002608 }
Anders Carlsson37909802009-11-30 21:24:50 +00002609
2610 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002611}
2612
Mike Stump1eb44332009-09-09 15:08:12 +00002613static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002614FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2615 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2616 FTI.ArgInfo[0].Param &&
2617 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2618}
2619
Douglas Gregor42a552f2008-11-05 20:51:48 +00002620/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2621/// the well-formednes of the destructor declarator @p D with type @p
2622/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002623/// emit diagnostics and set the declarator to invalid. Even if this happens,
2624/// will be updated to reflect a well-formed type for the destructor and
2625/// returned.
2626QualType Sema::CheckDestructorDeclarator(Declarator &D,
2627 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002628 // C++ [class.dtor]p1:
2629 // [...] A typedef-name that names a class is a class-name
2630 // (7.1.3); however, a typedef-name that names a class shall not
2631 // be used as the identifier in the declarator for a destructor
2632 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002633 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002634 if (isa<TypedefType>(DeclaratorType)) {
2635 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002636 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002637 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002638 }
2639
2640 // C++ [class.dtor]p2:
2641 // A destructor is used to destroy objects of its class type. A
2642 // destructor takes no parameters, and no return type can be
2643 // specified for it (not even void). The address of a destructor
2644 // shall not be taken. A destructor shall not be static. A
2645 // destructor can be invoked for a const, volatile or const
2646 // volatile object. A destructor shall not be declared const,
2647 // volatile or const volatile (9.3.2).
2648 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002649 if (!D.isInvalidType())
2650 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2651 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2652 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002653 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002654 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002655 }
Chris Lattner65401802009-04-25 08:28:21 +00002656 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002657 // Destructors don't have return types, but the parser will
2658 // happily parse something like:
2659 //
2660 // class X {
2661 // float ~X();
2662 // };
2663 //
2664 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002665 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2666 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2667 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Chris Lattner65401802009-04-25 08:28:21 +00002670 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2671 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002672 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002673 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2674 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002675 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002676 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2677 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002678 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002679 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2680 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002681 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002682 }
2683
2684 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002685 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002686 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2687
2688 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002689 FTI.freeArgs();
2690 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002691 }
2692
Mike Stump1eb44332009-09-09 15:08:12 +00002693 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002694 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002695 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002696 D.setInvalidType();
2697 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002698
2699 // Rebuild the function type "R" without any type qualifiers or
2700 // parameters (in case any of the errors above fired) and with
2701 // "void" as the return type, since destructors don't have return
2702 // types. We *always* have to do this, because GetTypeForDeclarator
2703 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002704 // FIXME: Exceptions!
2705 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2706 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002707}
2708
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002709/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2710/// well-formednes of the conversion function declarator @p D with
2711/// type @p R. If there are any errors in the declarator, this routine
2712/// will emit diagnostics and return true. Otherwise, it will return
2713/// false. Either way, the type @p R will be updated to reflect a
2714/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002715void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002716 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002717 // C++ [class.conv.fct]p1:
2718 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002719 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002720 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002721 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002722 if (!D.isInvalidType())
2723 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2724 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2725 << SourceRange(D.getIdentifierLoc());
2726 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002727 SC = FunctionDecl::None;
2728 }
Chris Lattner6e475012009-04-25 08:35:12 +00002729 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002730 // Conversion functions don't have return types, but the parser will
2731 // happily parse something like:
2732 //
2733 // class X {
2734 // float operator bool();
2735 // };
2736 //
2737 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002738 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2739 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2740 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002741 }
2742
2743 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002744 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002745 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2746
2747 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002748 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002749 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002750 }
2751
Mike Stump1eb44332009-09-09 15:08:12 +00002752 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002753 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002754 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002755 D.setInvalidType();
2756 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002757
2758 // C++ [class.conv.fct]p4:
2759 // The conversion-type-id shall not represent a function type nor
2760 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002761 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002762 if (ConvType->isArrayType()) {
2763 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2764 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002765 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002766 } else if (ConvType->isFunctionType()) {
2767 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2768 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002769 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002770 }
2771
2772 // Rebuild the function type "R" without any parameters (in case any
2773 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002774 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002775 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002776 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002777 Proto->getTypeQuals(),
2778 Proto->hasExceptionSpec(),
2779 Proto->hasAnyExceptionSpec(),
2780 Proto->getNumExceptions(),
2781 Proto->exception_begin(),
2782 Proto->getNoReturnAttr(),
2783 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002784
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002785 // C++0x explicit conversion operators.
2786 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002787 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002788 diag::warn_explicit_conversion_functions)
2789 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002790}
2791
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002792/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2793/// the declaration of the given C++ conversion function. This routine
2794/// is responsible for recording the conversion function in the C++
2795/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002796Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002797 assert(Conversion && "Expected to receive a conversion function declaration");
2798
Douglas Gregor9d350972008-12-12 08:25:50 +00002799 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002800
2801 // Make sure we aren't redeclaring the conversion function.
2802 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002803
2804 // C++ [class.conv.fct]p1:
2805 // [...] A conversion function is never used to convert a
2806 // (possibly cv-qualified) object to the (possibly cv-qualified)
2807 // same object type (or a reference to it), to a (possibly
2808 // cv-qualified) base class of that type (or a reference to it),
2809 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002810 // FIXME: Suppress this warning if the conversion function ends up being a
2811 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002812 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002813 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002814 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002815 ConvType = ConvTypeRef->getPointeeType();
2816 if (ConvType->isRecordType()) {
2817 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2818 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002819 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002820 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002821 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002822 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002823 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002824 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002825 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002826 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002827 }
2828
Douglas Gregor48026d22010-01-11 18:40:55 +00002829 if (Conversion->getPrimaryTemplate()) {
2830 // ignore specializations
2831 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002832 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002833 = Conversion->getDescribedFunctionTemplate()) {
2834 if (ClassDecl->replaceConversion(
2835 ConversionTemplate->getPreviousDeclaration(),
2836 ConversionTemplate))
2837 return DeclPtrTy::make(ConversionTemplate);
2838 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2839 Conversion))
John McCallba135432009-11-21 08:51:07 +00002840 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002841 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002842 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002843 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002844 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002845 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002846 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002847
Chris Lattnerb28317a2009-03-28 19:18:32 +00002848 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002849}
2850
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002851//===----------------------------------------------------------------------===//
2852// Namespace Handling
2853//===----------------------------------------------------------------------===//
2854
2855/// ActOnStartNamespaceDef - This is called at the start of a namespace
2856/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002857Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2858 SourceLocation IdentLoc,
2859 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002860 SourceLocation LBrace,
2861 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002862 NamespaceDecl *Namespc =
2863 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2864 Namespc->setLBracLoc(LBrace);
2865
2866 Scope *DeclRegionScope = NamespcScope->getParent();
2867
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002868 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2869
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002870 if (II) {
2871 // C++ [namespace.def]p2:
2872 // The identifier in an original-namespace-definition shall not have been
2873 // previously defined in the declarative region in which the
2874 // original-namespace-definition appears. The identifier in an
2875 // original-namespace-definition is the name of the namespace. Subsequently
2876 // in that declarative region, it is treated as an original-namespace-name.
2877
John McCallf36e02d2009-10-09 21:13:30 +00002878 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002879 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002880 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002881
Douglas Gregor44b43212008-12-11 16:49:14 +00002882 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2883 // This is an extended namespace definition.
2884 // Attach this namespace decl to the chain of extended namespace
2885 // definitions.
2886 OrigNS->setNextNamespace(Namespc);
2887 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002888
Mike Stump1eb44332009-09-09 15:08:12 +00002889 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002890 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002891 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002892 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002893 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002894 } else if (PrevDecl) {
2895 // This is an invalid name redefinition.
2896 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2897 << Namespc->getDeclName();
2898 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2899 Namespc->setInvalidDecl();
2900 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002901 } else if (II->isStr("std") &&
2902 CurContext->getLookupContext()->isTranslationUnit()) {
2903 // This is the first "real" definition of the namespace "std", so update
2904 // our cache of the "std" namespace to point at this definition.
2905 if (StdNamespace) {
2906 // We had already defined a dummy namespace "std". Link this new
2907 // namespace definition to the dummy namespace "std".
2908 StdNamespace->setNextNamespace(Namespc);
2909 StdNamespace->setLocation(IdentLoc);
2910 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2911 }
2912
2913 // Make our StdNamespace cache point at the first real definition of the
2914 // "std" namespace.
2915 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002916 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002917
2918 PushOnScopeChains(Namespc, DeclRegionScope);
2919 } else {
John McCall9aeed322009-10-01 00:25:31 +00002920 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002921 assert(Namespc->isAnonymousNamespace());
2922 CurContext->addDecl(Namespc);
2923
2924 // Link the anonymous namespace into its parent.
2925 NamespaceDecl *PrevDecl;
2926 DeclContext *Parent = CurContext->getLookupContext();
2927 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2928 PrevDecl = TU->getAnonymousNamespace();
2929 TU->setAnonymousNamespace(Namespc);
2930 } else {
2931 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2932 PrevDecl = ND->getAnonymousNamespace();
2933 ND->setAnonymousNamespace(Namespc);
2934 }
2935
2936 // Link the anonymous namespace with its previous declaration.
2937 if (PrevDecl) {
2938 assert(PrevDecl->isAnonymousNamespace());
2939 assert(!PrevDecl->getNextNamespace());
2940 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2941 PrevDecl->setNextNamespace(Namespc);
2942 }
John McCall9aeed322009-10-01 00:25:31 +00002943
2944 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2945 // behaves as if it were replaced by
2946 // namespace unique { /* empty body */ }
2947 // using namespace unique;
2948 // namespace unique { namespace-body }
2949 // where all occurrences of 'unique' in a translation unit are
2950 // replaced by the same identifier and this identifier differs
2951 // from all other identifiers in the entire program.
2952
2953 // We just create the namespace with an empty name and then add an
2954 // implicit using declaration, just like the standard suggests.
2955 //
2956 // CodeGen enforces the "universally unique" aspect by giving all
2957 // declarations semantically contained within an anonymous
2958 // namespace internal linkage.
2959
John McCall5fdd7642009-12-16 02:06:49 +00002960 if (!PrevDecl) {
2961 UsingDirectiveDecl* UD
2962 = UsingDirectiveDecl::Create(Context, CurContext,
2963 /* 'using' */ LBrace,
2964 /* 'namespace' */ SourceLocation(),
2965 /* qualifier */ SourceRange(),
2966 /* NNS */ NULL,
2967 /* identifier */ SourceLocation(),
2968 Namespc,
2969 /* Ancestor */ CurContext);
2970 UD->setImplicit();
2971 CurContext->addDecl(UD);
2972 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002973 }
2974
2975 // Although we could have an invalid decl (i.e. the namespace name is a
2976 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002977 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2978 // for the namespace has the declarations that showed up in that particular
2979 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002980 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002981 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002982}
2983
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002984/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2985/// is a namespace alias, returns the namespace it points to.
2986static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2987 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2988 return AD->getNamespace();
2989 return dyn_cast_or_null<NamespaceDecl>(D);
2990}
2991
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002992/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2993/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002994void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2995 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002996 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2997 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2998 Namespc->setRBracLoc(RBrace);
2999 PopDeclContext();
3000}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003001
Chris Lattnerb28317a2009-03-28 19:18:32 +00003002Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3003 SourceLocation UsingLoc,
3004 SourceLocation NamespcLoc,
3005 const CXXScopeSpec &SS,
3006 SourceLocation IdentLoc,
3007 IdentifierInfo *NamespcName,
3008 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003009 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3010 assert(NamespcName && "Invalid NamespcName.");
3011 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003012 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003013
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003014 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003015
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003016 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003017 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3018 LookupParsedName(R, S, &SS);
3019 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003020 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003021
John McCallf36e02d2009-10-09 21:13:30 +00003022 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003023 NamedDecl *Named = R.getFoundDecl();
3024 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3025 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003026 // C++ [namespace.udir]p1:
3027 // A using-directive specifies that the names in the nominated
3028 // namespace can be used in the scope in which the
3029 // using-directive appears after the using-directive. During
3030 // unqualified name lookup (3.4.1), the names appear as if they
3031 // were declared in the nearest enclosing namespace which
3032 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003033 // namespace. [Note: in this context, "contains" means "contains
3034 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003035
3036 // Find enclosing context containing both using-directive and
3037 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003038 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003039 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3040 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3041 CommonAncestor = CommonAncestor->getParent();
3042
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003043 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003044 SS.getRange(),
3045 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003046 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003047 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003048 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003049 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003050 }
3051
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003052 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003053 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003054 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003055}
3056
3057void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3058 // If scope has associated entity, then using directive is at namespace
3059 // or translation unit scope. We add UsingDirectiveDecls, into
3060 // it's lookup structure.
3061 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003062 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003063 else
3064 // Otherwise it is block-sope. using-directives will affect lookup
3065 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003066 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003067}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003068
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003069
3070Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003071 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003072 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003073 SourceLocation UsingLoc,
3074 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003075 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003076 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003077 bool IsTypeName,
3078 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003079 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Douglas Gregor12c118a2009-11-04 16:30:06 +00003081 switch (Name.getKind()) {
3082 case UnqualifiedId::IK_Identifier:
3083 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003084 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003085 case UnqualifiedId::IK_ConversionFunctionId:
3086 break;
3087
3088 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003089 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003090 // C++0x inherited constructors.
3091 if (getLangOptions().CPlusPlus0x) break;
3092
Douglas Gregor12c118a2009-11-04 16:30:06 +00003093 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3094 << SS.getRange();
3095 return DeclPtrTy();
3096
3097 case UnqualifiedId::IK_DestructorName:
3098 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3099 << SS.getRange();
3100 return DeclPtrTy();
3101
3102 case UnqualifiedId::IK_TemplateId:
3103 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3104 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3105 return DeclPtrTy();
3106 }
3107
3108 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003109 if (!TargetName)
3110 return DeclPtrTy();
3111
John McCall60fa3cf2009-12-11 02:10:03 +00003112 // Warn about using declarations.
3113 // TODO: store that the declaration was written without 'using' and
3114 // talk about access decls instead of using decls in the
3115 // diagnostics.
3116 if (!HasUsingKeyword) {
3117 UsingLoc = Name.getSourceRange().getBegin();
3118
3119 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3120 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3121 "using ");
3122 }
3123
John McCall9488ea12009-11-17 05:59:44 +00003124 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003125 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003126 TargetName, AttrList,
3127 /* IsInstantiation */ false,
3128 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003129 if (UD)
3130 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Anders Carlssonc72160b2009-08-28 05:40:36 +00003132 return DeclPtrTy::make(UD);
3133}
3134
John McCall9f54ad42009-12-10 09:41:52 +00003135/// Determines whether to create a using shadow decl for a particular
3136/// decl, given the set of decls existing prior to this using lookup.
3137bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3138 const LookupResult &Previous) {
3139 // Diagnose finding a decl which is not from a base class of the
3140 // current class. We do this now because there are cases where this
3141 // function will silently decide not to build a shadow decl, which
3142 // will pre-empt further diagnostics.
3143 //
3144 // We don't need to do this in C++0x because we do the check once on
3145 // the qualifier.
3146 //
3147 // FIXME: diagnose the following if we care enough:
3148 // struct A { int foo; };
3149 // struct B : A { using A::foo; };
3150 // template <class T> struct C : A {};
3151 // template <class T> struct D : C<T> { using B::foo; } // <---
3152 // This is invalid (during instantiation) in C++03 because B::foo
3153 // resolves to the using decl in B, which is not a base class of D<T>.
3154 // We can't diagnose it immediately because C<T> is an unknown
3155 // specialization. The UsingShadowDecl in D<T> then points directly
3156 // to A::foo, which will look well-formed when we instantiate.
3157 // The right solution is to not collapse the shadow-decl chain.
3158 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3159 DeclContext *OrigDC = Orig->getDeclContext();
3160
3161 // Handle enums and anonymous structs.
3162 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3163 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3164 while (OrigRec->isAnonymousStructOrUnion())
3165 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3166
3167 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3168 if (OrigDC == CurContext) {
3169 Diag(Using->getLocation(),
3170 diag::err_using_decl_nested_name_specifier_is_current_class)
3171 << Using->getNestedNameRange();
3172 Diag(Orig->getLocation(), diag::note_using_decl_target);
3173 return true;
3174 }
3175
3176 Diag(Using->getNestedNameRange().getBegin(),
3177 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3178 << Using->getTargetNestedNameDecl()
3179 << cast<CXXRecordDecl>(CurContext)
3180 << Using->getNestedNameRange();
3181 Diag(Orig->getLocation(), diag::note_using_decl_target);
3182 return true;
3183 }
3184 }
3185
3186 if (Previous.empty()) return false;
3187
3188 NamedDecl *Target = Orig;
3189 if (isa<UsingShadowDecl>(Target))
3190 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3191
John McCalld7533ec2009-12-11 02:33:26 +00003192 // If the target happens to be one of the previous declarations, we
3193 // don't have a conflict.
3194 //
3195 // FIXME: but we might be increasing its access, in which case we
3196 // should redeclare it.
3197 NamedDecl *NonTag = 0, *Tag = 0;
3198 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3199 I != E; ++I) {
3200 NamedDecl *D = (*I)->getUnderlyingDecl();
3201 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3202 return false;
3203
3204 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3205 }
3206
John McCall9f54ad42009-12-10 09:41:52 +00003207 if (Target->isFunctionOrFunctionTemplate()) {
3208 FunctionDecl *FD;
3209 if (isa<FunctionTemplateDecl>(Target))
3210 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3211 else
3212 FD = cast<FunctionDecl>(Target);
3213
3214 NamedDecl *OldDecl = 0;
3215 switch (CheckOverload(FD, Previous, OldDecl)) {
3216 case Ovl_Overload:
3217 return false;
3218
3219 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003220 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003221 break;
3222
3223 // We found a decl with the exact signature.
3224 case Ovl_Match:
3225 if (isa<UsingShadowDecl>(OldDecl)) {
3226 // Silently ignore the possible conflict.
3227 return false;
3228 }
3229
3230 // If we're in a record, we want to hide the target, so we
3231 // return true (without a diagnostic) to tell the caller not to
3232 // build a shadow decl.
3233 if (CurContext->isRecord())
3234 return true;
3235
3236 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003237 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003238 break;
3239 }
3240
3241 Diag(Target->getLocation(), diag::note_using_decl_target);
3242 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3243 return true;
3244 }
3245
3246 // Target is not a function.
3247
John McCall9f54ad42009-12-10 09:41:52 +00003248 if (isa<TagDecl>(Target)) {
3249 // No conflict between a tag and a non-tag.
3250 if (!Tag) return false;
3251
John McCall41ce66f2009-12-10 19:51:03 +00003252 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003253 Diag(Target->getLocation(), diag::note_using_decl_target);
3254 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3255 return true;
3256 }
3257
3258 // No conflict between a tag and a non-tag.
3259 if (!NonTag) return false;
3260
John McCall41ce66f2009-12-10 19:51:03 +00003261 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003262 Diag(Target->getLocation(), diag::note_using_decl_target);
3263 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3264 return true;
3265}
3266
John McCall9488ea12009-11-17 05:59:44 +00003267/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003268UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003269 UsingDecl *UD,
3270 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003271
3272 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003273 NamedDecl *Target = Orig;
3274 if (isa<UsingShadowDecl>(Target)) {
3275 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3276 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003277 }
3278
3279 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003280 = UsingShadowDecl::Create(Context, CurContext,
3281 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003282 UD->addShadowDecl(Shadow);
3283
3284 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003285 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003286 else
John McCall604e7f12009-12-08 07:46:18 +00003287 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003288 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003289
John McCall604e7f12009-12-08 07:46:18 +00003290 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3291 Shadow->setInvalidDecl();
3292
John McCall9f54ad42009-12-10 09:41:52 +00003293 return Shadow;
3294}
John McCall604e7f12009-12-08 07:46:18 +00003295
John McCall9f54ad42009-12-10 09:41:52 +00003296/// Hides a using shadow declaration. This is required by the current
3297/// using-decl implementation when a resolvable using declaration in a
3298/// class is followed by a declaration which would hide or override
3299/// one or more of the using decl's targets; for example:
3300///
3301/// struct Base { void foo(int); };
3302/// struct Derived : Base {
3303/// using Base::foo;
3304/// void foo(int);
3305/// };
3306///
3307/// The governing language is C++03 [namespace.udecl]p12:
3308///
3309/// When a using-declaration brings names from a base class into a
3310/// derived class scope, member functions in the derived class
3311/// override and/or hide member functions with the same name and
3312/// parameter types in a base class (rather than conflicting).
3313///
3314/// There are two ways to implement this:
3315/// (1) optimistically create shadow decls when they're not hidden
3316/// by existing declarations, or
3317/// (2) don't create any shadow decls (or at least don't make them
3318/// visible) until we've fully parsed/instantiated the class.
3319/// The problem with (1) is that we might have to retroactively remove
3320/// a shadow decl, which requires several O(n) operations because the
3321/// decl structures are (very reasonably) not designed for removal.
3322/// (2) avoids this but is very fiddly and phase-dependent.
3323void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3324 // Remove it from the DeclContext...
3325 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003326
John McCall9f54ad42009-12-10 09:41:52 +00003327 // ...and the scope, if applicable...
3328 if (S) {
3329 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3330 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003331 }
3332
John McCall9f54ad42009-12-10 09:41:52 +00003333 // ...and the using decl.
3334 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3335
3336 // TODO: complain somehow if Shadow was used. It shouldn't
3337 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003338}
3339
John McCall7ba107a2009-11-18 02:36:19 +00003340/// Builds a using declaration.
3341///
3342/// \param IsInstantiation - Whether this call arises from an
3343/// instantiation of an unresolved using declaration. We treat
3344/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003345NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3346 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003347 const CXXScopeSpec &SS,
3348 SourceLocation IdentLoc,
3349 DeclarationName Name,
3350 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003351 bool IsInstantiation,
3352 bool IsTypeName,
3353 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003354 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3355 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003356
Anders Carlsson550b14b2009-08-28 05:49:21 +00003357 // FIXME: We ignore attributes for now.
3358 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003360 if (SS.isEmpty()) {
3361 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003362 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
John McCall9f54ad42009-12-10 09:41:52 +00003365 // Do the redeclaration lookup in the current scope.
3366 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3367 ForRedeclaration);
3368 Previous.setHideTags(false);
3369 if (S) {
3370 LookupName(Previous, S);
3371
3372 // It is really dumb that we have to do this.
3373 LookupResult::Filter F = Previous.makeFilter();
3374 while (F.hasNext()) {
3375 NamedDecl *D = F.next();
3376 if (!isDeclInScope(D, CurContext, S))
3377 F.erase();
3378 }
3379 F.done();
3380 } else {
3381 assert(IsInstantiation && "no scope in non-instantiation");
3382 assert(CurContext->isRecord() && "scope not record in instantiation");
3383 LookupQualifiedName(Previous, CurContext);
3384 }
3385
Mike Stump1eb44332009-09-09 15:08:12 +00003386 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003387 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3388
John McCall9f54ad42009-12-10 09:41:52 +00003389 // Check for invalid redeclarations.
3390 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3391 return 0;
3392
3393 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003394 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3395 return 0;
3396
John McCallaf8e6ed2009-11-12 03:15:40 +00003397 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003398 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003399 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003400 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003401 // FIXME: not all declaration name kinds are legal here
3402 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3403 UsingLoc, TypenameLoc,
3404 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003405 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003406 } else {
3407 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3408 UsingLoc, SS.getRange(), NNS,
3409 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003410 }
John McCalled976492009-12-04 22:46:56 +00003411 } else {
3412 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3413 SS.getRange(), UsingLoc, NNS, Name,
3414 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003415 }
John McCalled976492009-12-04 22:46:56 +00003416 D->setAccess(AS);
3417 CurContext->addDecl(D);
3418
3419 if (!LookupContext) return D;
3420 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003421
John McCall604e7f12009-12-08 07:46:18 +00003422 if (RequireCompleteDeclContext(SS)) {
3423 UD->setInvalidDecl();
3424 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003425 }
3426
John McCall604e7f12009-12-08 07:46:18 +00003427 // Look up the target name.
3428
John McCalla24dc2e2009-11-17 02:14:36 +00003429 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003430
John McCall604e7f12009-12-08 07:46:18 +00003431 // Unlike most lookups, we don't always want to hide tag
3432 // declarations: tag names are visible through the using declaration
3433 // even if hidden by ordinary names, *except* in a dependent context
3434 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003435 if (!IsInstantiation)
3436 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003437
John McCalla24dc2e2009-11-17 02:14:36 +00003438 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003439
John McCallf36e02d2009-10-09 21:13:30 +00003440 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003441 Diag(IdentLoc, diag::err_no_member)
3442 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003443 UD->setInvalidDecl();
3444 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003445 }
3446
John McCalled976492009-12-04 22:46:56 +00003447 if (R.isAmbiguous()) {
3448 UD->setInvalidDecl();
3449 return UD;
3450 }
Mike Stump1eb44332009-09-09 15:08:12 +00003451
John McCall7ba107a2009-11-18 02:36:19 +00003452 if (IsTypeName) {
3453 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003454 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003455 Diag(IdentLoc, diag::err_using_typename_non_type);
3456 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3457 Diag((*I)->getUnderlyingDecl()->getLocation(),
3458 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003459 UD->setInvalidDecl();
3460 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003461 }
3462 } else {
3463 // If we asked for a non-typename and we got a type, error out,
3464 // but only if this is an instantiation of an unresolved using
3465 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003466 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003467 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3468 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003469 UD->setInvalidDecl();
3470 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003471 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003472 }
3473
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003474 // C++0x N2914 [namespace.udecl]p6:
3475 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003476 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003477 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3478 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003479 UD->setInvalidDecl();
3480 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003481 }
Mike Stump1eb44332009-09-09 15:08:12 +00003482
John McCall9f54ad42009-12-10 09:41:52 +00003483 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3484 if (!CheckUsingShadowDecl(UD, *I, Previous))
3485 BuildUsingShadowDecl(S, UD, *I);
3486 }
John McCall9488ea12009-11-17 05:59:44 +00003487
3488 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003489}
3490
John McCall9f54ad42009-12-10 09:41:52 +00003491/// Checks that the given using declaration is not an invalid
3492/// redeclaration. Note that this is checking only for the using decl
3493/// itself, not for any ill-formedness among the UsingShadowDecls.
3494bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3495 bool isTypeName,
3496 const CXXScopeSpec &SS,
3497 SourceLocation NameLoc,
3498 const LookupResult &Prev) {
3499 // C++03 [namespace.udecl]p8:
3500 // C++0x [namespace.udecl]p10:
3501 // A using-declaration is a declaration and can therefore be used
3502 // repeatedly where (and only where) multiple declarations are
3503 // allowed.
3504 // That's only in file contexts.
3505 if (CurContext->getLookupContext()->isFileContext())
3506 return false;
3507
3508 NestedNameSpecifier *Qual
3509 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3510
3511 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3512 NamedDecl *D = *I;
3513
3514 bool DTypename;
3515 NestedNameSpecifier *DQual;
3516 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3517 DTypename = UD->isTypeName();
3518 DQual = UD->getTargetNestedNameDecl();
3519 } else if (UnresolvedUsingValueDecl *UD
3520 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3521 DTypename = false;
3522 DQual = UD->getTargetNestedNameSpecifier();
3523 } else if (UnresolvedUsingTypenameDecl *UD
3524 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3525 DTypename = true;
3526 DQual = UD->getTargetNestedNameSpecifier();
3527 } else continue;
3528
3529 // using decls differ if one says 'typename' and the other doesn't.
3530 // FIXME: non-dependent using decls?
3531 if (isTypeName != DTypename) continue;
3532
3533 // using decls differ if they name different scopes (but note that
3534 // template instantiation can cause this check to trigger when it
3535 // didn't before instantiation).
3536 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3537 Context.getCanonicalNestedNameSpecifier(DQual))
3538 continue;
3539
3540 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003541 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003542 return true;
3543 }
3544
3545 return false;
3546}
3547
John McCall604e7f12009-12-08 07:46:18 +00003548
John McCalled976492009-12-04 22:46:56 +00003549/// Checks that the given nested-name qualifier used in a using decl
3550/// in the current context is appropriately related to the current
3551/// scope. If an error is found, diagnoses it and returns true.
3552bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3553 const CXXScopeSpec &SS,
3554 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003555 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003556
John McCall604e7f12009-12-08 07:46:18 +00003557 if (!CurContext->isRecord()) {
3558 // C++03 [namespace.udecl]p3:
3559 // C++0x [namespace.udecl]p8:
3560 // A using-declaration for a class member shall be a member-declaration.
3561
3562 // If we weren't able to compute a valid scope, it must be a
3563 // dependent class scope.
3564 if (!NamedContext || NamedContext->isRecord()) {
3565 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3566 << SS.getRange();
3567 return true;
3568 }
3569
3570 // Otherwise, everything is known to be fine.
3571 return false;
3572 }
3573
3574 // The current scope is a record.
3575
3576 // If the named context is dependent, we can't decide much.
3577 if (!NamedContext) {
3578 // FIXME: in C++0x, we can diagnose if we can prove that the
3579 // nested-name-specifier does not refer to a base class, which is
3580 // still possible in some cases.
3581
3582 // Otherwise we have to conservatively report that things might be
3583 // okay.
3584 return false;
3585 }
3586
3587 if (!NamedContext->isRecord()) {
3588 // Ideally this would point at the last name in the specifier,
3589 // but we don't have that level of source info.
3590 Diag(SS.getRange().getBegin(),
3591 diag::err_using_decl_nested_name_specifier_is_not_class)
3592 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3593 return true;
3594 }
3595
3596 if (getLangOptions().CPlusPlus0x) {
3597 // C++0x [namespace.udecl]p3:
3598 // In a using-declaration used as a member-declaration, the
3599 // nested-name-specifier shall name a base class of the class
3600 // being defined.
3601
3602 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3603 cast<CXXRecordDecl>(NamedContext))) {
3604 if (CurContext == NamedContext) {
3605 Diag(NameLoc,
3606 diag::err_using_decl_nested_name_specifier_is_current_class)
3607 << SS.getRange();
3608 return true;
3609 }
3610
3611 Diag(SS.getRange().getBegin(),
3612 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3613 << (NestedNameSpecifier*) SS.getScopeRep()
3614 << cast<CXXRecordDecl>(CurContext)
3615 << SS.getRange();
3616 return true;
3617 }
3618
3619 return false;
3620 }
3621
3622 // C++03 [namespace.udecl]p4:
3623 // A using-declaration used as a member-declaration shall refer
3624 // to a member of a base class of the class being defined [etc.].
3625
3626 // Salient point: SS doesn't have to name a base class as long as
3627 // lookup only finds members from base classes. Therefore we can
3628 // diagnose here only if we can prove that that can't happen,
3629 // i.e. if the class hierarchies provably don't intersect.
3630
3631 // TODO: it would be nice if "definitely valid" results were cached
3632 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3633 // need to be repeated.
3634
3635 struct UserData {
3636 llvm::DenseSet<const CXXRecordDecl*> Bases;
3637
3638 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3639 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3640 Data->Bases.insert(Base);
3641 return true;
3642 }
3643
3644 bool hasDependentBases(const CXXRecordDecl *Class) {
3645 return !Class->forallBases(collect, this);
3646 }
3647
3648 /// Returns true if the base is dependent or is one of the
3649 /// accumulated base classes.
3650 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3651 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3652 return !Data->Bases.count(Base);
3653 }
3654
3655 bool mightShareBases(const CXXRecordDecl *Class) {
3656 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3657 }
3658 };
3659
3660 UserData Data;
3661
3662 // Returns false if we find a dependent base.
3663 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3664 return false;
3665
3666 // Returns false if the class has a dependent base or if it or one
3667 // of its bases is present in the base set of the current context.
3668 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3669 return false;
3670
3671 Diag(SS.getRange().getBegin(),
3672 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3673 << (NestedNameSpecifier*) SS.getScopeRep()
3674 << cast<CXXRecordDecl>(CurContext)
3675 << SS.getRange();
3676
3677 return true;
John McCalled976492009-12-04 22:46:56 +00003678}
3679
Mike Stump1eb44332009-09-09 15:08:12 +00003680Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003681 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003682 SourceLocation AliasLoc,
3683 IdentifierInfo *Alias,
3684 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003685 SourceLocation IdentLoc,
3686 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Anders Carlsson81c85c42009-03-28 23:53:49 +00003688 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003689 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3690 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003691
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003692 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003693 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003694 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003695 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003696 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003697 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003698 if (!R.isAmbiguous() && !R.empty() &&
3699 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003700 return DeclPtrTy();
3701 }
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003703 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3704 diag::err_redefinition_different_kind;
3705 Diag(AliasLoc, DiagID) << Alias;
3706 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003707 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003708 }
3709
John McCalla24dc2e2009-11-17 02:14:36 +00003710 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003711 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003712
John McCallf36e02d2009-10-09 21:13:30 +00003713 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003714 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003715 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003716 }
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003718 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003719 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3720 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003721 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003722 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003723
John McCall3dbd3d52010-02-16 06:53:13 +00003724 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003725 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003726}
3727
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003728void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3729 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003730 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3731 !Constructor->isUsed()) &&
3732 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Eli Friedman80c30da2009-11-09 19:20:36 +00003734 CXXRecordDecl *ClassDecl
3735 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3736 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003737
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003738 DeclContext *PreviousContext = CurContext;
3739 CurContext = Constructor;
3740 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003741 Diag(CurrentLocation, diag::note_member_synthesized_at)
3742 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003743 Constructor->setInvalidDecl();
3744 } else {
3745 Constructor->setUsed();
3746 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003747 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003748}
3749
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003750void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003751 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003752 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3753 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003754 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003755 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003756
3757 DeclContext *PreviousContext = CurContext;
3758 CurContext = Destructor;
3759
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003760 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003762 // implicitly defined, all the implicitly-declared default destructors
3763 // for its base class and its non-static data members shall have been
3764 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3766 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003767 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003768 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003769 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003770 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003771 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3772 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3773 else
Mike Stump1eb44332009-09-09 15:08:12 +00003774 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003775 "DefineImplicitDestructor - missing dtor in a base class");
3776 }
3777 }
Mike Stump1eb44332009-09-09 15:08:12 +00003778
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003779 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3780 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003781 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3782 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3783 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003784 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003785 CXXRecordDecl *FieldClassDecl
3786 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3787 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003788 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003789 const_cast<CXXDestructorDecl*>(
3790 FieldClassDecl->getDestructor(Context)))
3791 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3792 else
Mike Stump1eb44332009-09-09 15:08:12 +00003793 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003794 "DefineImplicitDestructor - missing dtor in class of a data member");
3795 }
3796 }
3797 }
Anders Carlsson37909802009-11-30 21:24:50 +00003798
3799 // FIXME: If CheckDestructor fails, we should emit a note about where the
3800 // implicit destructor was needed.
3801 if (CheckDestructor(Destructor)) {
3802 Diag(CurrentLocation, diag::note_member_synthesized_at)
3803 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3804
3805 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003806 CurContext = PreviousContext;
3807
Anders Carlsson37909802009-11-30 21:24:50 +00003808 return;
3809 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003810 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003811
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003812 Destructor->setUsed();
3813}
3814
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003815void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3816 CXXMethodDecl *MethodDecl) {
3817 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3818 MethodDecl->getOverloadedOperator() == OO_Equal &&
3819 !MethodDecl->isUsed()) &&
3820 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003822 CXXRecordDecl *ClassDecl
3823 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003825 DeclContext *PreviousContext = CurContext;
3826 CurContext = MethodDecl;
3827
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003828 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003829 // Before the implicitly-declared copy assignment operator for a class is
3830 // implicitly defined, all implicitly-declared copy assignment operators
3831 // for its direct base classes and its nonstatic data members shall have
3832 // been implicitly defined.
3833 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003834 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3835 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003836 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003837 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003838 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003839 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3840 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003841 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3842 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003843 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3844 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003845 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3846 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3847 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003848 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003849 CXXRecordDecl *FieldClassDecl
3850 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003851 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003852 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3853 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003854 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003855 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003856 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003857 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3858 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003859 Diag(CurrentLocation, diag::note_first_required_here);
3860 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003861 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003862 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003863 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3864 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003865 Diag(CurrentLocation, diag::note_first_required_here);
3866 err = true;
3867 }
3868 }
3869 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003870 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003871
3872 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003873}
3874
3875CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003876Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3877 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003878 CXXRecordDecl *ClassDecl) {
3879 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3880 QualType RHSType(LHSType);
3881 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003882 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003883 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003884 RHSType = Context.getCVRQualifiedType(RHSType,
3885 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003886 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003887 LHSType,
3888 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003889 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003890 RHSType,
3891 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003892 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003893 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003894 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003895 CandidateSet);
3896 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003897 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003898 return cast<CXXMethodDecl>(Best->Function);
3899 assert(false &&
3900 "getAssignOperatorMethod - copy assignment operator method not found");
3901 return 0;
3902}
3903
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003904void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3905 CXXConstructorDecl *CopyConstructor,
3906 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003907 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003908 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003909 !CopyConstructor->isUsed()) &&
3910 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003912 CXXRecordDecl *ClassDecl
3913 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3914 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003915
3916 DeclContext *PreviousContext = CurContext;
3917 CurContext = CopyConstructor;
3918
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003919 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003920 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003921 // implicitly defined, all the implicitly-declared copy constructors
3922 // for its base class and its non-static data members shall have been
3923 // implicitly defined.
3924 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3925 Base != ClassDecl->bases_end(); ++Base) {
3926 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003927 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003928 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003929 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003930 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003931 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003932 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3933 FieldEnd = ClassDecl->field_end();
3934 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003935 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3936 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3937 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003938 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003939 CXXRecordDecl *FieldClassDecl
3940 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003941 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003942 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003943 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003944 }
3945 }
3946 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003947
3948 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003949}
3950
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003951Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003952Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003953 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003954 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003955 bool RequiresZeroInit,
3956 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003957 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003958
Douglas Gregor39da0b82009-09-09 23:08:42 +00003959 // C++ [class.copy]p15:
3960 // Whenever a temporary class object is copied using a copy constructor, and
3961 // this object and the copy have the same cv-unqualified type, an
3962 // implementation is permitted to treat the original and the copy as two
3963 // different ways of referring to the same object and not perform a copy at
3964 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003966 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003967 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003968 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003969 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3970 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3971 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003972 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3973 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003974 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3975 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003976 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3977 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3978 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003979
3980 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3981 Elidable = !CE->getCallReturnType()->isReferenceType();
3982 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003983 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003984 else if (isa<CXXConstructExpr>(E))
3985 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003986 }
Mike Stump1eb44332009-09-09 15:08:12 +00003987
3988 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003989 Elidable, move(ExprArgs), RequiresZeroInit,
3990 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003991}
3992
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003993/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3994/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003995Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003996Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3997 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003998 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003999 bool RequiresZeroInit,
4000 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004001 unsigned NumExprs = ExprArgs.size();
4002 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Douglas Gregor7edfb692009-11-23 12:27:39 +00004004 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004005 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004006 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004007 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004008}
4009
Mike Stump1eb44332009-09-09 15:08:12 +00004010bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004011 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004012 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004013 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004014 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004015 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004016 if (TempResult.isInvalid())
4017 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004019 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004020 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004021 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004022 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Anders Carlssonfe2de492009-08-25 05:18:00 +00004024 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004025}
4026
John McCall68c6c9a2010-02-02 09:10:11 +00004027void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4028 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004029 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4030 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004031 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4032 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004033 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004034 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004035}
4036
Mike Stump1eb44332009-09-09 15:08:12 +00004037/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004038/// ActOnDeclarator, when a C++ direct initializer is present.
4039/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004040void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4041 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004042 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004043 SourceLocation *CommaLocs,
4044 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004045 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004046 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004047
4048 // If there is no declaration, there was an error parsing it. Just ignore
4049 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004050 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004051 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004053 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4054 if (!VDecl) {
4055 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4056 RealDecl->setInvalidDecl();
4057 return;
4058 }
4059
Douglas Gregor83ddad32009-08-26 21:14:46 +00004060 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004061 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004062 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4063 //
4064 // Clients that want to distinguish between the two forms, can check for
4065 // direct initializer using VarDecl::hasCXXDirectInitializer().
4066 // A major benefit is that clients that don't particularly care about which
4067 // exactly form was it (like the CodeGen) can handle both cases without
4068 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004069
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004070 // C++ 8.5p11:
4071 // The form of initialization (using parentheses or '=') is generally
4072 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004073 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004074 QualType DeclInitType = VDecl->getType();
4075 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004076 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004077
Douglas Gregor4dffad62010-02-11 22:55:30 +00004078 if (!VDecl->getType()->isDependentType() &&
4079 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004080 diag::err_typecheck_decl_incomplete_type)) {
4081 VDecl->setInvalidDecl();
4082 return;
4083 }
4084
Douglas Gregor90f93822009-12-22 22:17:25 +00004085 // The variable can not have an abstract class type.
4086 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4087 diag::err_abstract_type_in_decl,
4088 AbstractVariableType))
4089 VDecl->setInvalidDecl();
4090
Sebastian Redl31310a22010-02-01 20:16:42 +00004091 const VarDecl *Def;
4092 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004093 Diag(VDecl->getLocation(), diag::err_redefinition)
4094 << VDecl->getDeclName();
4095 Diag(Def->getLocation(), diag::note_previous_definition);
4096 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004097 return;
4098 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004099
4100 // If either the declaration has a dependent type or if any of the
4101 // expressions is type-dependent, we represent the initialization
4102 // via a ParenListExpr for later use during template instantiation.
4103 if (VDecl->getType()->isDependentType() ||
4104 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4105 // Let clients know that initialization was done with a direct initializer.
4106 VDecl->setCXXDirectInitializer(true);
4107
4108 // Store the initialization expressions as a ParenListExpr.
4109 unsigned NumExprs = Exprs.size();
4110 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4111 (Expr **)Exprs.release(),
4112 NumExprs, RParenLoc));
4113 return;
4114 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004115
4116 // Capture the variable that is being initialized and the style of
4117 // initialization.
4118 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4119
4120 // FIXME: Poor source location information.
4121 InitializationKind Kind
4122 = InitializationKind::CreateDirect(VDecl->getLocation(),
4123 LParenLoc, RParenLoc);
4124
4125 InitializationSequence InitSeq(*this, Entity, Kind,
4126 (Expr**)Exprs.get(), Exprs.size());
4127 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4128 if (Result.isInvalid()) {
4129 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004130 return;
4131 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004132
4133 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004134 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004135 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004136
John McCall68c6c9a2010-02-02 09:10:11 +00004137 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4138 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004139}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004140
Douglas Gregor19aeac62009-11-14 03:27:21 +00004141/// \brief Add the applicable constructor candidates for an initialization
4142/// by constructor.
4143static void AddConstructorInitializationCandidates(Sema &SemaRef,
4144 QualType ClassType,
4145 Expr **Args,
4146 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004147 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004148 OverloadCandidateSet &CandidateSet) {
4149 // C++ [dcl.init]p14:
4150 // If the initialization is direct-initialization, or if it is
4151 // copy-initialization where the cv-unqualified version of the
4152 // source type is the same class as, or a derived class of, the
4153 // class of the destination, constructors are considered. The
4154 // applicable constructors are enumerated (13.3.1.3), and the
4155 // best one is chosen through overload resolution (13.3). The
4156 // constructor so selected is called to initialize the object,
4157 // with the initializer expression(s) as its argument(s). If no
4158 // constructor applies, or the overload resolution is ambiguous,
4159 // the initialization is ill-formed.
4160 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4161 assert(ClassRec && "Can only initialize a class type here");
4162
4163 // FIXME: When we decide not to synthesize the implicitly-declared
4164 // constructors, we'll need to make them appear here.
4165
4166 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4167 DeclarationName ConstructorName
4168 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4169 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4170 DeclContext::lookup_const_iterator Con, ConEnd;
4171 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4172 Con != ConEnd; ++Con) {
4173 // Find the constructor (which may be a template).
4174 CXXConstructorDecl *Constructor = 0;
4175 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4176 if (ConstructorTmpl)
4177 Constructor
4178 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4179 else
4180 Constructor = cast<CXXConstructorDecl>(*Con);
4181
Douglas Gregor20093b42009-12-09 23:02:17 +00004182 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4183 (Kind.getKind() == InitializationKind::IK_Value) ||
4184 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004185 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004186 ((Kind.getKind() == InitializationKind::IK_Default) &&
4187 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004188 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004189 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004190 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004191 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004192 Args, NumArgs, CandidateSet);
4193 else
John McCall86820f52010-01-26 01:37:31 +00004194 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4195 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004196 }
4197 }
4198}
4199
4200/// \brief Attempt to perform initialization by constructor
4201/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4202/// copy-initialization.
4203///
4204/// This routine determines whether initialization by constructor is possible,
4205/// but it does not emit any diagnostics in the case where the initialization
4206/// is ill-formed.
4207///
4208/// \param ClassType the type of the object being initialized, which must have
4209/// class type.
4210///
4211/// \param Args the arguments provided to initialize the object
4212///
4213/// \param NumArgs the number of arguments provided to initialize the object
4214///
4215/// \param Kind the type of initialization being performed
4216///
4217/// \returns the constructor used to initialize the object, if successful.
4218/// Otherwise, emits a diagnostic and returns NULL.
4219CXXConstructorDecl *
4220Sema::TryInitializationByConstructor(QualType ClassType,
4221 Expr **Args, unsigned NumArgs,
4222 SourceLocation Loc,
4223 InitializationKind Kind) {
4224 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004225 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004226 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4227 CandidateSet);
4228
4229 // Determine whether we found a constructor we can use.
4230 OverloadCandidateSet::iterator Best;
4231 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4232 case OR_Success:
4233 case OR_Deleted:
4234 // We found a constructor. Return it.
4235 return cast<CXXConstructorDecl>(Best->Function);
4236
4237 case OR_No_Viable_Function:
4238 case OR_Ambiguous:
4239 // Overload resolution failed. Return nothing.
4240 return 0;
4241 }
4242
4243 // Silence GCC warning
4244 return 0;
4245}
4246
Douglas Gregor39da0b82009-09-09 23:08:42 +00004247/// \brief Given a constructor and the set of arguments provided for the
4248/// constructor, convert the arguments and add any required default arguments
4249/// to form a proper call to this constructor.
4250///
4251/// \returns true if an error occurred, false otherwise.
4252bool
4253Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4254 MultiExprArg ArgsPtr,
4255 SourceLocation Loc,
4256 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4257 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4258 unsigned NumArgs = ArgsPtr.size();
4259 Expr **Args = (Expr **)ArgsPtr.get();
4260
4261 const FunctionProtoType *Proto
4262 = Constructor->getType()->getAs<FunctionProtoType>();
4263 assert(Proto && "Constructor without a prototype?");
4264 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004265
4266 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004267 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004268 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004269 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004270 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004271
4272 VariadicCallType CallType =
4273 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4274 llvm::SmallVector<Expr *, 8> AllArgs;
4275 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4276 Proto, 0, Args, NumArgs, AllArgs,
4277 CallType);
4278 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4279 ConvertedArgs.push_back(AllArgs[i]);
4280 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004281}
4282
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004283/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4284/// determine whether they are reference-related,
4285/// reference-compatible, reference-compatible with added
4286/// qualification, or incompatible, for use in C++ initialization by
4287/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4288/// type, and the first type (T1) is the pointee type of the reference
4289/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004290Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004291Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004292 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004293 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004294 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004295 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004296 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004297
Douglas Gregor393896f2009-11-05 13:06:35 +00004298 QualType T1 = Context.getCanonicalType(OrigT1);
4299 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004300 Qualifiers T1Quals, T2Quals;
4301 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4302 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004303
4304 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004305 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004306 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004307 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004308 if (UnqualT1 == UnqualT2)
4309 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004310 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4311 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4312 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004313 DerivedToBase = true;
4314 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004315 return Ref_Incompatible;
4316
4317 // At this point, we know that T1 and T2 are reference-related (at
4318 // least).
4319
Chandler Carruth28e318c2009-12-29 07:16:59 +00004320 // If the type is an array type, promote the element qualifiers to the type
4321 // for comparison.
4322 if (isa<ArrayType>(T1) && T1Quals)
4323 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4324 if (isa<ArrayType>(T2) && T2Quals)
4325 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4326
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004327 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004328 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004329 // reference-related to T2 and cv1 is the same cv-qualification
4330 // as, or greater cv-qualification than, cv2. For purposes of
4331 // overload resolution, cases for which cv1 is greater
4332 // cv-qualification than cv2 are identified as
4333 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004334 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004335 return Ref_Compatible;
4336 else if (T1.isMoreQualifiedThan(T2))
4337 return Ref_Compatible_With_Added_Qualification;
4338 else
4339 return Ref_Related;
4340}
4341
4342/// CheckReferenceInit - Check the initialization of a reference
4343/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4344/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004345/// list), and DeclType is the type of the declaration. When ICS is
4346/// non-null, this routine will compute the implicit conversion
4347/// sequence according to C++ [over.ics.ref] and will not produce any
4348/// diagnostics; when ICS is null, it will emit diagnostics when any
4349/// errors are found. Either way, a return value of true indicates
4350/// that there was a failure, a return value of false indicates that
4351/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004352///
4353/// When @p SuppressUserConversions, user-defined conversions are
4354/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004355/// When @p AllowExplicit, we also permit explicit user-defined
4356/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004357/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004358/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4359/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004360bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004361Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004362 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004363 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004364 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004365 ImplicitConversionSequence *ICS,
4366 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004367 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4368
Ted Kremenek6217b802009-07-29 21:53:49 +00004369 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004370 QualType T2 = Init->getType();
4371
Douglas Gregor904eed32008-11-10 20:40:00 +00004372 // If the initializer is the address of an overloaded function, try
4373 // to resolve the overloaded function. If all goes well, T2 is the
4374 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004375 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004376 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004377 ICS != 0);
4378 if (Fn) {
4379 // Since we're performing this reference-initialization for
4380 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004381 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004382 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004384
Anders Carlsson96ad5332009-10-21 17:16:23 +00004385 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004386 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004387
4388 T2 = Fn->getType();
4389 }
4390 }
4391
Douglas Gregor15da57e2008-10-29 02:00:59 +00004392 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004393 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004394 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004395 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4396 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004397 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004398 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004399
4400 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004401 if (ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00004402 ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
John McCalladbb8f82010-01-13 09:16:55 +00004403 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004404
4405 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004406 // A reference to type "cv1 T1" is initialized by an expression
4407 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004408
4409 // -- If the initializer expression
4410
Sebastian Redla9845802009-03-29 15:27:50 +00004411 // Rvalue references cannot bind to lvalues (N2812).
4412 // There is absolutely no situation where they can. In particular, note that
4413 // this is ill-formed, even if B has a user-defined conversion to A&&:
4414 // B b;
4415 // A&& r = b;
4416 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4417 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004418 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004419 << Init->getSourceRange();
4420 return true;
4421 }
4422
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004423 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004424 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4425 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004426 //
4427 // Note that the bit-field check is skipped if we are just computing
4428 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004429 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004430 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004431 BindsDirectly = true;
4432
Douglas Gregor15da57e2008-10-29 02:00:59 +00004433 if (ICS) {
4434 // C++ [over.ics.ref]p1:
4435 // When a parameter of reference type binds directly (8.5.3)
4436 // to an argument expression, the implicit conversion sequence
4437 // is the identity conversion, unless the argument expression
4438 // has a type that is a derived class of the parameter type,
4439 // in which case the implicit conversion sequence is a
4440 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004441 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004442 ICS->Standard.First = ICK_Identity;
4443 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4444 ICS->Standard.Third = ICK_Identity;
4445 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004446 ICS->Standard.setToType(0, T2);
4447 ICS->Standard.setToType(1, T1);
4448 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004449 ICS->Standard.ReferenceBinding = true;
4450 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004451 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004452 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004453
4454 // Nothing more to do: the inaccessibility/ambiguity check for
4455 // derived-to-base conversions is suppressed when we're
4456 // computing the implicit conversion sequence (C++
4457 // [over.best.ics]p2).
4458 return false;
4459 } else {
4460 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004461 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4462 if (DerivedToBase)
4463 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004464 else if(CheckExceptionSpecCompatibility(Init, T1))
4465 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004466 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004467 }
4468 }
4469
4470 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004471 // implicitly converted to an lvalue of type "cv3 T3,"
4472 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004473 // 92) (this conversion is selected by enumerating the
4474 // applicable conversion functions (13.3.1.6) and choosing
4475 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004476 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004477 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004478 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004479 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004480
John McCall5769d612010-02-08 23:07:23 +00004481 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004482 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004483 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004484 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004485 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004486 NamedDecl *D = *I;
4487 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4488 if (isa<UsingShadowDecl>(D))
4489 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4490
Mike Stump1eb44332009-09-09 15:08:12 +00004491 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004492 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004493 CXXConversionDecl *Conv;
4494 if (ConvTemplate)
4495 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4496 else
John McCall701c89e2009-12-03 04:06:58 +00004497 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004498
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004499 // If the conversion function doesn't return a reference type,
4500 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004501 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004502 (AllowExplicit || !Conv->isExplicit())) {
4503 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004504 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004505 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004506 else
John McCall86820f52010-01-26 01:37:31 +00004507 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4508 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004509 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004510 }
4511
4512 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004513 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004514 case OR_Success:
4515 // This is a direct binding.
4516 BindsDirectly = true;
4517
4518 if (ICS) {
4519 // C++ [over.ics.ref]p1:
4520 //
4521 // [...] If the parameter binds directly to the result of
4522 // applying a conversion function to the argument
4523 // expression, the implicit conversion sequence is a
4524 // user-defined conversion sequence (13.3.3.1.2), with the
4525 // second standard conversion sequence either an identity
4526 // conversion or, if the conversion function returns an
4527 // entity of a type that is a derived class of the parameter
4528 // type, a derived-to-base Conversion.
John McCall1d318332010-01-12 00:44:57 +00004529 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004530 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4531 ICS->UserDefined.After = Best->FinalConversion;
4532 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004533 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004534 assert(ICS->UserDefined.After.ReferenceBinding &&
4535 ICS->UserDefined.After.DirectBinding &&
4536 "Expected a direct reference binding!");
4537 return false;
4538 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004539 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004540 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004541 CastExpr::CK_UserDefinedConversion,
4542 cast<CXXMethodDecl>(Best->Function),
4543 Owned(Init));
4544 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004545
4546 if (CheckExceptionSpecCompatibility(Init, T1))
4547 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004548 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4549 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004550 }
4551 break;
4552
4553 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004554 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004555 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004556 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4557 Cand != CandidateSet.end(); ++Cand)
4558 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004559 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004560 break;
4561 }
4562 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4563 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004564 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004565 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004566
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004567 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004568 case OR_Deleted:
4569 // There was no suitable conversion, or we found a deleted
4570 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004571 break;
4572 }
4573 }
Mike Stump1eb44332009-09-09 15:08:12 +00004574
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004575 if (BindsDirectly) {
4576 // C++ [dcl.init.ref]p4:
4577 // [...] In all cases where the reference-related or
4578 // reference-compatible relationship of two types is used to
4579 // establish the validity of a reference binding, and T1 is a
4580 // base class of T2, a program that necessitates such a binding
4581 // is ill-formed if T1 is an inaccessible (clause 11) or
4582 // ambiguous (10.2) base class of T2.
4583 //
4584 // Note that we only check this condition when we're allowed to
4585 // complain about errors, because we should not be checking for
4586 // ambiguity (or inaccessibility) unless the reference binding
4587 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004588 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004589 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004590 Init->getSourceRange(),
4591 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004592 else
4593 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004594 }
4595
4596 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004597 // type (i.e., cv1 shall be const), or the reference shall be an
4598 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004599 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004600 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004601 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004602 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004603 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004604 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004605 return true;
4606 }
4607
4608 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004609 // class type, and "cv1 T1" is reference-compatible with
4610 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004611 // following ways (the choice is implementation-defined):
4612 //
4613 // -- The reference is bound to the object represented by
4614 // the rvalue (see 3.10) or to a sub-object within that
4615 // object.
4616 //
Eli Friedman33a31382009-08-05 19:21:58 +00004617 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004618 // a constructor is called to copy the entire rvalue
4619 // object into the temporary. The reference is bound to
4620 // the temporary or to a sub-object within the
4621 // temporary.
4622 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004623 // The constructor that would be used to make the copy
4624 // shall be callable whether or not the copy is actually
4625 // done.
4626 //
Sebastian Redla9845802009-03-29 15:27:50 +00004627 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004628 // freedom, so we will always take the first option and never build
4629 // a temporary in this case. FIXME: We will, however, have to check
4630 // for the presence of a copy constructor in C++98/03 mode.
4631 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004632 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4633 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004634 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004635 ICS->Standard.First = ICK_Identity;
4636 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4637 ICS->Standard.Third = ICK_Identity;
4638 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004639 ICS->Standard.setToType(0, T2);
4640 ICS->Standard.setToType(1, T1);
4641 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004642 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004643 ICS->Standard.DirectBinding = false;
4644 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004645 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004646 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004647 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4648 if (DerivedToBase)
4649 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004650 else if(CheckExceptionSpecCompatibility(Init, T1))
4651 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004652 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004653 }
4654 return false;
4655 }
4656
Eli Friedman33a31382009-08-05 19:21:58 +00004657 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004658 // initialized from the initializer expression using the
4659 // rules for a non-reference copy initialization (8.5). The
4660 // reference is then bound to the temporary. If T1 is
4661 // reference-related to T2, cv1 must be the same
4662 // cv-qualification as, or greater cv-qualification than,
4663 // cv2; otherwise, the program is ill-formed.
4664 if (RefRelationship == Ref_Related) {
4665 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4666 // we would be reference-compatible or reference-compatible with
4667 // added qualification. But that wasn't the case, so the reference
4668 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004669 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004670 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004671 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004672 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004673 return true;
4674 }
4675
Douglas Gregor734d9862009-01-30 23:27:23 +00004676 // If at least one of the types is a class type, the types are not
4677 // related, and we aren't allowed any user conversions, the
4678 // reference binding fails. This case is important for breaking
4679 // recursion, since TryImplicitConversion below will attempt to
4680 // create a temporary through the use of a copy constructor.
4681 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4682 (T1->isRecordType() || T2->isRecordType())) {
4683 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004684 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004685 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004686 return true;
4687 }
4688
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004689 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004690 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004691 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004692 //
Sebastian Redla9845802009-03-29 15:27:50 +00004693 // When a parameter of reference type is not bound directly to
4694 // an argument expression, the conversion sequence is the one
4695 // required to convert the argument expression to the
4696 // underlying type of the reference according to
4697 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4698 // to copy-initializing a temporary of the underlying type with
4699 // the argument expression. Any difference in top-level
4700 // cv-qualification is subsumed by the initialization itself
4701 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004702 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4703 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004704 /*ForceRValue=*/false,
4705 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Sebastian Redla9845802009-03-29 15:27:50 +00004707 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004708 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004709 ICS->Standard.ReferenceBinding = true;
4710 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004711 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004712 ICS->UserDefined.After.ReferenceBinding = true;
4713 ICS->UserDefined.After.RRefBinding = isRValRef;
4714 }
John McCall1d318332010-01-12 00:44:57 +00004715 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004716 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004717 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004718 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004719 false, false,
4720 Conversions);
4721 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004722 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004723 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004724 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004725 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004726 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004727 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004728 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004729 }
4730 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004731 else {
4732 if (isRValRef)
4733 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4734 << Init->getSourceRange();
4735 else
4736 Diag(DeclLoc, diag::err_invalid_initialization)
4737 << DeclType << Init->getType() << Init->getSourceRange();
4738 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004739 }
4740 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004741 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004742}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004743
Anders Carlsson20d45d22009-12-12 00:32:00 +00004744static inline bool
4745CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4746 const FunctionDecl *FnDecl) {
4747 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4748 if (isa<NamespaceDecl>(DC)) {
4749 return SemaRef.Diag(FnDecl->getLocation(),
4750 diag::err_operator_new_delete_declared_in_namespace)
4751 << FnDecl->getDeclName();
4752 }
4753
4754 if (isa<TranslationUnitDecl>(DC) &&
4755 FnDecl->getStorageClass() == FunctionDecl::Static) {
4756 return SemaRef.Diag(FnDecl->getLocation(),
4757 diag::err_operator_new_delete_declared_static)
4758 << FnDecl->getDeclName();
4759 }
4760
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004761 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004762}
4763
Anders Carlsson156c78e2009-12-13 17:53:43 +00004764static inline bool
4765CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4766 CanQualType ExpectedResultType,
4767 CanQualType ExpectedFirstParamType,
4768 unsigned DependentParamTypeDiag,
4769 unsigned InvalidParamTypeDiag) {
4770 QualType ResultType =
4771 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4772
4773 // Check that the result type is not dependent.
4774 if (ResultType->isDependentType())
4775 return SemaRef.Diag(FnDecl->getLocation(),
4776 diag::err_operator_new_delete_dependent_result_type)
4777 << FnDecl->getDeclName() << ExpectedResultType;
4778
4779 // Check that the result type is what we expect.
4780 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4781 return SemaRef.Diag(FnDecl->getLocation(),
4782 diag::err_operator_new_delete_invalid_result_type)
4783 << FnDecl->getDeclName() << ExpectedResultType;
4784
4785 // A function template must have at least 2 parameters.
4786 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4787 return SemaRef.Diag(FnDecl->getLocation(),
4788 diag::err_operator_new_delete_template_too_few_parameters)
4789 << FnDecl->getDeclName();
4790
4791 // The function decl must have at least 1 parameter.
4792 if (FnDecl->getNumParams() == 0)
4793 return SemaRef.Diag(FnDecl->getLocation(),
4794 diag::err_operator_new_delete_too_few_parameters)
4795 << FnDecl->getDeclName();
4796
4797 // Check the the first parameter type is not dependent.
4798 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4799 if (FirstParamType->isDependentType())
4800 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4801 << FnDecl->getDeclName() << ExpectedFirstParamType;
4802
4803 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004804 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004805 ExpectedFirstParamType)
4806 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4807 << FnDecl->getDeclName() << ExpectedFirstParamType;
4808
4809 return false;
4810}
4811
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004812static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004813CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004814 // C++ [basic.stc.dynamic.allocation]p1:
4815 // A program is ill-formed if an allocation function is declared in a
4816 // namespace scope other than global scope or declared static in global
4817 // scope.
4818 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4819 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004820
4821 CanQualType SizeTy =
4822 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4823
4824 // C++ [basic.stc.dynamic.allocation]p1:
4825 // The return type shall be void*. The first parameter shall have type
4826 // std::size_t.
4827 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4828 SizeTy,
4829 diag::err_operator_new_dependent_param_type,
4830 diag::err_operator_new_param_type))
4831 return true;
4832
4833 // C++ [basic.stc.dynamic.allocation]p1:
4834 // The first parameter shall not have an associated default argument.
4835 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004836 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004837 diag::err_operator_new_default_arg)
4838 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4839
4840 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004841}
4842
4843static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004844CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4845 // C++ [basic.stc.dynamic.deallocation]p1:
4846 // A program is ill-formed if deallocation functions are declared in a
4847 // namespace scope other than global scope or declared static in global
4848 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004849 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4850 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004851
4852 // C++ [basic.stc.dynamic.deallocation]p2:
4853 // Each deallocation function shall return void and its first parameter
4854 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004855 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4856 SemaRef.Context.VoidPtrTy,
4857 diag::err_operator_delete_dependent_param_type,
4858 diag::err_operator_delete_param_type))
4859 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004860
Anders Carlsson46991d62009-12-12 00:16:02 +00004861 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4862 if (FirstParamType->isDependentType())
4863 return SemaRef.Diag(FnDecl->getLocation(),
4864 diag::err_operator_delete_dependent_param_type)
4865 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4866
4867 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4868 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004869 return SemaRef.Diag(FnDecl->getLocation(),
4870 diag::err_operator_delete_param_type)
4871 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004872
4873 return false;
4874}
4875
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004876/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4877/// of this overloaded operator is well-formed. If so, returns false;
4878/// otherwise, emits appropriate diagnostics and returns true.
4879bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004880 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004881 "Expected an overloaded operator declaration");
4882
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004883 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4884
Mike Stump1eb44332009-09-09 15:08:12 +00004885 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004886 // The allocation and deallocation functions, operator new,
4887 // operator new[], operator delete and operator delete[], are
4888 // described completely in 3.7.3. The attributes and restrictions
4889 // found in the rest of this subclause do not apply to them unless
4890 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004891 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004892 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004893
Anders Carlssona3ccda52009-12-12 00:26:23 +00004894 if (Op == OO_New || Op == OO_Array_New)
4895 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004896
4897 // C++ [over.oper]p6:
4898 // An operator function shall either be a non-static member
4899 // function or be a non-member function and have at least one
4900 // parameter whose type is a class, a reference to a class, an
4901 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004902 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4903 if (MethodDecl->isStatic())
4904 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004905 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004906 } else {
4907 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004908 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4909 ParamEnd = FnDecl->param_end();
4910 Param != ParamEnd; ++Param) {
4911 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004912 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4913 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004914 ClassOrEnumParam = true;
4915 break;
4916 }
4917 }
4918
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004919 if (!ClassOrEnumParam)
4920 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004921 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004922 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004923 }
4924
4925 // C++ [over.oper]p8:
4926 // An operator function cannot have default arguments (8.3.6),
4927 // except where explicitly stated below.
4928 //
Mike Stump1eb44332009-09-09 15:08:12 +00004929 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004930 // (C++ [over.call]p1).
4931 if (Op != OO_Call) {
4932 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4933 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004934 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004935 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004936 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004937 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004938 }
4939 }
4940
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004941 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4942 { false, false, false }
4943#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4944 , { Unary, Binary, MemberOnly }
4945#include "clang/Basic/OperatorKinds.def"
4946 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004947
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004948 bool CanBeUnaryOperator = OperatorUses[Op][0];
4949 bool CanBeBinaryOperator = OperatorUses[Op][1];
4950 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004951
4952 // C++ [over.oper]p8:
4953 // [...] Operator functions cannot have more or fewer parameters
4954 // than the number required for the corresponding operator, as
4955 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004956 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004957 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004958 if (Op != OO_Call &&
4959 ((NumParams == 1 && !CanBeUnaryOperator) ||
4960 (NumParams == 2 && !CanBeBinaryOperator) ||
4961 (NumParams < 1) || (NumParams > 2))) {
4962 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004963 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004964 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004965 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004966 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004967 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004968 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004969 assert(CanBeBinaryOperator &&
4970 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004971 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004972 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004973
Chris Lattner416e46f2008-11-21 07:57:12 +00004974 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004975 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004976 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004977
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004978 // Overloaded operators other than operator() cannot be variadic.
4979 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004980 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004981 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004982 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004983 }
4984
4985 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004986 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4987 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004988 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004989 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004990 }
4991
4992 // C++ [over.inc]p1:
4993 // The user-defined function called operator++ implements the
4994 // prefix and postfix ++ operator. If this function is a member
4995 // function with no parameters, or a non-member function with one
4996 // parameter of class or enumeration type, it defines the prefix
4997 // increment operator ++ for objects of that type. If the function
4998 // is a member function with one parameter (which shall be of type
4999 // int) or a non-member function with two parameters (the second
5000 // of which shall be of type int), it defines the postfix
5001 // increment operator ++ for objects of that type.
5002 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5003 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5004 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005005 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005006 ParamIsInt = BT->getKind() == BuiltinType::Int;
5007
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005008 if (!ParamIsInt)
5009 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005010 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005011 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005012 }
5013
Sebastian Redl64b45f72009-01-05 20:52:13 +00005014 // Notify the class if it got an assignment operator.
5015 if (Op == OO_Equal) {
5016 // Would have returned earlier otherwise.
5017 assert(isa<CXXMethodDecl>(FnDecl) &&
5018 "Overloaded = not member, but not filtered.");
5019 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5020 Method->getParent()->addedAssignmentOperator(Context, Method);
5021 }
5022
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005023 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005024}
Chris Lattner5a003a42008-12-17 07:09:26 +00005025
Sean Hunta6c058d2010-01-13 09:01:02 +00005026/// CheckLiteralOperatorDeclaration - Check whether the declaration
5027/// of this literal operator function is well-formed. If so, returns
5028/// false; otherwise, emits appropriate diagnostics and returns true.
5029bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5030 DeclContext *DC = FnDecl->getDeclContext();
5031 Decl::Kind Kind = DC->getDeclKind();
5032 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5033 Kind != Decl::LinkageSpec) {
5034 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5035 << FnDecl->getDeclName();
5036 return true;
5037 }
5038
5039 bool Valid = false;
5040
5041 // FIXME: Check for the one valid template signature
5042 // template <char...> type operator "" name();
5043
5044 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5045 // Check the first parameter
5046 QualType T = (*Param)->getType();
5047
5048 // unsigned long long int and long double are allowed, but only
5049 // alone.
5050 // We also allow any character type; their omission seems to be a bug
5051 // in n3000
5052 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5053 Context.hasSameType(T, Context.LongDoubleTy) ||
5054 Context.hasSameType(T, Context.CharTy) ||
5055 Context.hasSameType(T, Context.WCharTy) ||
5056 Context.hasSameType(T, Context.Char16Ty) ||
5057 Context.hasSameType(T, Context.Char32Ty)) {
5058 if (++Param == FnDecl->param_end())
5059 Valid = true;
5060 goto FinishedParams;
5061 }
5062
5063 // Otherwise it must be a pointer to const; let's strip those.
5064 const PointerType *PT = T->getAs<PointerType>();
5065 if (!PT)
5066 goto FinishedParams;
5067 T = PT->getPointeeType();
5068 if (!T.isConstQualified())
5069 goto FinishedParams;
5070 T = T.getUnqualifiedType();
5071
5072 // Move on to the second parameter;
5073 ++Param;
5074
5075 // If there is no second parameter, the first must be a const char *
5076 if (Param == FnDecl->param_end()) {
5077 if (Context.hasSameType(T, Context.CharTy))
5078 Valid = true;
5079 goto FinishedParams;
5080 }
5081
5082 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5083 // are allowed as the first parameter to a two-parameter function
5084 if (!(Context.hasSameType(T, Context.CharTy) ||
5085 Context.hasSameType(T, Context.WCharTy) ||
5086 Context.hasSameType(T, Context.Char16Ty) ||
5087 Context.hasSameType(T, Context.Char32Ty)))
5088 goto FinishedParams;
5089
5090 // The second and final parameter must be an std::size_t
5091 T = (*Param)->getType().getUnqualifiedType();
5092 if (Context.hasSameType(T, Context.getSizeType()) &&
5093 ++Param == FnDecl->param_end())
5094 Valid = true;
5095 }
5096
5097 // FIXME: This diagnostic is absolutely terrible.
5098FinishedParams:
5099 if (!Valid) {
5100 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5101 << FnDecl->getDeclName();
5102 return true;
5103 }
5104
5105 return false;
5106}
5107
Douglas Gregor074149e2009-01-05 19:45:36 +00005108/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5109/// linkage specification, including the language and (if present)
5110/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5111/// the location of the language string literal, which is provided
5112/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5113/// the '{' brace. Otherwise, this linkage specification does not
5114/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005115Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5116 SourceLocation ExternLoc,
5117 SourceLocation LangLoc,
5118 const char *Lang,
5119 unsigned StrSize,
5120 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005121 LinkageSpecDecl::LanguageIDs Language;
5122 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5123 Language = LinkageSpecDecl::lang_c;
5124 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5125 Language = LinkageSpecDecl::lang_cxx;
5126 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005127 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005128 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005129 }
Mike Stump1eb44332009-09-09 15:08:12 +00005130
Chris Lattnercc98eac2008-12-17 07:13:27 +00005131 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005132
Douglas Gregor074149e2009-01-05 19:45:36 +00005133 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005134 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005135 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005136 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005137 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005138 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005139}
5140
Douglas Gregor074149e2009-01-05 19:45:36 +00005141/// ActOnFinishLinkageSpecification - Completely the definition of
5142/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5143/// valid, it's the position of the closing '}' brace in a linkage
5144/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005145Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5146 DeclPtrTy LinkageSpec,
5147 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005148 if (LinkageSpec)
5149 PopDeclContext();
5150 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005151}
5152
Douglas Gregord308e622009-05-18 20:51:54 +00005153/// \brief Perform semantic analysis for the variable declaration that
5154/// occurs within a C++ catch clause, returning the newly-created
5155/// variable.
5156VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005157 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005158 IdentifierInfo *Name,
5159 SourceLocation Loc,
5160 SourceRange Range) {
5161 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005162
5163 // Arrays and functions decay.
5164 if (ExDeclType->isArrayType())
5165 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5166 else if (ExDeclType->isFunctionType())
5167 ExDeclType = Context.getPointerType(ExDeclType);
5168
5169 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5170 // The exception-declaration shall not denote a pointer or reference to an
5171 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005172 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005173 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005174 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005175 Invalid = true;
5176 }
Douglas Gregord308e622009-05-18 20:51:54 +00005177
Sebastian Redl4b07b292008-12-22 19:15:10 +00005178 QualType BaseType = ExDeclType;
5179 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005180 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005181 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005182 BaseType = Ptr->getPointeeType();
5183 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005184 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005185 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005186 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005187 BaseType = Ref->getPointeeType();
5188 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005189 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005190 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005191 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005192 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005193 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005194
Mike Stump1eb44332009-09-09 15:08:12 +00005195 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005196 RequireNonAbstractType(Loc, ExDeclType,
5197 diag::err_abstract_type_in_decl,
5198 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005199 Invalid = true;
5200
Douglas Gregord308e622009-05-18 20:51:54 +00005201 // FIXME: Need to test for ability to copy-construct and destroy the
5202 // exception variable.
5203
Sebastian Redl8351da02008-12-22 21:35:02 +00005204 // FIXME: Need to check for abstract classes.
5205
Mike Stump1eb44332009-09-09 15:08:12 +00005206 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005207 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005208
5209 if (Invalid)
5210 ExDecl->setInvalidDecl();
5211
5212 return ExDecl;
5213}
5214
5215/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5216/// handler.
5217Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005218 TypeSourceInfo *TInfo = 0;
5219 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005220
5221 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005222 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005223 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005224 // The scope should be freshly made just for us. There is just no way
5225 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005226 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005227 if (PrevDecl->isTemplateParameter()) {
5228 // Maybe we will complain about the shadowed template parameter.
5229 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005230 }
5231 }
5232
Chris Lattnereaaebc72009-04-25 08:06:05 +00005233 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005234 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5235 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005236 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005237 }
5238
John McCalla93c9342009-12-07 02:54:59 +00005239 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005240 D.getIdentifier(),
5241 D.getIdentifierLoc(),
5242 D.getDeclSpec().getSourceRange());
5243
Chris Lattnereaaebc72009-04-25 08:06:05 +00005244 if (Invalid)
5245 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005246
Sebastian Redl4b07b292008-12-22 19:15:10 +00005247 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005248 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005249 PushOnScopeChains(ExDecl, S);
5250 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005251 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005252
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005253 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005254 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005255}
Anders Carlssonfb311762009-03-14 00:25:26 +00005256
Mike Stump1eb44332009-09-09 15:08:12 +00005257Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005258 ExprArg assertexpr,
5259 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005260 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005261 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005262 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5263
Anders Carlssonc3082412009-03-14 00:33:21 +00005264 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5265 llvm::APSInt Value(32);
5266 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5267 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5268 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005269 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005270 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005271
Anders Carlssonc3082412009-03-14 00:33:21 +00005272 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005273 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005274 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005275 }
5276 }
Mike Stump1eb44332009-09-09 15:08:12 +00005277
Anders Carlsson77d81422009-03-15 17:35:16 +00005278 assertexpr.release();
5279 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005280 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005281 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005282
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005283 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005284 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005285}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005286
John McCalldd4a3b02009-09-16 22:47:08 +00005287/// Handle a friend type declaration. This works in tandem with
5288/// ActOnTag.
5289///
5290/// Notes on friend class templates:
5291///
5292/// We generally treat friend class declarations as if they were
5293/// declaring a class. So, for example, the elaborated type specifier
5294/// in a friend declaration is required to obey the restrictions of a
5295/// class-head (i.e. no typedefs in the scope chain), template
5296/// parameters are required to match up with simple template-ids, &c.
5297/// However, unlike when declaring a template specialization, it's
5298/// okay to refer to a template specialization without an empty
5299/// template parameter declaration, e.g.
5300/// friend class A<T>::B<unsigned>;
5301/// We permit this as a special case; if there are any template
5302/// parameters present at all, require proper matching, i.e.
5303/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005304Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005305 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005306 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005307
5308 assert(DS.isFriendSpecified());
5309 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5310
John McCalldd4a3b02009-09-16 22:47:08 +00005311 // Try to convert the decl specifier to a type. This works for
5312 // friend templates because ActOnTag never produces a ClassTemplateDecl
5313 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005314 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005315 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5316 if (TheDeclarator.isInvalidType())
5317 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005318
John McCalldd4a3b02009-09-16 22:47:08 +00005319 // This is definitely an error in C++98. It's probably meant to
5320 // be forbidden in C++0x, too, but the specification is just
5321 // poorly written.
5322 //
5323 // The problem is with declarations like the following:
5324 // template <T> friend A<T>::foo;
5325 // where deciding whether a class C is a friend or not now hinges
5326 // on whether there exists an instantiation of A that causes
5327 // 'foo' to equal C. There are restrictions on class-heads
5328 // (which we declare (by fiat) elaborated friend declarations to
5329 // be) that makes this tractable.
5330 //
5331 // FIXME: handle "template <> friend class A<T>;", which
5332 // is possibly well-formed? Who even knows?
5333 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5334 Diag(Loc, diag::err_tagless_friend_type_template)
5335 << DS.getSourceRange();
5336 return DeclPtrTy();
5337 }
5338
John McCall02cace72009-08-28 07:59:38 +00005339 // C++ [class.friend]p2:
5340 // An elaborated-type-specifier shall be used in a friend declaration
5341 // for a class.*
5342 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005343 // This is one of the rare places in Clang where it's legitimate to
5344 // ask about the "spelling" of the type.
5345 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5346 // If we evaluated the type to a record type, suggest putting
5347 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005348 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005349 RecordDecl *RD = RT->getDecl();
5350
5351 std::string InsertionText = std::string(" ") + RD->getKindName();
5352
John McCalle3af0232009-10-07 23:34:25 +00005353 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5354 << (unsigned) RD->getTagKind()
5355 << T
5356 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005357 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5358 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005359 return DeclPtrTy();
5360 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005361 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5362 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005363 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005364 }
5365 }
5366
John McCalle3af0232009-10-07 23:34:25 +00005367 // Enum types cannot be friends.
5368 if (T->getAs<EnumType>()) {
5369 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5370 << SourceRange(DS.getFriendSpecLoc());
5371 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005372 }
John McCall02cace72009-08-28 07:59:38 +00005373
John McCall02cace72009-08-28 07:59:38 +00005374 // C++98 [class.friend]p1: A friend of a class is a function
5375 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005376 // This is fixed in DR77, which just barely didn't make the C++03
5377 // deadline. It's also a very silly restriction that seriously
5378 // affects inner classes and which nobody else seems to implement;
5379 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005380
John McCalldd4a3b02009-09-16 22:47:08 +00005381 Decl *D;
5382 if (TempParams.size())
5383 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5384 TempParams.size(),
5385 (TemplateParameterList**) TempParams.release(),
5386 T.getTypePtr(),
5387 DS.getFriendSpecLoc());
5388 else
5389 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5390 DS.getFriendSpecLoc());
5391 D->setAccess(AS_public);
5392 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005393
John McCalldd4a3b02009-09-16 22:47:08 +00005394 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005395}
5396
John McCallbbbcdd92009-09-11 21:02:39 +00005397Sema::DeclPtrTy
5398Sema::ActOnFriendFunctionDecl(Scope *S,
5399 Declarator &D,
5400 bool IsDefinition,
5401 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005402 const DeclSpec &DS = D.getDeclSpec();
5403
5404 assert(DS.isFriendSpecified());
5405 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5406
5407 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005408 TypeSourceInfo *TInfo = 0;
5409 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005410
5411 // C++ [class.friend]p1
5412 // A friend of a class is a function or class....
5413 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005414 // It *doesn't* see through dependent types, which is correct
5415 // according to [temp.arg.type]p3:
5416 // If a declaration acquires a function type through a
5417 // type dependent on a template-parameter and this causes
5418 // a declaration that does not use the syntactic form of a
5419 // function declarator to have a function type, the program
5420 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005421 if (!T->isFunctionType()) {
5422 Diag(Loc, diag::err_unexpected_friend);
5423
5424 // It might be worthwhile to try to recover by creating an
5425 // appropriate declaration.
5426 return DeclPtrTy();
5427 }
5428
5429 // C++ [namespace.memdef]p3
5430 // - If a friend declaration in a non-local class first declares a
5431 // class or function, the friend class or function is a member
5432 // of the innermost enclosing namespace.
5433 // - The name of the friend is not found by simple name lookup
5434 // until a matching declaration is provided in that namespace
5435 // scope (either before or after the class declaration granting
5436 // friendship).
5437 // - If a friend function is called, its name may be found by the
5438 // name lookup that considers functions from namespaces and
5439 // classes associated with the types of the function arguments.
5440 // - When looking for a prior declaration of a class or a function
5441 // declared as a friend, scopes outside the innermost enclosing
5442 // namespace scope are not considered.
5443
John McCall02cace72009-08-28 07:59:38 +00005444 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5445 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005446 assert(Name);
5447
John McCall67d1a672009-08-06 02:15:43 +00005448 // The context we found the declaration in, or in which we should
5449 // create the declaration.
5450 DeclContext *DC;
5451
5452 // FIXME: handle local classes
5453
5454 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005455 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5456 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005457 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005458 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005459 DC = computeDeclContext(ScopeQual);
5460
5461 // FIXME: handle dependent contexts
5462 if (!DC) return DeclPtrTy();
5463
John McCall68263142009-11-18 22:49:29 +00005464 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005465
5466 // If searching in that context implicitly found a declaration in
5467 // a different context, treat it like it wasn't found at all.
5468 // TODO: better diagnostics for this case. Suggesting the right
5469 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005470 // FIXME: getRepresentativeDecl() is not right here at all
5471 if (Previous.empty() ||
5472 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005473 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005474 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5475 return DeclPtrTy();
5476 }
5477
5478 // C++ [class.friend]p1: A friend of a class is a function or
5479 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005480 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005481 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5482
John McCall67d1a672009-08-06 02:15:43 +00005483 // Otherwise walk out to the nearest namespace scope looking for matches.
5484 } else {
5485 // TODO: handle local class contexts.
5486
5487 DC = CurContext;
5488 while (true) {
5489 // Skip class contexts. If someone can cite chapter and verse
5490 // for this behavior, that would be nice --- it's what GCC and
5491 // EDG do, and it seems like a reasonable intent, but the spec
5492 // really only says that checks for unqualified existing
5493 // declarations should stop at the nearest enclosing namespace,
5494 // not that they should only consider the nearest enclosing
5495 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005496 while (DC->isRecord())
5497 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005498
John McCall68263142009-11-18 22:49:29 +00005499 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005500
5501 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005502 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005503 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005504
John McCall67d1a672009-08-06 02:15:43 +00005505 if (DC->isFileContext()) break;
5506 DC = DC->getParent();
5507 }
5508
5509 // C++ [class.friend]p1: A friend of a class is a function or
5510 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005511 // C++0x changes this for both friend types and functions.
5512 // Most C++ 98 compilers do seem to give an error here, so
5513 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005514 if (!Previous.empty() && DC->Equals(CurContext)
5515 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005516 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5517 }
5518
Douglas Gregor182ddf02009-09-28 00:08:27 +00005519 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005520 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005521 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5522 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5523 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005524 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005525 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5526 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005527 return DeclPtrTy();
5528 }
John McCall67d1a672009-08-06 02:15:43 +00005529 }
5530
Douglas Gregor182ddf02009-09-28 00:08:27 +00005531 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005532 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005533 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005534 IsDefinition,
5535 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005536 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005537
Douglas Gregor182ddf02009-09-28 00:08:27 +00005538 assert(ND->getDeclContext() == DC);
5539 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005540
John McCallab88d972009-08-31 22:39:49 +00005541 // Add the function declaration to the appropriate lookup tables,
5542 // adjusting the redeclarations list as necessary. We don't
5543 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005544 //
John McCallab88d972009-08-31 22:39:49 +00005545 // Also update the scope-based lookup if the target context's
5546 // lookup context is in lexical scope.
5547 if (!CurContext->isDependentContext()) {
5548 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005549 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005550 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005551 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005552 }
John McCall02cace72009-08-28 07:59:38 +00005553
5554 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005555 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005556 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005557 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005558 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005559
Douglas Gregor7557a132009-12-24 20:56:24 +00005560 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5561 FrD->setSpecialization(true);
5562
Douglas Gregor182ddf02009-09-28 00:08:27 +00005563 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005564}
5565
Chris Lattnerb28317a2009-03-28 19:18:32 +00005566void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005567 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005568
Chris Lattnerb28317a2009-03-28 19:18:32 +00005569 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005570 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5571 if (!Fn) {
5572 Diag(DelLoc, diag::err_deleted_non_function);
5573 return;
5574 }
5575 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5576 Diag(DelLoc, diag::err_deleted_decl_not_first);
5577 Diag(Prev->getLocation(), diag::note_previous_declaration);
5578 // If the declaration wasn't the first, we delete the function anyway for
5579 // recovery.
5580 }
5581 Fn->setDeleted();
5582}
Sebastian Redl13e88542009-04-27 21:33:24 +00005583
5584static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5585 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5586 ++CI) {
5587 Stmt *SubStmt = *CI;
5588 if (!SubStmt)
5589 continue;
5590 if (isa<ReturnStmt>(SubStmt))
5591 Self.Diag(SubStmt->getSourceRange().getBegin(),
5592 diag::err_return_in_constructor_handler);
5593 if (!isa<Expr>(SubStmt))
5594 SearchForReturnInStmt(Self, SubStmt);
5595 }
5596}
5597
5598void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5599 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5600 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5601 SearchForReturnInStmt(*this, Handler);
5602 }
5603}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005604
Mike Stump1eb44332009-09-09 15:08:12 +00005605bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005606 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005607 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5608 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005609
Chandler Carruth73857792010-02-15 11:53:20 +00005610 if (Context.hasSameType(NewTy, OldTy) ||
5611 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005612 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005614 // Check if the return types are covariant
5615 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005616
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005617 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005618 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5619 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005620 NewClassTy = NewPT->getPointeeType();
5621 OldClassTy = OldPT->getPointeeType();
5622 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005623 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5624 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5625 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5626 NewClassTy = NewRT->getPointeeType();
5627 OldClassTy = OldRT->getPointeeType();
5628 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005629 }
5630 }
Mike Stump1eb44332009-09-09 15:08:12 +00005631
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005632 // The return types aren't either both pointers or references to a class type.
5633 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005634 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005635 diag::err_different_return_type_for_overriding_virtual_function)
5636 << New->getDeclName() << NewTy << OldTy;
5637 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005638
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005639 return true;
5640 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005641
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005642 // C++ [class.virtual]p6:
5643 // If the return type of D::f differs from the return type of B::f, the
5644 // class type in the return type of D::f shall be complete at the point of
5645 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005646 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5647 if (!RT->isBeingDefined() &&
5648 RequireCompleteType(New->getLocation(), NewClassTy,
5649 PDiag(diag::err_covariant_return_incomplete)
5650 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005651 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005652 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005653
Douglas Gregora4923eb2009-11-16 21:35:15 +00005654 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005655 // Check if the new class derives from the old class.
5656 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5657 Diag(New->getLocation(),
5658 diag::err_covariant_return_not_derived)
5659 << New->getDeclName() << NewTy << OldTy;
5660 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5661 return true;
5662 }
Mike Stump1eb44332009-09-09 15:08:12 +00005663
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005664 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005665 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005666 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5667 // FIXME: Should this point to the return type?
5668 New->getLocation(), SourceRange(), New->getDeclName())) {
5669 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5670 return true;
5671 }
5672 }
Mike Stump1eb44332009-09-09 15:08:12 +00005673
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005674 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005675 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005676 Diag(New->getLocation(),
5677 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005678 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005679 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5680 return true;
5681 };
Mike Stump1eb44332009-09-09 15:08:12 +00005682
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005683
5684 // The new class type must have the same or less qualifiers as the old type.
5685 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5686 Diag(New->getLocation(),
5687 diag::err_covariant_return_type_class_type_more_qualified)
5688 << New->getDeclName() << NewTy << OldTy;
5689 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5690 return true;
5691 };
Mike Stump1eb44332009-09-09 15:08:12 +00005692
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005693 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005694}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005695
Sean Huntbbd37c62009-11-21 08:43:09 +00005696bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5697 const CXXMethodDecl *Old)
5698{
5699 if (Old->hasAttr<FinalAttr>()) {
5700 Diag(New->getLocation(), diag::err_final_function_overridden)
5701 << New->getDeclName();
5702 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5703 return true;
5704 }
5705
5706 return false;
5707}
5708
Douglas Gregor4ba31362009-12-01 17:24:26 +00005709/// \brief Mark the given method pure.
5710///
5711/// \param Method the method to be marked pure.
5712///
5713/// \param InitRange the source range that covers the "0" initializer.
5714bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5715 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5716 Method->setPure();
5717
5718 // A class is abstract if at least one function is pure virtual.
5719 Method->getParent()->setAbstract(true);
5720 return false;
5721 }
5722
5723 if (!Method->isInvalidDecl())
5724 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5725 << Method->getDeclName() << InitRange;
5726 return true;
5727}
5728
John McCall731ad842009-12-19 09:28:58 +00005729/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5730/// an initializer for the out-of-line declaration 'Dcl'. The scope
5731/// is a fresh scope pushed for just this purpose.
5732///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005733/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5734/// static data member of class X, names should be looked up in the scope of
5735/// class X.
5736void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005737 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005738 Decl *D = Dcl.getAs<Decl>();
5739 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005740
John McCall731ad842009-12-19 09:28:58 +00005741 // We should only get called for declarations with scope specifiers, like:
5742 // int foo::bar;
5743 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005744 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005745}
5746
5747/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005748/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005749void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005750 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005751 Decl *D = Dcl.getAs<Decl>();
5752 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005753
John McCall731ad842009-12-19 09:28:58 +00005754 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005755 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005756}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005757
5758/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5759/// C++ if/switch/while/for statement.
5760/// e.g: "if (int x = f()) {...}"
5761Action::DeclResult
5762Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5763 // C++ 6.4p2:
5764 // The declarator shall not specify a function or an array.
5765 // The type-specifier-seq shall not contain typedef and shall not declare a
5766 // new class or enumeration.
5767 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5768 "Parser allowed 'typedef' as storage class of condition decl.");
5769
John McCalla93c9342009-12-07 02:54:59 +00005770 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005771 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005772 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005773
5774 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5775 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5776 // would be created and CXXConditionDeclExpr wants a VarDecl.
5777 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5778 << D.getSourceRange();
5779 return DeclResult();
5780 } else if (OwnedTag && OwnedTag->isDefinition()) {
5781 // The type-specifier-seq shall not declare a new class or enumeration.
5782 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5783 }
5784
5785 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5786 if (!Dcl)
5787 return DeclResult();
5788
5789 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5790 VD->setDeclaredInCondition(true);
5791 return Dcl;
5792}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005793
Anders Carlssond6a637f2009-12-07 08:24:59 +00005794void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5795 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005796 // Ignore dependent types.
5797 if (MD->isDependentContext())
5798 return;
5799
5800 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005801
5802 // Ignore classes without a vtable.
5803 if (!RD->isDynamicClass())
5804 return;
5805
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005806 // Ignore declarations that are not definitions.
5807 if (!MD->isThisDeclarationADefinition())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005808 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005809
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005810 if (isa<CXXConstructorDecl>(MD)) {
5811 switch (MD->getParent()->getTemplateSpecializationKind()) {
5812 case TSK_Undeclared:
5813 case TSK_ExplicitSpecialization:
5814 // Classes that aren't instantiations of templates don't need their
5815 // virtual methods marked until we see the definition of the key
5816 // function.
5817 return;
5818
5819 case TSK_ImplicitInstantiation:
5820 case TSK_ExplicitInstantiationDeclaration:
5821 case TSK_ExplicitInstantiationDefinition:
5822 // This is a constructor of a class template; mark all of the virtual
5823 // members as referenced to ensure that they get instantiatied.
5824 break;
5825 }
5826 } else if (!MD->isOutOfLine()) {
5827 // Consider only out-of-line definitions of member functions. When we see
5828 // an inline definition, it's too early to compute the key function.
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005829 return;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005830 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5831 // If this is not the key function, we don't need to mark virtual members.
5832 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5833 return;
5834 } else {
5835 // The class has no key function, so we've already noted that we need to
5836 // mark the virtual members of this class.
5837 return;
5838 }
5839
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005840 // We will need to mark all of the virtual members as referenced to build the
5841 // vtable.
5842 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005843}
5844
5845bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5846 if (ClassesWithUnmarkedVirtualMembers.empty())
5847 return false;
5848
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005849 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5850 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5851 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5852 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005853 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005854 }
5855
Anders Carlssond6a637f2009-12-07 08:24:59 +00005856 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005857}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005858
5859void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5860 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5861 e = RD->method_end(); i != e; ++i) {
5862 CXXMethodDecl *MD = *i;
5863
5864 // C++ [basic.def.odr]p2:
5865 // [...] A virtual member function is used if it is not pure. [...]
5866 if (MD->isVirtual() && !MD->isPure())
5867 MarkDeclarationReferenced(Loc, MD);
5868 }
5869}
5870