blob: 767da87e42a22d65e7de2e9423305ea5c8f7b41f [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);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000590 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000591 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
592 Virtual, Access,
593 BaseType, BaseLoc))
594 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000597}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000598
Douglas Gregor2943aed2009-03-03 04:44:36 +0000599/// \brief Performs the actual work of attaching the given base class
600/// specifiers to a C++ class.
601bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
602 unsigned NumBases) {
603 if (NumBases == 0)
604 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000605
606 // Used to keep track of which base types we have already seen, so
607 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000608 // that the key is always the unqualified canonical type of the base
609 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
611
612 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000614 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000615 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000616 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000617 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000618 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000620 if (KnownBaseTypes[NewBaseType]) {
621 // C++ [class.mi]p3:
622 // A class shall not be specified as a direct base class of a
623 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000624 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000626 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000627 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000628
629 // Delete the duplicate base class specifier; we're going to
630 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000631 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632
633 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000634 } else {
635 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636 KnownBaseTypes[NewBaseType] = Bases[idx];
637 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 }
639 }
640
641 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000642 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the remaining (good) base class specifiers, since their
645 // data has been copied into the CXXRecordDecl.
646 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000647 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000648
649 return Invalid;
650}
651
652/// ActOnBaseSpecifiers - Attach the given base specifiers to the
653/// class, after checking whether there are any duplicate base
654/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000655void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000656 unsigned NumBases) {
657 if (!ClassDecl || !Bases || !NumBases)
658 return;
659
660 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000661 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000662 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000663}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000664
Douglas Gregora8f32e02009-10-06 17:59:45 +0000665/// \brief Determine whether the type \p Derived is a C++ class that is
666/// derived from the type \p Base.
667bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
668 if (!getLangOptions().CPlusPlus)
669 return false;
670
671 const RecordType *DerivedRT = Derived->getAs<RecordType>();
672 if (!DerivedRT)
673 return false;
674
675 const RecordType *BaseRT = Base->getAs<RecordType>();
676 if (!BaseRT)
677 return false;
678
679 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
680 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall86ff3082010-02-04 22:26:26 +0000681 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
682 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000683}
684
685/// \brief Determine whether the type \p Derived is a C++ class that is
686/// derived from the type \p Base.
687bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
688 if (!getLangOptions().CPlusPlus)
689 return false;
690
691 const RecordType *DerivedRT = Derived->getAs<RecordType>();
692 if (!DerivedRT)
693 return false;
694
695 const RecordType *BaseRT = Base->getAs<RecordType>();
696 if (!BaseRT)
697 return false;
698
699 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
700 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
701 return DerivedRD->isDerivedFrom(BaseRD, Paths);
702}
703
704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
705/// conversion (where Derived and Base are class types) is
706/// well-formed, meaning that the conversion is unambiguous (and
707/// that all of the base classes are accessible). Returns true
708/// and emits a diagnostic if the code is ill-formed, returns false
709/// otherwise. Loc is the location where this routine should point to
710/// if there is an error, and Range is the source range to highlight
711/// if there is an error.
712bool
713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall6b2accb2010-02-10 09:31:12 +0000714 AccessDiagnosticsKind ADK,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 unsigned AmbigiousBaseConvID,
716 SourceLocation Loc, SourceRange Range,
717 DeclarationName Name) {
718 // First, determine whether the path from Derived to Base is
719 // ambiguous. This is slightly more expensive than checking whether
720 // the Derived to Base conversion exists, because here we need to
721 // explore multiple paths to determine if there is an ambiguity.
722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
723 /*DetectVirtual=*/false);
724 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
725 assert(DerivationOkay &&
726 "Can only be used with a derived-to-base conversion");
727 (void)DerivationOkay;
728
729 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall6b2accb2010-02-10 09:31:12 +0000730 if (ADK == ADK_quiet)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000731 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000732
Douglas Gregora8f32e02009-10-06 17:59:45 +0000733 // Check that the base class can be accessed.
John McCall6b2accb2010-02-10 09:31:12 +0000734 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
735 Base, Derived, Paths.front(),
736 /*force*/ false,
737 /*unprivileged*/ false,
738 ADK)) {
739 case AR_accessible: return false;
740 case AR_inaccessible: return true;
741 case AR_dependent: return false;
742 case AR_delayed: return false;
743 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000744 }
745
746 // We know that the derived-to-base conversion is ambiguous, and
747 // we're going to produce a diagnostic. Perform the derived-to-base
748 // search just one more time to compute all of the possible paths so
749 // that we can print them out. This is more expensive than any of
750 // the previous derived-to-base checks we've done, but at this point
751 // performance isn't as much of an issue.
752 Paths.clear();
753 Paths.setRecordingPaths(true);
754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
755 assert(StillOkay && "Can only be used with a derived-to-base conversion");
756 (void)StillOkay;
757
758 // Build up a textual representation of the ambiguous paths, e.g.,
759 // D -> B -> A, that will be used to illustrate the ambiguous
760 // conversions in the diagnostic. We only print one of the paths
761 // to each base class subobject.
762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
763
764 Diag(Loc, AmbigiousBaseConvID)
765 << Derived << Base << PathDisplayStr << Range << Name;
766 return true;
767}
768
769bool
770Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000771 SourceLocation Loc, SourceRange Range,
772 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000773 return CheckDerivedToBaseConversion(Derived, Base,
John McCall6b2accb2010-02-10 09:31:12 +0000774 IgnoreAccess ? ADK_quiet : ADK_normal,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000775 diag::err_ambiguous_derived_to_base_conv,
776 Loc, Range, DeclarationName());
777}
778
779
780/// @brief Builds a string representing ambiguous paths from a
781/// specific derived class to different subobjects of the same base
782/// class.
783///
784/// This function builds a string that can be used in error messages
785/// to show the different paths that one can take through the
786/// inheritance hierarchy to go from the derived class to different
787/// subobjects of a base class. The result looks something like this:
788/// @code
789/// struct D -> struct B -> struct A
790/// struct D -> struct C -> struct A
791/// @endcode
792std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
793 std::string PathDisplayStr;
794 std::set<unsigned> DisplayedPaths;
795 for (CXXBasePaths::paths_iterator Path = Paths.begin();
796 Path != Paths.end(); ++Path) {
797 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
798 // We haven't displayed a path to this particular base
799 // class subobject yet.
800 PathDisplayStr += "\n ";
801 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
802 for (CXXBasePath::const_iterator Element = Path->begin();
803 Element != Path->end(); ++Element)
804 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
805 }
806 }
807
808 return PathDisplayStr;
809}
810
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811//===----------------------------------------------------------------------===//
812// C++ class member Handling
813//===----------------------------------------------------------------------===//
814
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000815/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
816/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
817/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000818/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000819Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000820Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000821 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000822 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
823 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000824 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000825 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000826 Expr *BitWidth = static_cast<Expr*>(BW);
827 Expr *Init = static_cast<Expr*>(InitExpr);
828 SourceLocation Loc = D.getIdentifierLoc();
829
Sebastian Redl669d5d72008-11-14 23:42:31 +0000830 bool isFunc = D.isFunctionDeclarator();
831
John McCall67d1a672009-08-06 02:15:43 +0000832 assert(!DS.isFriendSpecified());
833
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000834 // C++ 9.2p6: A member shall not be declared to have automatic storage
835 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000836 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
837 // data members and cannot be applied to names declared const or static,
838 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000839 switch (DS.getStorageClassSpec()) {
840 case DeclSpec::SCS_unspecified:
841 case DeclSpec::SCS_typedef:
842 case DeclSpec::SCS_static:
843 // FALL THROUGH.
844 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000845 case DeclSpec::SCS_mutable:
846 if (isFunc) {
847 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000848 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000849 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000850 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Sebastian Redla11f42f2008-11-17 23:24:37 +0000852 // FIXME: It would be nicer if the keyword was ignored only for this
853 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000854 D.getMutableDeclSpec().ClearStorageClassSpecs();
855 } else {
856 QualType T = GetTypeForDeclarator(D, S);
857 diag::kind err = static_cast<diag::kind>(0);
858 if (T->isReferenceType())
859 err = diag::err_mutable_reference;
860 else if (T.isConstQualified())
861 err = diag::err_mutable_const;
862 if (err != 0) {
863 if (DS.getStorageClassSpecLoc().isValid())
864 Diag(DS.getStorageClassSpecLoc(), err);
865 else
866 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000867 // FIXME: It would be nicer if the keyword was ignored only for this
868 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000869 D.getMutableDeclSpec().ClearStorageClassSpecs();
870 }
871 }
872 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873 default:
874 if (DS.getStorageClassSpecLoc().isValid())
875 Diag(DS.getStorageClassSpecLoc(),
876 diag::err_storageclass_invalid_for_member);
877 else
878 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
879 D.getMutableDeclSpec().ClearStorageClassSpecs();
880 }
881
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000882 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000883 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000884 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000885 // Check also for this case:
886 //
887 // typedef int f();
888 // f a;
889 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000890 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000891 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000892 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893
Sebastian Redl669d5d72008-11-14 23:42:31 +0000894 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
895 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000896 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000897
898 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000899 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000900 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000901 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
902 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000903 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000904 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000905 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000906 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000907 if (!Member) {
908 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000909 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000910 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000911
912 // Non-instance-fields can't have a bitfield.
913 if (BitWidth) {
914 if (Member->isInvalidDecl()) {
915 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000916 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000917 // C++ 9.6p3: A bit-field shall not be a static member.
918 // "static member 'A' cannot be a bit-field"
919 Diag(Loc, diag::err_static_not_bitfield)
920 << Name << BitWidth->getSourceRange();
921 } else if (isa<TypedefDecl>(Member)) {
922 // "typedef member 'x' cannot be a bit-field"
923 Diag(Loc, diag::err_typedef_not_bitfield)
924 << Name << BitWidth->getSourceRange();
925 } else {
926 // A function typedef ("typedef int f(); f a;").
927 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
928 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000929 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000930 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Chris Lattner8b963ef2009-03-05 23:01:03 +0000933 DeleteExpr(BitWidth);
934 BitWidth = 0;
935 Member->setInvalidDecl();
936 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000937
938 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor37b372b2009-08-20 22:52:58 +0000940 // If we have declared a member function template, set the access of the
941 // templated declaration as well.
942 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
943 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000944 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000945
Douglas Gregor10bd3682008-11-17 22:58:34 +0000946 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000947
Douglas Gregor021c3b32009-03-11 23:00:04 +0000948 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000949 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000950 if (Deleted) // FIXME: Source location is not very good.
951 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000952
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000953 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000954 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000955 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000956 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000957 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000958}
959
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000960/// \brief Find the direct and/or virtual base specifiers that
961/// correspond to the given base type, for use in base initialization
962/// within a constructor.
963static bool FindBaseInitializer(Sema &SemaRef,
964 CXXRecordDecl *ClassDecl,
965 QualType BaseType,
966 const CXXBaseSpecifier *&DirectBaseSpec,
967 const CXXBaseSpecifier *&VirtualBaseSpec) {
968 // First, check for a direct base class.
969 DirectBaseSpec = 0;
970 for (CXXRecordDecl::base_class_const_iterator Base
971 = ClassDecl->bases_begin();
972 Base != ClassDecl->bases_end(); ++Base) {
973 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
974 // We found a direct base of this type. That's what we're
975 // initializing.
976 DirectBaseSpec = &*Base;
977 break;
978 }
979 }
980
981 // Check for a virtual base class.
982 // FIXME: We might be able to short-circuit this if we know in advance that
983 // there are no virtual bases.
984 VirtualBaseSpec = 0;
985 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
986 // We haven't found a base yet; search the class hierarchy for a
987 // virtual base class.
988 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
989 /*DetectVirtual=*/false);
990 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
991 BaseType, Paths)) {
992 for (CXXBasePaths::paths_iterator Path = Paths.begin();
993 Path != Paths.end(); ++Path) {
994 if (Path->back().Base->isVirtual()) {
995 VirtualBaseSpec = Path->back().Base;
996 break;
997 }
998 }
999 }
1000 }
1001
1002 return DirectBaseSpec || VirtualBaseSpec;
1003}
1004
Douglas Gregor7ad83902008-11-05 04:29:56 +00001005/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001006Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001007Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001008 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001009 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001010 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001011 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001012 SourceLocation IdLoc,
1013 SourceLocation LParenLoc,
1014 ExprTy **Args, unsigned NumArgs,
1015 SourceLocation *CommaLocs,
1016 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001017 if (!ConstructorD)
1018 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001020 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001021
1022 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001023 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001024 if (!Constructor) {
1025 // The user wrote a constructor initializer on a function that is
1026 // not a C++ constructor. Ignore the error for now, because we may
1027 // have more member initializers coming; we'll diagnose it just
1028 // once in ActOnMemInitializers.
1029 return true;
1030 }
1031
1032 CXXRecordDecl *ClassDecl = Constructor->getParent();
1033
1034 // C++ [class.base.init]p2:
1035 // Names in a mem-initializer-id are looked up in the scope of the
1036 // constructor’s class and, if not found in that scope, are looked
1037 // up in the scope containing the constructor’s
1038 // definition. [Note: if the constructor’s class contains a member
1039 // with the same name as a direct or virtual base class of the
1040 // class, a mem-initializer-id naming the member or base class and
1041 // composed of a single identifier refers to the class member. A
1042 // mem-initializer-id for the hidden base class may be specified
1043 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001044 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001045 // Look for a member, first.
1046 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001047 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001048 = ClassDecl->lookup(MemberOrBase);
1049 if (Result.first != Result.second)
1050 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001051
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001052 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001053
Eli Friedman59c04372009-07-29 19:44:27 +00001054 if (Member)
1055 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001056 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001057 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001058 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001059 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001060 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001061
1062 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001063 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001064 } else {
1065 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1066 LookupParsedName(R, S, &SS);
1067
1068 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1069 if (!TyD) {
1070 if (R.isAmbiguous()) return true;
1071
Douglas Gregor7a886e12010-01-19 06:46:48 +00001072 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1073 bool NotUnknownSpecialization = false;
1074 DeclContext *DC = computeDeclContext(SS, false);
1075 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1076 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1077
1078 if (!NotUnknownSpecialization) {
1079 // When the scope specifier can refer to a member of an unknown
1080 // specialization, we take it as a type name.
1081 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1082 *MemberOrBase, SS.getRange());
1083 R.clear();
1084 }
1085 }
1086
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001087 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001088 if (R.empty() && BaseType.isNull() &&
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001089 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1090 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1091 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1092 // We have found a non-static data member with a similar
1093 // name to what was typed; complain and initialize that
1094 // member.
1095 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1096 << MemberOrBase << true << R.getLookupName()
1097 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1098 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001099 Diag(Member->getLocation(), diag::note_previous_decl)
1100 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001101
1102 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1103 LParenLoc, RParenLoc);
1104 }
1105 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1106 const CXXBaseSpecifier *DirectBaseSpec;
1107 const CXXBaseSpecifier *VirtualBaseSpec;
1108 if (FindBaseInitializer(*this, ClassDecl,
1109 Context.getTypeDeclType(Type),
1110 DirectBaseSpec, VirtualBaseSpec)) {
1111 // We have found a direct or virtual base class with a
1112 // similar name to what was typed; complain and initialize
1113 // that base class.
1114 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1115 << MemberOrBase << false << R.getLookupName()
1116 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1117 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001118
1119 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1120 : VirtualBaseSpec;
1121 Diag(BaseSpec->getSourceRange().getBegin(),
1122 diag::note_base_class_specified_here)
1123 << BaseSpec->getType()
1124 << BaseSpec->getSourceRange();
1125
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001126 TyD = Type;
1127 }
1128 }
1129 }
1130
Douglas Gregor7a886e12010-01-19 06:46:48 +00001131 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001132 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1133 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1134 return true;
1135 }
John McCall2b194412009-12-21 10:41:20 +00001136 }
1137
Douglas Gregor7a886e12010-01-19 06:46:48 +00001138 if (BaseType.isNull()) {
1139 BaseType = Context.getTypeDeclType(TyD);
1140 if (SS.isSet()) {
1141 NestedNameSpecifier *Qualifier =
1142 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001143
Douglas Gregor7a886e12010-01-19 06:46:48 +00001144 // FIXME: preserve source range information
1145 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1146 }
John McCall2b194412009-12-21 10:41:20 +00001147 }
1148 }
Mike Stump1eb44332009-09-09 15:08:12 +00001149
John McCalla93c9342009-12-07 02:54:59 +00001150 if (!TInfo)
1151 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001152
John McCalla93c9342009-12-07 02:54:59 +00001153 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001154 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001155}
1156
John McCallb4190042009-11-04 23:02:40 +00001157/// Checks an initializer expression for use of uninitialized fields, such as
1158/// containing the field that is being initialized. Returns true if there is an
1159/// uninitialized field was used an updates the SourceLocation parameter; false
1160/// otherwise.
1161static bool InitExprContainsUninitializedFields(const Stmt* S,
1162 const FieldDecl* LhsField,
1163 SourceLocation* L) {
1164 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1165 if (ME) {
1166 const NamedDecl* RhsField = ME->getMemberDecl();
1167 if (RhsField == LhsField) {
1168 // Initializing a field with itself. Throw a warning.
1169 // But wait; there are exceptions!
1170 // Exception #1: The field may not belong to this record.
1171 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1172 const Expr* base = ME->getBase();
1173 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1174 // Even though the field matches, it does not belong to this record.
1175 return false;
1176 }
1177 // None of the exceptions triggered; return true to indicate an
1178 // uninitialized field was used.
1179 *L = ME->getMemberLoc();
1180 return true;
1181 }
1182 }
1183 bool found = false;
1184 for (Stmt::const_child_iterator it = S->child_begin();
1185 it != S->child_end() && found == false;
1186 ++it) {
1187 if (isa<CallExpr>(S)) {
1188 // Do not descend into function calls or constructors, as the use
1189 // of an uninitialized field may be valid. One would have to inspect
1190 // the contents of the function/ctor to determine if it is safe or not.
1191 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1192 // may be safe, depending on what the function/ctor does.
1193 continue;
1194 }
1195 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1196 }
1197 return found;
1198}
1199
Eli Friedman59c04372009-07-29 19:44:27 +00001200Sema::MemInitResult
1201Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1202 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001203 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001204 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001205 // Diagnose value-uses of fields to initialize themselves, e.g.
1206 // foo(foo)
1207 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001208 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001209 for (unsigned i = 0; i < NumArgs; ++i) {
1210 SourceLocation L;
1211 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1212 // FIXME: Return true in the case when other fields are used before being
1213 // uninitialized. For example, let this field be the i'th field. When
1214 // initializing the i'th field, throw a warning if any of the >= i'th
1215 // fields are used, as they are not yet initialized.
1216 // Right now we are only handling the case where the i'th field uses
1217 // itself in its initializer.
1218 Diag(L, diag::warn_field_is_uninit);
1219 }
1220 }
1221
Eli Friedman59c04372009-07-29 19:44:27 +00001222 bool HasDependentArg = false;
1223 for (unsigned i = 0; i < NumArgs; i++)
1224 HasDependentArg |= Args[i]->isTypeDependent();
1225
Eli Friedman59c04372009-07-29 19:44:27 +00001226 QualType FieldType = Member->getType();
1227 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1228 FieldType = Array->getElementType();
Eli Friedmane6d11b72009-12-25 23:59:21 +00001229 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001230 if (FieldType->isDependentType() || HasDependentArg) {
1231 // Can't check initialization for a member of dependent type or when
1232 // any of the arguments are type-dependent expressions.
1233 OwningExprResult Init
1234 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1235 RParenLoc));
1236
1237 // Erase any temporaries within this evaluation context; we're not
1238 // going to track them in the AST, since we'll be rebuilding the
1239 // ASTs during template instantiation.
1240 ExprTemporaries.erase(
1241 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1242 ExprTemporaries.end());
1243
1244 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1245 LParenLoc,
1246 Init.takeAs<Expr>(),
1247 RParenLoc);
1248
Douglas Gregor7ad83902008-11-05 04:29:56 +00001249 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001250
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001251 if (Member->isInvalidDecl())
1252 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001253
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001254 // Initialize the member.
1255 InitializedEntity MemberEntity =
1256 InitializedEntity::InitializeMember(Member, 0);
1257 InitializationKind Kind =
1258 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1259
1260 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1261
1262 OwningExprResult MemberInit =
1263 InitSeq.Perform(*this, MemberEntity, Kind,
1264 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1265 if (MemberInit.isInvalid())
1266 return true;
1267
1268 // C++0x [class.base.init]p7:
1269 // The initialization of each base and member constitutes a
1270 // full-expression.
1271 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1272 if (MemberInit.isInvalid())
1273 return true;
1274
1275 // If we are in a dependent context, template instantiation will
1276 // perform this type-checking again. Just save the arguments that we
1277 // received in a ParenListExpr.
1278 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1279 // of the information that we have about the member
1280 // initializer. However, deconstructing the ASTs is a dicey process,
1281 // and this approach is far more likely to get the corner cases right.
1282 if (CurContext->isDependentContext()) {
1283 // Bump the reference count of all of the arguments.
1284 for (unsigned I = 0; I != NumArgs; ++I)
1285 Args[I]->Retain();
1286
1287 OwningExprResult Init
1288 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1289 RParenLoc));
1290 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291 LParenLoc,
1292 Init.takeAs<Expr>(),
1293 RParenLoc);
1294 }
1295
Douglas Gregor802ab452009-12-02 22:36:29 +00001296 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001297 LParenLoc,
1298 MemberInit.takeAs<Expr>(),
1299 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001300}
1301
1302Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001303Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001304 Expr **Args, unsigned NumArgs,
1305 SourceLocation LParenLoc, SourceLocation RParenLoc,
1306 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001307 bool HasDependentArg = false;
1308 for (unsigned i = 0; i < NumArgs; i++)
1309 HasDependentArg |= Args[i]->isTypeDependent();
1310
John McCalla93c9342009-12-07 02:54:59 +00001311 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 if (BaseType->isDependentType() || HasDependentArg) {
1313 // Can't check initialization for a base of dependent type or when
1314 // any of the arguments are type-dependent expressions.
1315 OwningExprResult BaseInit
1316 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1317 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001318
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001319 // Erase any temporaries within this evaluation context; we're not
1320 // going to track them in the AST, since we'll be rebuilding the
1321 // ASTs during template instantiation.
1322 ExprTemporaries.erase(
1323 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1324 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001326 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1327 LParenLoc,
1328 BaseInit.takeAs<Expr>(),
1329 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001330 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001331
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001332 if (!BaseType->isRecordType())
1333 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1334 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1335
1336 // C++ [class.base.init]p2:
1337 // [...] Unless the mem-initializer-id names a nonstatic data
1338 // member of the constructor’s class or a direct or virtual base
1339 // of that class, the mem-initializer is ill-formed. A
1340 // mem-initializer-list can initialize a base class using any
1341 // name that denotes that base class type.
1342
1343 // Check for direct and virtual base classes.
1344 const CXXBaseSpecifier *DirectBaseSpec = 0;
1345 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1346 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1347 VirtualBaseSpec);
1348
1349 // C++ [base.class.init]p2:
1350 // If a mem-initializer-id is ambiguous because it designates both
1351 // a direct non-virtual base class and an inherited virtual base
1352 // class, the mem-initializer is ill-formed.
1353 if (DirectBaseSpec && VirtualBaseSpec)
1354 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1355 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1356 // C++ [base.class.init]p2:
1357 // Unless the mem-initializer-id names a nonstatic data membeer of the
1358 // constructor's class ot a direst or virtual base of that class, the
1359 // mem-initializer is ill-formed.
1360 if (!DirectBaseSpec && !VirtualBaseSpec)
1361 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1362 << BaseType << ClassDecl->getNameAsCString()
1363 << BaseTInfo->getTypeLoc().getSourceRange();
1364
1365 CXXBaseSpecifier *BaseSpec
1366 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1367 if (!BaseSpec)
1368 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1369
1370 // Initialize the base.
1371 InitializedEntity BaseEntity =
1372 InitializedEntity::InitializeBase(Context, BaseSpec);
1373 InitializationKind Kind =
1374 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1375
1376 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1377
1378 OwningExprResult BaseInit =
1379 InitSeq.Perform(*this, BaseEntity, Kind,
1380 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1381 if (BaseInit.isInvalid())
1382 return true;
1383
1384 // C++0x [class.base.init]p7:
1385 // The initialization of each base and member constitutes a
1386 // full-expression.
1387 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1388 if (BaseInit.isInvalid())
1389 return true;
1390
1391 // If we are in a dependent context, template instantiation will
1392 // perform this type-checking again. Just save the arguments that we
1393 // received in a ParenListExpr.
1394 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1395 // of the information that we have about the base
1396 // initializer. However, deconstructing the ASTs is a dicey process,
1397 // and this approach is far more likely to get the corner cases right.
1398 if (CurContext->isDependentContext()) {
1399 // Bump the reference count of all of the arguments.
1400 for (unsigned I = 0; I != NumArgs; ++I)
1401 Args[I]->Retain();
1402
1403 OwningExprResult Init
1404 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1405 RParenLoc));
1406 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1407 LParenLoc,
1408 Init.takeAs<Expr>(),
1409 RParenLoc);
1410 }
1411
1412 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1413 LParenLoc,
1414 BaseInit.takeAs<Expr>(),
1415 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001416}
1417
Eli Friedman80c30da2009-11-09 19:20:36 +00001418bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001419Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001420 CXXBaseOrMemberInitializer **Initializers,
1421 unsigned NumInitializers,
1422 bool IsImplicitConstructor,
1423 bool AnyErrors) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001424 // We need to build the initializer AST according to order of construction
1425 // and not what user specified in the Initializers list.
1426 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1427 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1428 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1429 bool HasDependentBaseInit = false;
Eli Friedman80c30da2009-11-09 19:20:36 +00001430 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001432 for (unsigned i = 0; i < NumInitializers; i++) {
1433 CXXBaseOrMemberInitializer *Member = Initializers[i];
1434 if (Member->isBaseInitializer()) {
1435 if (Member->getBaseClass()->isDependentType())
1436 HasDependentBaseInit = true;
1437 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1438 } else {
1439 AllBaseFields[Member->getMember()] = Member;
1440 }
1441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001443 if (HasDependentBaseInit) {
1444 // FIXME. This does not preserve the ordering of the initializers.
1445 // Try (with -Wreorder)
1446 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // template<class X> struct B : A<X> {
1448 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001449 // int x1;
1450 // };
1451 // B<int> x;
1452 // On seeing one dependent type, we should essentially exit this routine
1453 // while preserving user-declared initializer list. When this routine is
1454 // called during instantiatiation process, this routine will rebuild the
John McCall6aee6212009-11-04 23:13:52 +00001455 // ordered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001457 // If we have a dependent base initialization, we can't determine the
1458 // association between initializers and bases; just dump the known
1459 // initializers into the list, and don't try to deal with other bases.
1460 for (unsigned i = 0; i < NumInitializers; i++) {
1461 CXXBaseOrMemberInitializer *Member = Initializers[i];
1462 if (Member->isBaseInitializer())
1463 AllToInit.push_back(Member);
1464 }
1465 } else {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001466 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1467
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001468 // Push virtual bases before others.
1469 for (CXXRecordDecl::base_class_iterator VBase =
1470 ClassDecl->vbases_begin(),
1471 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1472 if (VBase->getType()->isDependentType())
1473 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001474 if (CXXBaseOrMemberInitializer *Value
1475 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001476 AllToInit.push_back(Value);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 } else if (!AnyErrors) {
1478 InitializedEntity InitEntity
1479 = InitializedEntity::InitializeBase(Context, VBase);
1480 InitializationKind InitKind
1481 = InitializationKind::CreateDefault(Constructor->getLocation());
1482 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1483 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1484 MultiExprArg(*this, 0, 0));
1485 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1486 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001487 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001488 continue;
1489 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001490
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001491 // Don't attach synthesized base initializers in a dependent
1492 // context; they'll be checked again at template instantiation
1493 // time.
1494 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001495 continue;
1496
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001497 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001498 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001499 Context.getTrivialTypeSourceInfo(VBase->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001500 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001501 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001502 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001503 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001504 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001505 }
1506 }
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001508 for (CXXRecordDecl::base_class_iterator Base =
1509 ClassDecl->bases_begin(),
1510 E = ClassDecl->bases_end(); Base != E; ++Base) {
1511 // Virtuals are in the virtual base list and already constructed.
1512 if (Base->isVirtual())
1513 continue;
1514 // Skip dependent types.
1515 if (Base->getType()->isDependentType())
1516 continue;
Douglas Gregorc07a4942009-11-15 08:51:10 +00001517 if (CXXBaseOrMemberInitializer *Value
1518 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001519 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001520 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001521 else if (!AnyErrors) {
1522 InitializedEntity InitEntity
1523 = InitializedEntity::InitializeBase(Context, Base);
1524 InitializationKind InitKind
1525 = InitializationKind::CreateDefault(Constructor->getLocation());
1526 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1527 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1528 MultiExprArg(*this, 0, 0));
1529 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1530 if (BaseInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001531 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001532 continue;
1533 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001534
1535 // Don't attach synthesized base initializers in a dependent
1536 // context; they'll be regenerated at template instantiation
1537 // time.
1538 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001539 continue;
1540
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001541 CXXBaseOrMemberInitializer *CXXBaseInit =
Douglas Gregor802ab452009-12-02 22:36:29 +00001542 new (Context) CXXBaseOrMemberInitializer(Context,
John McCalla93c9342009-12-07 02:54:59 +00001543 Context.getTrivialTypeSourceInfo(Base->getType(),
Douglas Gregor802ab452009-12-02 22:36:29 +00001544 SourceLocation()),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001545 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001546 BaseInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001547 SourceLocation());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001548 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001549 }
1550 }
1551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001553 // non-static data members.
1554 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1555 E = ClassDecl->field_end(); Field != E; ++Field) {
1556 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001557 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001558 Field->getType()->getAs<RecordType>()) {
1559 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001560 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001561 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001562 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1563 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1564 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1565 // set to the anonymous union data member used in the initializer
1566 // list.
1567 Value->setMember(*Field);
1568 Value->setAnonUnionMember(*FA);
1569 AllToInit.push_back(Value);
1570 break;
1571 }
1572 }
1573 }
1574 continue;
1575 }
1576 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1577 AllToInit.push_back(Value);
1578 continue;
1579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001581 if ((*Field)->getType()->isDependentType() || AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001582 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001583
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001584 QualType FT = Context.getBaseElementType((*Field)->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001585 if (FT->getAs<RecordType>()) {
1586 InitializedEntity InitEntity
1587 = InitializedEntity::InitializeMember(*Field);
1588 InitializationKind InitKind
1589 = InitializationKind::CreateDefault(Constructor->getLocation());
1590
1591 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1592 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1593 MultiExprArg(*this, 0, 0));
1594 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1595 if (MemberInit.isInvalid()) {
Eli Friedman80c30da2009-11-09 19:20:36 +00001596 HadError = true;
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001597 continue;
1598 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001599
1600 // Don't attach synthesized member initializers in a dependent
1601 // context; they'll be regenerated a template instantiation
1602 // time.
1603 if (CurContext->isDependentContext())
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001604 continue;
1605
Mike Stump1eb44332009-09-09 15:08:12 +00001606 CXXBaseOrMemberInitializer *Member =
Douglas Gregor802ab452009-12-02 22:36:29 +00001607 new (Context) CXXBaseOrMemberInitializer(Context,
1608 *Field, SourceLocation(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001609 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001610 MemberInit.takeAs<Expr>(),
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001611 SourceLocation());
1612
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001613 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001614 }
1615 else if (FT->isReferenceType()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001616 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001617 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1618 << 0 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001619 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001620 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001621 }
1622 else if (FT.isConstQualified()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001623 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
Eli Friedman49c16da2009-11-09 01:05:47 +00001624 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1625 << 1 << (*Field)->getDeclName();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001626 Diag((*Field)->getLocation(), diag::note_declared_at);
Eli Friedman80c30da2009-11-09 19:20:36 +00001627 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001628 }
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001631 NumInitializers = AllToInit.size();
1632 if (NumInitializers > 0) {
1633 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1634 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1635 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001637 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1638 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1639 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1640 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001641
1642 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001643}
1644
Eli Friedman6347f422009-07-21 19:28:10 +00001645static void *GetKeyForTopLevelField(FieldDecl *Field) {
1646 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001647 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001648 if (RT->getDecl()->isAnonymousStructOrUnion())
1649 return static_cast<void *>(RT->getDecl());
1650 }
1651 return static_cast<void *>(Field);
1652}
1653
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001654static void *GetKeyForBase(QualType BaseType) {
1655 if (const RecordType *RT = BaseType->getAs<RecordType>())
1656 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001658 assert(0 && "Unexpected base type!");
1659 return 0;
1660}
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001663 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001664 // For fields injected into the class via declaration of an anonymous union,
1665 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001666 if (Member->isMemberInitializer()) {
1667 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Eli Friedman49c16da2009-11-09 01:05:47 +00001669 // After SetBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001670 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001671 // in AnonUnionMember field.
1672 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1673 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001674 if (Field->getDeclContext()->isRecord()) {
1675 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1676 if (RD->isAnonymousStructOrUnion())
1677 return static_cast<void *>(RD);
1678 }
1679 return static_cast<void *>(Field);
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001682 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001683}
1684
John McCall6aee6212009-11-04 23:13:52 +00001685/// ActOnMemInitializers - Handle the member initializers for a constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00001686void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001687 SourceLocation ColonLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001688 MemInitTy **MemInits, unsigned NumMemInits,
1689 bool AnyErrors) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001690 if (!ConstructorDecl)
1691 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001692
1693 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001694
1695 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001696 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Anders Carlssona7b35212009-03-25 02:58:17 +00001698 if (!Constructor) {
1699 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1700 return;
1701 }
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001703 if (!Constructor->isDependentContext()) {
1704 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1705 bool err = false;
1706 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001707 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001708 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1709 void *KeyToMember = GetKeyForMember(Member);
1710 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1711 if (!PrevMember) {
1712 PrevMember = Member;
1713 continue;
1714 }
1715 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001716 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001717 diag::error_multiple_mem_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001718 << Field->getNameAsString()
1719 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001720 else {
1721 Type *BaseClass = Member->getBaseClass();
1722 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001723 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001724 diag::error_multiple_base_initialization)
Douglas Gregor802ab452009-12-02 22:36:29 +00001725 << QualType(BaseClass, 0)
1726 << Member->getSourceRange();
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001727 }
1728 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1729 << 0;
1730 err = true;
1731 }
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001733 if (err)
1734 return;
1735 }
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Eli Friedman49c16da2009-11-09 01:05:47 +00001737 SetBaseOrMemberInitializers(Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001738 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001739 NumMemInits, false, AnyErrors);
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001741 if (Constructor->isDependentContext())
1742 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001743
1744 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001745 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001746 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001747 Diagnostic::Ignored)
1748 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001750 // Also issue warning if order of ctor-initializer list does not match order
1751 // of 1) base class declarations and 2) order of non-static data members.
1752 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001754 CXXRecordDecl *ClassDecl
1755 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1756 // Push virtual bases before others.
1757 for (CXXRecordDecl::base_class_iterator VBase =
1758 ClassDecl->vbases_begin(),
1759 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001760 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001762 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1763 E = ClassDecl->bases_end(); Base != E; ++Base) {
1764 // Virtuals are alread in the virtual base list and are constructed
1765 // first.
1766 if (Base->isVirtual())
1767 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001768 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001771 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1772 E = ClassDecl->field_end(); Field != E; ++Field)
1773 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001775 int Last = AllBaseOrMembers.size();
1776 int curIndex = 0;
1777 CXXBaseOrMemberInitializer *PrevMember = 0;
1778 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001779 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001780 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1781 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001782
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001783 for (; curIndex < Last; curIndex++)
1784 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1785 break;
1786 if (curIndex == Last) {
1787 assert(PrevMember && "Member not in member list?!");
1788 // Initializer as specified in ctor-initializer list is out of order.
1789 // Issue a warning diagnostic.
1790 if (PrevMember->isBaseInitializer()) {
1791 // Diagnostics is for an initialized base class.
1792 Type *BaseClass = PrevMember->getBaseClass();
1793 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001794 diag::warn_base_initialized)
John McCallbf1cc052009-09-29 23:03:30 +00001795 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001796 } else {
1797 FieldDecl *Field = PrevMember->getMember();
1798 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001799 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001800 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001801 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001802 // Also the note!
1803 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001804 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001805 diag::note_fieldorbase_initialized_here) << 0
1806 << Field->getNameAsString();
1807 else {
1808 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001809 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001810 diag::note_fieldorbase_initialized_here) << 1
John McCallbf1cc052009-09-29 23:03:30 +00001811 << QualType(BaseClass, 0);
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001812 }
1813 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001814 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001815 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001816 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001817 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001818 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001819}
1820
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001821void
Anders Carlsson9f853df2009-11-17 04:44:12 +00001822Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1823 // Ignore dependent destructors.
1824 if (Destructor->isDependentContext())
1825 return;
1826
1827 CXXRecordDecl *ClassDecl = Destructor->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Anders Carlsson9f853df2009-11-17 04:44:12 +00001829 // Non-static data members.
1830 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1831 E = ClassDecl->field_end(); I != E; ++I) {
1832 FieldDecl *Field = *I;
1833
1834 QualType FieldType = Context.getBaseElementType(Field->getType());
1835
1836 const RecordType* RT = FieldType->getAs<RecordType>();
1837 if (!RT)
1838 continue;
1839
1840 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1841 if (FieldClassDecl->hasTrivialDestructor())
1842 continue;
1843
1844 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1845 MarkDeclarationReferenced(Destructor->getLocation(),
1846 const_cast<CXXDestructorDecl*>(Dtor));
1847 }
1848
1849 // Bases.
1850 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1851 E = ClassDecl->bases_end(); Base != E; ++Base) {
1852 // Ignore virtual bases.
1853 if (Base->isVirtual())
1854 continue;
1855
1856 // Ignore trivial destructors.
1857 CXXRecordDecl *BaseClassDecl
1858 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1859 if (BaseClassDecl->hasTrivialDestructor())
1860 continue;
1861
1862 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1863 MarkDeclarationReferenced(Destructor->getLocation(),
1864 const_cast<CXXDestructorDecl*>(Dtor));
1865 }
1866
1867 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001868 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1869 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
Anders Carlsson9f853df2009-11-17 04:44:12 +00001870 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001871 CXXRecordDecl *BaseClassDecl
1872 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1873 if (BaseClassDecl->hasTrivialDestructor())
1874 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00001875
1876 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1877 MarkDeclarationReferenced(Destructor->getLocation(),
1878 const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001879 }
1880}
1881
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001882void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001883 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001884 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001886 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
1888 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001889 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001890 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001891}
1892
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001893namespace {
1894 /// PureVirtualMethodCollector - traverses a class and its superclasses
1895 /// and determines if it has any pure virtual methods.
Benjamin Kramer85b45212009-11-28 19:45:26 +00001896 class PureVirtualMethodCollector {
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001897 ASTContext &Context;
1898
Sebastian Redldfe292d2009-03-22 21:28:55 +00001899 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001900 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001901
1902 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001903 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001905 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001907 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001908 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001909 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001911 MethodList List;
1912 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001914 // Copy the temporary list to methods, and make sure to ignore any
1915 // null entries.
1916 for (size_t i = 0, e = List.size(); i != e; ++i) {
1917 if (List[i])
1918 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001919 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001920 }
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001922 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001924 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1925 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001926 };
Mike Stump1eb44332009-09-09 15:08:12 +00001927
1928 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001929 MethodList& Methods) {
1930 // First, collect the pure virtual methods for the base classes.
1931 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1932 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001933 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001934 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001935 if (BaseDecl && BaseDecl->isAbstract())
1936 Collect(BaseDecl, Methods);
1937 }
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001940 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001941 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001943 MethodSetTy OverriddenMethods;
1944 size_t MethodsSize = Methods.size();
1945
Mike Stump1eb44332009-09-09 15:08:12 +00001946 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001947 i != e; ++i) {
1948 // Traverse the record, looking for methods.
1949 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001950 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson27823022009-10-18 19:34:08 +00001951 if (MD->isPure())
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001952 Methods.push_back(MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Anders Carlsson27823022009-10-18 19:34:08 +00001954 // Record all the overridden methods in our set.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001955 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1956 E = MD->end_overridden_methods(); I != E; ++I) {
1957 // Keep track of the overridden methods.
1958 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001959 }
1960 }
1961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
1963 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001964 // overridden.
1965 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1966 if (OverriddenMethods.count(Methods[i]))
1967 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001970 }
1971}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001972
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001973
Mike Stump1eb44332009-09-09 15:08:12 +00001974bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001975 unsigned DiagID, AbstractDiagSelID SelID,
1976 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001977 if (SelID == -1)
1978 return RequireNonAbstractType(Loc, T,
1979 PDiag(DiagID), CurrentRD);
1980 else
1981 return RequireNonAbstractType(Loc, T,
1982 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001983}
1984
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001985bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1986 const PartialDiagnostic &PD,
1987 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001988 if (!getLangOptions().CPlusPlus)
1989 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Anders Carlsson11f21a02009-03-23 19:10:31 +00001991 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001992 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001993 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Ted Kremenek6217b802009-07-29 21:53:49 +00001995 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001996 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001997 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001998 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002000 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002001 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Ted Kremenek6217b802009-07-29 21:53:49 +00002004 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002005 if (!RT)
2006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002007
John McCall86ff3082010-02-04 22:26:26 +00002008 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002009
Anders Carlssone65a3c82009-03-24 17:23:42 +00002010 if (CurrentRD && CurrentRD != RD)
2011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall86ff3082010-02-04 22:26:26 +00002013 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002014 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002015 return false;
2016
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002017 if (!RD->isAbstract())
2018 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002020 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002022 // Check if we've already emitted the list of pure virtual functions for this
2023 // class.
2024 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2025 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002027 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002028
2029 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002030 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2031 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
2033 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002034 MD->getDeclName();
2035 }
2036
2037 if (!PureVirtualClassDiagSet)
2038 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2039 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002041 return true;
2042}
2043
Anders Carlsson8211eff2009-03-24 01:19:16 +00002044namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002045 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002046 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2047 Sema &SemaRef;
2048 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Anders Carlssone65a3c82009-03-24 17:23:42 +00002050 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002051 bool Invalid = false;
2052
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002053 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2054 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002055 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002056
Anders Carlsson8211eff2009-03-24 01:19:16 +00002057 return Invalid;
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Anders Carlssone65a3c82009-03-24 17:23:42 +00002060 public:
2061 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2062 : SemaRef(SemaRef), AbstractClass(ac) {
2063 Visit(SemaRef.Context.getTranslationUnitDecl());
2064 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002065
Anders Carlssone65a3c82009-03-24 17:23:42 +00002066 bool VisitFunctionDecl(const FunctionDecl *FD) {
2067 if (FD->isThisDeclarationADefinition()) {
2068 // No need to do the check if we're in a definition, because it requires
2069 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002070 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002071 return VisitDeclContext(FD);
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Anders Carlssone65a3c82009-03-24 17:23:42 +00002074 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002075 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002076 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002077 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2078 diag::err_abstract_type_in_decl,
2079 Sema::AbstractReturnType,
2080 AbstractClass);
2081
Mike Stump1eb44332009-09-09 15:08:12 +00002082 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002083 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002084 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002085 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002086 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002087 VD->getOriginalType(),
2088 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002089 Sema::AbstractParamType,
2090 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002091 }
2092
2093 return Invalid;
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Anders Carlssone65a3c82009-03-24 17:23:42 +00002096 bool VisitDecl(const Decl* D) {
2097 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2098 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Anders Carlssone65a3c82009-03-24 17:23:42 +00002100 return false;
2101 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002102 };
2103}
2104
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002105/// \brief Perform semantic checks on a class definition that has been
2106/// completing, introducing implicitly-declared members, checking for
2107/// abstract types, etc.
2108void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2109 if (!Record || Record->isInvalidDecl())
2110 return;
2111
Eli Friedmanff2d8782009-12-16 20:00:27 +00002112 if (!Record->isDependentType())
2113 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002114
Eli Friedmanff2d8782009-12-16 20:00:27 +00002115 if (Record->isInvalidDecl())
2116 return;
2117
John McCall233a6412010-01-28 07:38:46 +00002118 // Set access bits correctly on the directly-declared conversions.
2119 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2120 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2121 Convs->setAccess(I, (*I)->getAccess());
2122
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002123 if (!Record->isAbstract()) {
2124 // Collect all the pure virtual methods and see if this is an abstract
2125 // class after all.
2126 PureVirtualMethodCollector Collector(Context, Record);
2127 if (!Collector.empty())
2128 Record->setAbstract(true);
2129 }
2130
2131 if (Record->isAbstract())
2132 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002133}
2134
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002135void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002136 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002137 SourceLocation LBrac,
2138 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002139 if (!TagDecl)
2140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Douglas Gregor42af25f2009-05-11 19:58:34 +00002142 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002143
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002144 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002145 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002146 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002147
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002148 CheckCompletedCXXClass(
2149 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002150}
2151
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002152/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2153/// special functions, such as the default constructor, copy
2154/// constructor, or destructor, to the given C++ class (C++
2155/// [special]p1). This routine can only be executed just before the
2156/// definition of the class is complete.
2157void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002158 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002159 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002160
Sebastian Redl465226e2009-05-27 22:11:52 +00002161 // FIXME: Implicit declarations have exception specifications, which are
2162 // the union of the specifications of the implicitly called functions.
2163
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002164 if (!ClassDecl->hasUserDeclaredConstructor()) {
2165 // C++ [class.ctor]p5:
2166 // A default constructor for a class X is a constructor of class X
2167 // that can be called without an argument. If there is no
2168 // user-declared constructor for class X, a default constructor is
2169 // implicitly declared. An implicitly-declared default constructor
2170 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002171 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002172 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002173 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002174 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002175 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002176 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002177 0, 0, false, 0,
2178 /*FIXME*/false, false,
2179 0, 0, false,
2180 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002181 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002182 /*isExplicit=*/false,
2183 /*isInline=*/true,
2184 /*isImplicitlyDeclared=*/true);
2185 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002186 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002187 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002188 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002189 }
2190
2191 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2192 // C++ [class.copy]p4:
2193 // If the class definition does not explicitly declare a copy
2194 // constructor, one is declared implicitly.
2195
2196 // C++ [class.copy]p5:
2197 // The implicitly-declared copy constructor for a class X will
2198 // have the form
2199 //
2200 // X::X(const X&)
2201 //
2202 // if
2203 bool HasConstCopyConstructor = true;
2204
2205 // -- each direct or virtual base class B of X has a copy
2206 // constructor whose first parameter is of type const B& or
2207 // const volatile B&, and
2208 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2209 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2210 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002211 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002212 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002213 = BaseClassDecl->hasConstCopyConstructor(Context);
2214 }
2215
2216 // -- for all the nonstatic data members of X that are of a
2217 // class type M (or array thereof), each such class type
2218 // has a copy constructor whose first parameter is of type
2219 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002220 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2221 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002222 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002223 QualType FieldType = (*Field)->getType();
2224 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2225 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002226 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002227 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002228 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002229 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002230 = FieldClassDecl->hasConstCopyConstructor(Context);
2231 }
2232 }
2233
Sebastian Redl64b45f72009-01-05 20:52:13 +00002234 // Otherwise, the implicitly declared copy constructor will have
2235 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002236 //
2237 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002238 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002239 if (HasConstCopyConstructor)
2240 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002241 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002242
Sebastian Redl64b45f72009-01-05 20:52:13 +00002243 // An implicitly-declared copy constructor is an inline public
2244 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002245 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002246 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002247 CXXConstructorDecl *CopyConstructor
2248 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002249 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002250 Context.getFunctionType(Context.VoidTy,
2251 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002252 false, 0,
2253 /*FIXME:*/false,
2254 false, 0, 0, false,
2255 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002256 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002257 /*isExplicit=*/false,
2258 /*isInline=*/true,
2259 /*isImplicitlyDeclared=*/true);
2260 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002261 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002262 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002263
2264 // Add the parameter to the constructor.
2265 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2266 ClassDecl->getLocation(),
2267 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002268 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002269 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002270 CopyConstructor->setParams(&FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002271 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002272 }
2273
Sebastian Redl64b45f72009-01-05 20:52:13 +00002274 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2275 // Note: The following rules are largely analoguous to the copy
2276 // constructor rules. Note that virtual bases are not taken into account
2277 // for determining the argument type of the operator. Note also that
2278 // operators taking an object instead of a reference are allowed.
2279 //
2280 // C++ [class.copy]p10:
2281 // If the class definition does not explicitly declare a copy
2282 // assignment operator, one is declared implicitly.
2283 // The implicitly-defined copy assignment operator for a class X
2284 // will have the form
2285 //
2286 // X& X::operator=(const X&)
2287 //
2288 // if
2289 bool HasConstCopyAssignment = true;
2290
2291 // -- each direct base class B of X has a copy assignment operator
2292 // whose parameter is of type const B&, const volatile B& or B,
2293 // and
2294 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2295 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002296 assert(!Base->getType()->isDependentType() &&
2297 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002298 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002299 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002300 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002301 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002302 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002303 }
2304
2305 // -- for all the nonstatic data members of X that are of a class
2306 // type M (or array thereof), each such class type has a copy
2307 // assignment operator whose parameter is of type const M&,
2308 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002309 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2310 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002311 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002312 QualType FieldType = (*Field)->getType();
2313 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2314 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002315 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002316 const CXXRecordDecl *FieldClassDecl
2317 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002318 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002319 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002320 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002321 }
2322 }
2323
2324 // Otherwise, the implicitly declared copy assignment operator will
2325 // have the form
2326 //
2327 // X& X::operator=(X&)
2328 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002329 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002330 if (HasConstCopyAssignment)
2331 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002332 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002333
2334 // An implicitly-declared copy assignment operator is an inline public
2335 // member of its class.
2336 DeclarationName Name =
2337 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2338 CXXMethodDecl *CopyAssignment =
2339 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2340 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002341 false, 0,
2342 /*FIXME:*/false,
2343 false, 0, 0, false,
2344 CC_Default),
John McCalla93c9342009-12-07 02:54:59 +00002345 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002346 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002347 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002348 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002349 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002350
2351 // Add the parameter to the operator.
2352 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2353 ClassDecl->getLocation(),
2354 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002355 ArgType, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002356 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002357 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002358
2359 // Don't call addedAssignmentOperator. There is no way to distinguish an
2360 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002361 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002362 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002363 }
2364
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002365 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002366 // C++ [class.dtor]p2:
2367 // If a class has no user-declared destructor, a destructor is
2368 // declared implicitly. An implicitly-declared destructor is an
2369 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002370 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002371 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002372 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002373 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002374 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002375 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002376 0, 0, false, 0,
2377 /*FIXME:*/false,
2378 false, 0, 0, false,
2379 CC_Default),
Douglas Gregor42a552f2008-11-05 20:51:48 +00002380 /*isInline=*/true,
2381 /*isImplicitlyDeclared=*/true);
2382 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002383 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002384 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002385 ClassDecl->addDecl(Destructor);
Anders Carlssond5a942b2009-11-26 21:25:09 +00002386
2387 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002388 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002389}
2390
Douglas Gregor6569d682009-05-27 23:11:45 +00002391void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002392 Decl *D = TemplateD.getAs<Decl>();
2393 if (!D)
2394 return;
2395
2396 TemplateParameterList *Params = 0;
2397 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2398 Params = Template->getTemplateParameters();
2399 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2400 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2401 Params = PartialSpec->getTemplateParameters();
2402 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002403 return;
2404
Douglas Gregor6569d682009-05-27 23:11:45 +00002405 for (TemplateParameterList::iterator Param = Params->begin(),
2406 ParamEnd = Params->end();
2407 Param != ParamEnd; ++Param) {
2408 NamedDecl *Named = cast<NamedDecl>(*Param);
2409 if (Named->getDeclName()) {
2410 S->AddDecl(DeclPtrTy::make(Named));
2411 IdResolver.AddDecl(Named);
2412 }
2413 }
2414}
2415
John McCall7a1dc562009-12-19 10:49:29 +00002416void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2417 if (!RecordD) return;
2418 AdjustDeclIfTemplate(RecordD);
2419 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2420 PushDeclContext(S, Record);
2421}
2422
2423void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2424 if (!RecordD) return;
2425 PopDeclContext();
2426}
2427
Douglas Gregor72b505b2008-12-16 21:30:33 +00002428/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2429/// parsing a top-level (non-nested) C++ class, and we are now
2430/// parsing those parts of the given Method declaration that could
2431/// not be parsed earlier (C++ [class.mem]p2), such as default
2432/// arguments. This action should enter the scope of the given
2433/// Method declaration as if we had just parsed the qualified method
2434/// name. However, it should not bring the parameters into scope;
2435/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002436void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002437}
2438
2439/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2440/// C++ method declaration. We're (re-)introducing the given
2441/// function parameter into scope for use in parsing later parts of
2442/// the method declaration. For example, we could see an
2443/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002444void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002445 if (!ParamD)
2446 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002447
Chris Lattnerb28317a2009-03-28 19:18:32 +00002448 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002449
2450 // If this parameter has an unparsed default argument, clear it out
2451 // to make way for the parsed default argument.
2452 if (Param->hasUnparsedDefaultArg())
2453 Param->setDefaultArg(0);
2454
Chris Lattnerb28317a2009-03-28 19:18:32 +00002455 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002456 if (Param->getDeclName())
2457 IdResolver.AddDecl(Param);
2458}
2459
2460/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2461/// processing the delayed method declaration for Method. The method
2462/// declaration is now considered finished. There may be a separate
2463/// ActOnStartOfFunctionDef action later (not necessarily
2464/// immediately!) for this method, if it was also defined inside the
2465/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002466void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002467 if (!MethodD)
2468 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002470 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Chris Lattnerb28317a2009-03-28 19:18:32 +00002472 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002473
2474 // Now that we have our default arguments, check the constructor
2475 // again. It could produce additional diagnostics or affect whether
2476 // the class has implicitly-declared destructors, among other
2477 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002478 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2479 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002480
2481 // Check the default arguments, which we may have added.
2482 if (!Method->isInvalidDecl())
2483 CheckCXXDefaultArguments(Method);
2484}
2485
Douglas Gregor42a552f2008-11-05 20:51:48 +00002486/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002487/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002488/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002489/// emit diagnostics and set the invalid bit to true. In any case, the type
2490/// will be updated to reflect a well-formed type for the constructor and
2491/// returned.
2492QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2493 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002494 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002495
2496 // C++ [class.ctor]p3:
2497 // A constructor shall not be virtual (10.3) or static (9.4). A
2498 // constructor can be invoked for a const, volatile or const
2499 // volatile object. A constructor shall not be declared const,
2500 // volatile, or const volatile (9.3.2).
2501 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002502 if (!D.isInvalidType())
2503 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2504 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2505 << SourceRange(D.getIdentifierLoc());
2506 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002507 }
2508 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002509 if (!D.isInvalidType())
2510 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2511 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2512 << SourceRange(D.getIdentifierLoc());
2513 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002514 SC = FunctionDecl::None;
2515 }
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Chris Lattner65401802009-04-25 08:28:21 +00002517 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2518 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002519 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002520 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2521 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002522 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002523 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2524 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002525 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002526 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2527 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002528 }
Mike Stump1eb44332009-09-09 15:08:12 +00002529
Douglas Gregor42a552f2008-11-05 20:51:48 +00002530 // Rebuild the function type "R" without any type qualifiers (in
2531 // case any of the errors above fired) and with "void" as the
2532 // return type, since constructors don't have return types. We
2533 // *always* have to do this, because GetTypeForDeclarator will
2534 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002535 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002536 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2537 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002538 Proto->isVariadic(), 0,
2539 Proto->hasExceptionSpec(),
2540 Proto->hasAnyExceptionSpec(),
2541 Proto->getNumExceptions(),
2542 Proto->exception_begin(),
2543 Proto->getNoReturnAttr(),
2544 Proto->getCallConv());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002545}
2546
Douglas Gregor72b505b2008-12-16 21:30:33 +00002547/// CheckConstructor - Checks a fully-formed constructor for
2548/// well-formedness, issuing any diagnostics required. Returns true if
2549/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002550void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002551 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002552 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2553 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002554 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002555
2556 // C++ [class.copy]p3:
2557 // A declaration of a constructor for a class X is ill-formed if
2558 // its first parameter is of type (optionally cv-qualified) X and
2559 // either there are no other parameters or else all other
2560 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002561 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002562 ((Constructor->getNumParams() == 1) ||
2563 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002564 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2565 Constructor->getTemplateSpecializationKind()
2566 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002567 QualType ParamType = Constructor->getParamDecl(0)->getType();
2568 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2569 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002570 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2571 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002572 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002573
2574 // FIXME: Rather that making the constructor invalid, we should endeavor
2575 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002576 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002577 }
2578 }
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Douglas Gregor72b505b2008-12-16 21:30:33 +00002580 // Notify the class that we've added a constructor.
2581 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002582}
2583
Anders Carlsson37909802009-11-30 21:24:50 +00002584/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2585/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002586bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002587 CXXRecordDecl *RD = Destructor->getParent();
2588
2589 if (Destructor->isVirtual()) {
2590 SourceLocation Loc;
2591
2592 if (!Destructor->isImplicit())
2593 Loc = Destructor->getLocation();
2594 else
2595 Loc = RD->getLocation();
2596
2597 // If we have a virtual destructor, look up the deallocation function
2598 FunctionDecl *OperatorDelete = 0;
2599 DeclarationName Name =
2600 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002601 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002602 return true;
2603
2604 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002605 }
Anders Carlsson37909802009-11-30 21:24:50 +00002606
2607 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002608}
2609
Mike Stump1eb44332009-09-09 15:08:12 +00002610static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002611FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2612 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2613 FTI.ArgInfo[0].Param &&
2614 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2615}
2616
Douglas Gregor42a552f2008-11-05 20:51:48 +00002617/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2618/// the well-formednes of the destructor declarator @p D with type @p
2619/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002620/// emit diagnostics and set the declarator to invalid. Even if this happens,
2621/// will be updated to reflect a well-formed type for the destructor and
2622/// returned.
2623QualType Sema::CheckDestructorDeclarator(Declarator &D,
2624 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002625 // C++ [class.dtor]p1:
2626 // [...] A typedef-name that names a class is a class-name
2627 // (7.1.3); however, a typedef-name that names a class shall not
2628 // be used as the identifier in the declarator for a destructor
2629 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002630 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002631 if (isa<TypedefType>(DeclaratorType)) {
2632 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002633 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002634 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002635 }
2636
2637 // C++ [class.dtor]p2:
2638 // A destructor is used to destroy objects of its class type. A
2639 // destructor takes no parameters, and no return type can be
2640 // specified for it (not even void). The address of a destructor
2641 // shall not be taken. A destructor shall not be static. A
2642 // destructor can be invoked for a const, volatile or const
2643 // volatile object. A destructor shall not be declared const,
2644 // volatile or const volatile (9.3.2).
2645 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002646 if (!D.isInvalidType())
2647 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2648 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2649 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002650 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002651 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002652 }
Chris Lattner65401802009-04-25 08:28:21 +00002653 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002654 // Destructors don't have return types, but the parser will
2655 // happily parse something like:
2656 //
2657 // class X {
2658 // float ~X();
2659 // };
2660 //
2661 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002662 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2663 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2664 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002665 }
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Chris Lattner65401802009-04-25 08:28:21 +00002667 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2668 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002669 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002670 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2671 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002672 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002673 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2674 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002675 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002676 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2677 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002678 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002679 }
2680
2681 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002682 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002683 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2684
2685 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002686 FTI.freeArgs();
2687 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002688 }
2689
Mike Stump1eb44332009-09-09 15:08:12 +00002690 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002691 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002692 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002693 D.setInvalidType();
2694 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002695
2696 // Rebuild the function type "R" without any type qualifiers or
2697 // parameters (in case any of the errors above fired) and with
2698 // "void" as the return type, since destructors don't have return
2699 // types. We *always* have to do this, because GetTypeForDeclarator
2700 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002701 // FIXME: Exceptions!
2702 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2703 false, false, 0, 0, false, CC_Default);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002704}
2705
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002706/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2707/// well-formednes of the conversion function declarator @p D with
2708/// type @p R. If there are any errors in the declarator, this routine
2709/// will emit diagnostics and return true. Otherwise, it will return
2710/// false. Either way, the type @p R will be updated to reflect a
2711/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002712void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002713 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002714 // C++ [class.conv.fct]p1:
2715 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002716 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002717 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002718 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002719 if (!D.isInvalidType())
2720 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2721 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2722 << SourceRange(D.getIdentifierLoc());
2723 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002724 SC = FunctionDecl::None;
2725 }
Chris Lattner6e475012009-04-25 08:35:12 +00002726 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002727 // Conversion functions don't have return types, but the parser will
2728 // happily parse something like:
2729 //
2730 // class X {
2731 // float operator bool();
2732 // };
2733 //
2734 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002735 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2736 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2737 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002738 }
2739
2740 // Make sure we don't have any parameters.
John McCall183700f2009-09-21 23:43:11 +00002741 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002742 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2743
2744 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002745 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002746 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002747 }
2748
Mike Stump1eb44332009-09-09 15:08:12 +00002749 // Make sure the conversion function isn't variadic.
John McCall183700f2009-09-21 23:43:11 +00002750 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002751 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002752 D.setInvalidType();
2753 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002754
2755 // C++ [class.conv.fct]p4:
2756 // The conversion-type-id shall not represent a function type nor
2757 // an array type.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002758 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002759 if (ConvType->isArrayType()) {
2760 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2761 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002762 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002763 } else if (ConvType->isFunctionType()) {
2764 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2765 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002766 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002767 }
2768
2769 // Rebuild the function type "R" without any parameters (in case any
2770 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002771 // return type.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002772 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002773 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002774 Proto->getTypeQuals(),
2775 Proto->hasExceptionSpec(),
2776 Proto->hasAnyExceptionSpec(),
2777 Proto->getNumExceptions(),
2778 Proto->exception_begin(),
2779 Proto->getNoReturnAttr(),
2780 Proto->getCallConv());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002781
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002782 // C++0x explicit conversion operators.
2783 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002784 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002785 diag::warn_explicit_conversion_functions)
2786 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002787}
2788
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002789/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2790/// the declaration of the given C++ conversion function. This routine
2791/// is responsible for recording the conversion function in the C++
2792/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002793Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002794 assert(Conversion && "Expected to receive a conversion function declaration");
2795
Douglas Gregor9d350972008-12-12 08:25:50 +00002796 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002797
2798 // Make sure we aren't redeclaring the conversion function.
2799 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002800
2801 // C++ [class.conv.fct]p1:
2802 // [...] A conversion function is never used to convert a
2803 // (possibly cv-qualified) object to the (possibly cv-qualified)
2804 // same object type (or a reference to it), to a (possibly
2805 // cv-qualified) base class of that type (or a reference to it),
2806 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002807 // FIXME: Suppress this warning if the conversion function ends up being a
2808 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002809 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002810 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002811 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002812 ConvType = ConvTypeRef->getPointeeType();
2813 if (ConvType->isRecordType()) {
2814 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2815 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002816 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002817 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002818 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002819 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002820 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002821 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002822 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002823 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002824 }
2825
Douglas Gregor48026d22010-01-11 18:40:55 +00002826 if (Conversion->getPrimaryTemplate()) {
2827 // ignore specializations
2828 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002829 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00002830 = Conversion->getDescribedFunctionTemplate()) {
2831 if (ClassDecl->replaceConversion(
2832 ConversionTemplate->getPreviousDeclaration(),
2833 ConversionTemplate))
2834 return DeclPtrTy::make(ConversionTemplate);
2835 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2836 Conversion))
John McCallba135432009-11-21 08:51:07 +00002837 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002838 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002839 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002840 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002841 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00002842 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00002843 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002844
Chris Lattnerb28317a2009-03-28 19:18:32 +00002845 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002846}
2847
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002848//===----------------------------------------------------------------------===//
2849// Namespace Handling
2850//===----------------------------------------------------------------------===//
2851
2852/// ActOnStartNamespaceDef - This is called at the start of a namespace
2853/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002854Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2855 SourceLocation IdentLoc,
2856 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002857 SourceLocation LBrace,
2858 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002859 NamespaceDecl *Namespc =
2860 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2861 Namespc->setLBracLoc(LBrace);
2862
2863 Scope *DeclRegionScope = NamespcScope->getParent();
2864
Anders Carlsson2a3503d2010-02-07 01:09:23 +00002865 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2866
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002867 if (II) {
2868 // C++ [namespace.def]p2:
2869 // The identifier in an original-namespace-definition shall not have been
2870 // previously defined in the declarative region in which the
2871 // original-namespace-definition appears. The identifier in an
2872 // original-namespace-definition is the name of the namespace. Subsequently
2873 // in that declarative region, it is treated as an original-namespace-name.
2874
John McCallf36e02d2009-10-09 21:13:30 +00002875 NamedDecl *PrevDecl
John McCalla24dc2e2009-11-17 02:14:36 +00002876 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00002877 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Douglas Gregor44b43212008-12-11 16:49:14 +00002879 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2880 // This is an extended namespace definition.
2881 // Attach this namespace decl to the chain of extended namespace
2882 // definitions.
2883 OrigNS->setNextNamespace(Namespc);
2884 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002885
Mike Stump1eb44332009-09-09 15:08:12 +00002886 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002887 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002888 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002889 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002890 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002891 } else if (PrevDecl) {
2892 // This is an invalid name redefinition.
2893 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2894 << Namespc->getDeclName();
2895 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2896 Namespc->setInvalidDecl();
2897 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00002898 } else if (II->isStr("std") &&
2899 CurContext->getLookupContext()->isTranslationUnit()) {
2900 // This is the first "real" definition of the namespace "std", so update
2901 // our cache of the "std" namespace to point at this definition.
2902 if (StdNamespace) {
2903 // We had already defined a dummy namespace "std". Link this new
2904 // namespace definition to the dummy namespace "std".
2905 StdNamespace->setNextNamespace(Namespc);
2906 StdNamespace->setLocation(IdentLoc);
2907 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2908 }
2909
2910 // Make our StdNamespace cache point at the first real definition of the
2911 // "std" namespace.
2912 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00002913 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002914
2915 PushOnScopeChains(Namespc, DeclRegionScope);
2916 } else {
John McCall9aeed322009-10-01 00:25:31 +00002917 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00002918 assert(Namespc->isAnonymousNamespace());
2919 CurContext->addDecl(Namespc);
2920
2921 // Link the anonymous namespace into its parent.
2922 NamespaceDecl *PrevDecl;
2923 DeclContext *Parent = CurContext->getLookupContext();
2924 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2925 PrevDecl = TU->getAnonymousNamespace();
2926 TU->setAnonymousNamespace(Namespc);
2927 } else {
2928 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2929 PrevDecl = ND->getAnonymousNamespace();
2930 ND->setAnonymousNamespace(Namespc);
2931 }
2932
2933 // Link the anonymous namespace with its previous declaration.
2934 if (PrevDecl) {
2935 assert(PrevDecl->isAnonymousNamespace());
2936 assert(!PrevDecl->getNextNamespace());
2937 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2938 PrevDecl->setNextNamespace(Namespc);
2939 }
John McCall9aeed322009-10-01 00:25:31 +00002940
2941 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2942 // behaves as if it were replaced by
2943 // namespace unique { /* empty body */ }
2944 // using namespace unique;
2945 // namespace unique { namespace-body }
2946 // where all occurrences of 'unique' in a translation unit are
2947 // replaced by the same identifier and this identifier differs
2948 // from all other identifiers in the entire program.
2949
2950 // We just create the namespace with an empty name and then add an
2951 // implicit using declaration, just like the standard suggests.
2952 //
2953 // CodeGen enforces the "universally unique" aspect by giving all
2954 // declarations semantically contained within an anonymous
2955 // namespace internal linkage.
2956
John McCall5fdd7642009-12-16 02:06:49 +00002957 if (!PrevDecl) {
2958 UsingDirectiveDecl* UD
2959 = UsingDirectiveDecl::Create(Context, CurContext,
2960 /* 'using' */ LBrace,
2961 /* 'namespace' */ SourceLocation(),
2962 /* qualifier */ SourceRange(),
2963 /* NNS */ NULL,
2964 /* identifier */ SourceLocation(),
2965 Namespc,
2966 /* Ancestor */ CurContext);
2967 UD->setImplicit();
2968 CurContext->addDecl(UD);
2969 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002970 }
2971
2972 // Although we could have an invalid decl (i.e. the namespace name is a
2973 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002974 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2975 // for the namespace has the declarations that showed up in that particular
2976 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002977 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002978 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002979}
2980
Sebastian Redleb0d8c92009-11-23 15:34:23 +00002981/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2982/// is a namespace alias, returns the namespace it points to.
2983static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2984 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2985 return AD->getNamespace();
2986 return dyn_cast_or_null<NamespaceDecl>(D);
2987}
2988
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002989/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2990/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002991void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2992 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002993 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2994 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2995 Namespc->setRBracLoc(RBrace);
2996 PopDeclContext();
2997}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002998
Chris Lattnerb28317a2009-03-28 19:18:32 +00002999Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3000 SourceLocation UsingLoc,
3001 SourceLocation NamespcLoc,
3002 const CXXScopeSpec &SS,
3003 SourceLocation IdentLoc,
3004 IdentifierInfo *NamespcName,
3005 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003006 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3007 assert(NamespcName && "Invalid NamespcName.");
3008 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003009 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003010
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003011 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003012
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003013 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003014 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3015 LookupParsedName(R, S, &SS);
3016 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003017 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003018
John McCallf36e02d2009-10-09 21:13:30 +00003019 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003020 NamedDecl *Named = R.getFoundDecl();
3021 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3022 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003023 // C++ [namespace.udir]p1:
3024 // A using-directive specifies that the names in the nominated
3025 // namespace can be used in the scope in which the
3026 // using-directive appears after the using-directive. During
3027 // unqualified name lookup (3.4.1), the names appear as if they
3028 // were declared in the nearest enclosing namespace which
3029 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003030 // namespace. [Note: in this context, "contains" means "contains
3031 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003032
3033 // Find enclosing context containing both using-directive and
3034 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003035 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003036 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3037 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3038 CommonAncestor = CommonAncestor->getParent();
3039
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003040 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003041 SS.getRange(),
3042 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003043 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003044 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003045 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003046 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003047 }
3048
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003049 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003050 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003051 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003052}
3053
3054void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3055 // If scope has associated entity, then using directive is at namespace
3056 // or translation unit scope. We add UsingDirectiveDecls, into
3057 // it's lookup structure.
3058 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003059 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003060 else
3061 // Otherwise it is block-sope. using-directives will affect lookup
3062 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003063 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003064}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003065
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003066
3067Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003068 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003069 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003070 SourceLocation UsingLoc,
3071 const CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003072 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003073 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003074 bool IsTypeName,
3075 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003076 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Douglas Gregor12c118a2009-11-04 16:30:06 +00003078 switch (Name.getKind()) {
3079 case UnqualifiedId::IK_Identifier:
3080 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003081 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003082 case UnqualifiedId::IK_ConversionFunctionId:
3083 break;
3084
3085 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003086 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003087 // C++0x inherited constructors.
3088 if (getLangOptions().CPlusPlus0x) break;
3089
Douglas Gregor12c118a2009-11-04 16:30:06 +00003090 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3091 << SS.getRange();
3092 return DeclPtrTy();
3093
3094 case UnqualifiedId::IK_DestructorName:
3095 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3096 << SS.getRange();
3097 return DeclPtrTy();
3098
3099 case UnqualifiedId::IK_TemplateId:
3100 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3101 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3102 return DeclPtrTy();
3103 }
3104
3105 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003106 if (!TargetName)
3107 return DeclPtrTy();
3108
John McCall60fa3cf2009-12-11 02:10:03 +00003109 // Warn about using declarations.
3110 // TODO: store that the declaration was written without 'using' and
3111 // talk about access decls instead of using decls in the
3112 // diagnostics.
3113 if (!HasUsingKeyword) {
3114 UsingLoc = Name.getSourceRange().getBegin();
3115
3116 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3117 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3118 "using ");
3119 }
3120
John McCall9488ea12009-11-17 05:59:44 +00003121 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003122 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003123 TargetName, AttrList,
3124 /* IsInstantiation */ false,
3125 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003126 if (UD)
3127 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Anders Carlssonc72160b2009-08-28 05:40:36 +00003129 return DeclPtrTy::make(UD);
3130}
3131
John McCall9f54ad42009-12-10 09:41:52 +00003132/// Determines whether to create a using shadow decl for a particular
3133/// decl, given the set of decls existing prior to this using lookup.
3134bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3135 const LookupResult &Previous) {
3136 // Diagnose finding a decl which is not from a base class of the
3137 // current class. We do this now because there are cases where this
3138 // function will silently decide not to build a shadow decl, which
3139 // will pre-empt further diagnostics.
3140 //
3141 // We don't need to do this in C++0x because we do the check once on
3142 // the qualifier.
3143 //
3144 // FIXME: diagnose the following if we care enough:
3145 // struct A { int foo; };
3146 // struct B : A { using A::foo; };
3147 // template <class T> struct C : A {};
3148 // template <class T> struct D : C<T> { using B::foo; } // <---
3149 // This is invalid (during instantiation) in C++03 because B::foo
3150 // resolves to the using decl in B, which is not a base class of D<T>.
3151 // We can't diagnose it immediately because C<T> is an unknown
3152 // specialization. The UsingShadowDecl in D<T> then points directly
3153 // to A::foo, which will look well-formed when we instantiate.
3154 // The right solution is to not collapse the shadow-decl chain.
3155 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3156 DeclContext *OrigDC = Orig->getDeclContext();
3157
3158 // Handle enums and anonymous structs.
3159 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3160 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3161 while (OrigRec->isAnonymousStructOrUnion())
3162 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3163
3164 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3165 if (OrigDC == CurContext) {
3166 Diag(Using->getLocation(),
3167 diag::err_using_decl_nested_name_specifier_is_current_class)
3168 << Using->getNestedNameRange();
3169 Diag(Orig->getLocation(), diag::note_using_decl_target);
3170 return true;
3171 }
3172
3173 Diag(Using->getNestedNameRange().getBegin(),
3174 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3175 << Using->getTargetNestedNameDecl()
3176 << cast<CXXRecordDecl>(CurContext)
3177 << Using->getNestedNameRange();
3178 Diag(Orig->getLocation(), diag::note_using_decl_target);
3179 return true;
3180 }
3181 }
3182
3183 if (Previous.empty()) return false;
3184
3185 NamedDecl *Target = Orig;
3186 if (isa<UsingShadowDecl>(Target))
3187 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3188
John McCalld7533ec2009-12-11 02:33:26 +00003189 // If the target happens to be one of the previous declarations, we
3190 // don't have a conflict.
3191 //
3192 // FIXME: but we might be increasing its access, in which case we
3193 // should redeclare it.
3194 NamedDecl *NonTag = 0, *Tag = 0;
3195 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3196 I != E; ++I) {
3197 NamedDecl *D = (*I)->getUnderlyingDecl();
3198 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3199 return false;
3200
3201 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3202 }
3203
John McCall9f54ad42009-12-10 09:41:52 +00003204 if (Target->isFunctionOrFunctionTemplate()) {
3205 FunctionDecl *FD;
3206 if (isa<FunctionTemplateDecl>(Target))
3207 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3208 else
3209 FD = cast<FunctionDecl>(Target);
3210
3211 NamedDecl *OldDecl = 0;
3212 switch (CheckOverload(FD, Previous, OldDecl)) {
3213 case Ovl_Overload:
3214 return false;
3215
3216 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003217 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003218 break;
3219
3220 // We found a decl with the exact signature.
3221 case Ovl_Match:
3222 if (isa<UsingShadowDecl>(OldDecl)) {
3223 // Silently ignore the possible conflict.
3224 return false;
3225 }
3226
3227 // If we're in a record, we want to hide the target, so we
3228 // return true (without a diagnostic) to tell the caller not to
3229 // build a shadow decl.
3230 if (CurContext->isRecord())
3231 return true;
3232
3233 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003234 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003235 break;
3236 }
3237
3238 Diag(Target->getLocation(), diag::note_using_decl_target);
3239 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3240 return true;
3241 }
3242
3243 // Target is not a function.
3244
John McCall9f54ad42009-12-10 09:41:52 +00003245 if (isa<TagDecl>(Target)) {
3246 // No conflict between a tag and a non-tag.
3247 if (!Tag) return false;
3248
John McCall41ce66f2009-12-10 19:51:03 +00003249 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003250 Diag(Target->getLocation(), diag::note_using_decl_target);
3251 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3252 return true;
3253 }
3254
3255 // No conflict between a tag and a non-tag.
3256 if (!NonTag) return false;
3257
John McCall41ce66f2009-12-10 19:51:03 +00003258 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003259 Diag(Target->getLocation(), diag::note_using_decl_target);
3260 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3261 return true;
3262}
3263
John McCall9488ea12009-11-17 05:59:44 +00003264/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003265UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003266 UsingDecl *UD,
3267 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003268
3269 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003270 NamedDecl *Target = Orig;
3271 if (isa<UsingShadowDecl>(Target)) {
3272 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3273 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003274 }
3275
3276 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003277 = UsingShadowDecl::Create(Context, CurContext,
3278 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003279 UD->addShadowDecl(Shadow);
3280
3281 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003282 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003283 else
John McCall604e7f12009-12-08 07:46:18 +00003284 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003285 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003286
John McCall604e7f12009-12-08 07:46:18 +00003287 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3288 Shadow->setInvalidDecl();
3289
John McCall9f54ad42009-12-10 09:41:52 +00003290 return Shadow;
3291}
John McCall604e7f12009-12-08 07:46:18 +00003292
John McCall9f54ad42009-12-10 09:41:52 +00003293/// Hides a using shadow declaration. This is required by the current
3294/// using-decl implementation when a resolvable using declaration in a
3295/// class is followed by a declaration which would hide or override
3296/// one or more of the using decl's targets; for example:
3297///
3298/// struct Base { void foo(int); };
3299/// struct Derived : Base {
3300/// using Base::foo;
3301/// void foo(int);
3302/// };
3303///
3304/// The governing language is C++03 [namespace.udecl]p12:
3305///
3306/// When a using-declaration brings names from a base class into a
3307/// derived class scope, member functions in the derived class
3308/// override and/or hide member functions with the same name and
3309/// parameter types in a base class (rather than conflicting).
3310///
3311/// There are two ways to implement this:
3312/// (1) optimistically create shadow decls when they're not hidden
3313/// by existing declarations, or
3314/// (2) don't create any shadow decls (or at least don't make them
3315/// visible) until we've fully parsed/instantiated the class.
3316/// The problem with (1) is that we might have to retroactively remove
3317/// a shadow decl, which requires several O(n) operations because the
3318/// decl structures are (very reasonably) not designed for removal.
3319/// (2) avoids this but is very fiddly and phase-dependent.
3320void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3321 // Remove it from the DeclContext...
3322 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003323
John McCall9f54ad42009-12-10 09:41:52 +00003324 // ...and the scope, if applicable...
3325 if (S) {
3326 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3327 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003328 }
3329
John McCall9f54ad42009-12-10 09:41:52 +00003330 // ...and the using decl.
3331 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3332
3333 // TODO: complain somehow if Shadow was used. It shouldn't
3334 // be possible for this to happen, because
John McCall9488ea12009-11-17 05:59:44 +00003335}
3336
John McCall7ba107a2009-11-18 02:36:19 +00003337/// Builds a using declaration.
3338///
3339/// \param IsInstantiation - Whether this call arises from an
3340/// instantiation of an unresolved using declaration. We treat
3341/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003342NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3343 SourceLocation UsingLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003344 const CXXScopeSpec &SS,
3345 SourceLocation IdentLoc,
3346 DeclarationName Name,
3347 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003348 bool IsInstantiation,
3349 bool IsTypeName,
3350 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003351 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3352 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003353
Anders Carlsson550b14b2009-08-28 05:49:21 +00003354 // FIXME: We ignore attributes for now.
3355 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003357 if (SS.isEmpty()) {
3358 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003359 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003360 }
Mike Stump1eb44332009-09-09 15:08:12 +00003361
John McCall9f54ad42009-12-10 09:41:52 +00003362 // Do the redeclaration lookup in the current scope.
3363 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3364 ForRedeclaration);
3365 Previous.setHideTags(false);
3366 if (S) {
3367 LookupName(Previous, S);
3368
3369 // It is really dumb that we have to do this.
3370 LookupResult::Filter F = Previous.makeFilter();
3371 while (F.hasNext()) {
3372 NamedDecl *D = F.next();
3373 if (!isDeclInScope(D, CurContext, S))
3374 F.erase();
3375 }
3376 F.done();
3377 } else {
3378 assert(IsInstantiation && "no scope in non-instantiation");
3379 assert(CurContext->isRecord() && "scope not record in instantiation");
3380 LookupQualifiedName(Previous, CurContext);
3381 }
3382
Mike Stump1eb44332009-09-09 15:08:12 +00003383 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003384 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3385
John McCall9f54ad42009-12-10 09:41:52 +00003386 // Check for invalid redeclarations.
3387 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3388 return 0;
3389
3390 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003391 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3392 return 0;
3393
John McCallaf8e6ed2009-11-12 03:15:40 +00003394 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003395 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003396 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003397 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003398 // FIXME: not all declaration name kinds are legal here
3399 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3400 UsingLoc, TypenameLoc,
3401 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003402 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003403 } else {
3404 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3405 UsingLoc, SS.getRange(), NNS,
3406 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003407 }
John McCalled976492009-12-04 22:46:56 +00003408 } else {
3409 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3410 SS.getRange(), UsingLoc, NNS, Name,
3411 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003412 }
John McCalled976492009-12-04 22:46:56 +00003413 D->setAccess(AS);
3414 CurContext->addDecl(D);
3415
3416 if (!LookupContext) return D;
3417 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall604e7f12009-12-08 07:46:18 +00003419 if (RequireCompleteDeclContext(SS)) {
3420 UD->setInvalidDecl();
3421 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003422 }
3423
John McCall604e7f12009-12-08 07:46:18 +00003424 // Look up the target name.
3425
John McCalla24dc2e2009-11-17 02:14:36 +00003426 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003427
John McCall604e7f12009-12-08 07:46:18 +00003428 // Unlike most lookups, we don't always want to hide tag
3429 // declarations: tag names are visible through the using declaration
3430 // even if hidden by ordinary names, *except* in a dependent context
3431 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003432 if (!IsInstantiation)
3433 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003434
John McCalla24dc2e2009-11-17 02:14:36 +00003435 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003436
John McCallf36e02d2009-10-09 21:13:30 +00003437 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003438 Diag(IdentLoc, diag::err_no_member)
3439 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003440 UD->setInvalidDecl();
3441 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003442 }
3443
John McCalled976492009-12-04 22:46:56 +00003444 if (R.isAmbiguous()) {
3445 UD->setInvalidDecl();
3446 return UD;
3447 }
Mike Stump1eb44332009-09-09 15:08:12 +00003448
John McCall7ba107a2009-11-18 02:36:19 +00003449 if (IsTypeName) {
3450 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003451 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003452 Diag(IdentLoc, diag::err_using_typename_non_type);
3453 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3454 Diag((*I)->getUnderlyingDecl()->getLocation(),
3455 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003456 UD->setInvalidDecl();
3457 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003458 }
3459 } else {
3460 // If we asked for a non-typename and we got a type, error out,
3461 // but only if this is an instantiation of an unresolved using
3462 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003463 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003464 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3465 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003466 UD->setInvalidDecl();
3467 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003468 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003469 }
3470
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003471 // C++0x N2914 [namespace.udecl]p6:
3472 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003473 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003474 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3475 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003476 UD->setInvalidDecl();
3477 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003478 }
Mike Stump1eb44332009-09-09 15:08:12 +00003479
John McCall9f54ad42009-12-10 09:41:52 +00003480 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3481 if (!CheckUsingShadowDecl(UD, *I, Previous))
3482 BuildUsingShadowDecl(S, UD, *I);
3483 }
John McCall9488ea12009-11-17 05:59:44 +00003484
3485 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003486}
3487
John McCall9f54ad42009-12-10 09:41:52 +00003488/// Checks that the given using declaration is not an invalid
3489/// redeclaration. Note that this is checking only for the using decl
3490/// itself, not for any ill-formedness among the UsingShadowDecls.
3491bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3492 bool isTypeName,
3493 const CXXScopeSpec &SS,
3494 SourceLocation NameLoc,
3495 const LookupResult &Prev) {
3496 // C++03 [namespace.udecl]p8:
3497 // C++0x [namespace.udecl]p10:
3498 // A using-declaration is a declaration and can therefore be used
3499 // repeatedly where (and only where) multiple declarations are
3500 // allowed.
3501 // That's only in file contexts.
3502 if (CurContext->getLookupContext()->isFileContext())
3503 return false;
3504
3505 NestedNameSpecifier *Qual
3506 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3507
3508 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3509 NamedDecl *D = *I;
3510
3511 bool DTypename;
3512 NestedNameSpecifier *DQual;
3513 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3514 DTypename = UD->isTypeName();
3515 DQual = UD->getTargetNestedNameDecl();
3516 } else if (UnresolvedUsingValueDecl *UD
3517 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3518 DTypename = false;
3519 DQual = UD->getTargetNestedNameSpecifier();
3520 } else if (UnresolvedUsingTypenameDecl *UD
3521 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3522 DTypename = true;
3523 DQual = UD->getTargetNestedNameSpecifier();
3524 } else continue;
3525
3526 // using decls differ if one says 'typename' and the other doesn't.
3527 // FIXME: non-dependent using decls?
3528 if (isTypeName != DTypename) continue;
3529
3530 // using decls differ if they name different scopes (but note that
3531 // template instantiation can cause this check to trigger when it
3532 // didn't before instantiation).
3533 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3534 Context.getCanonicalNestedNameSpecifier(DQual))
3535 continue;
3536
3537 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003538 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003539 return true;
3540 }
3541
3542 return false;
3543}
3544
John McCall604e7f12009-12-08 07:46:18 +00003545
John McCalled976492009-12-04 22:46:56 +00003546/// Checks that the given nested-name qualifier used in a using decl
3547/// in the current context is appropriately related to the current
3548/// scope. If an error is found, diagnoses it and returns true.
3549bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3550 const CXXScopeSpec &SS,
3551 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003552 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003553
John McCall604e7f12009-12-08 07:46:18 +00003554 if (!CurContext->isRecord()) {
3555 // C++03 [namespace.udecl]p3:
3556 // C++0x [namespace.udecl]p8:
3557 // A using-declaration for a class member shall be a member-declaration.
3558
3559 // If we weren't able to compute a valid scope, it must be a
3560 // dependent class scope.
3561 if (!NamedContext || NamedContext->isRecord()) {
3562 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3563 << SS.getRange();
3564 return true;
3565 }
3566
3567 // Otherwise, everything is known to be fine.
3568 return false;
3569 }
3570
3571 // The current scope is a record.
3572
3573 // If the named context is dependent, we can't decide much.
3574 if (!NamedContext) {
3575 // FIXME: in C++0x, we can diagnose if we can prove that the
3576 // nested-name-specifier does not refer to a base class, which is
3577 // still possible in some cases.
3578
3579 // Otherwise we have to conservatively report that things might be
3580 // okay.
3581 return false;
3582 }
3583
3584 if (!NamedContext->isRecord()) {
3585 // Ideally this would point at the last name in the specifier,
3586 // but we don't have that level of source info.
3587 Diag(SS.getRange().getBegin(),
3588 diag::err_using_decl_nested_name_specifier_is_not_class)
3589 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3590 return true;
3591 }
3592
3593 if (getLangOptions().CPlusPlus0x) {
3594 // C++0x [namespace.udecl]p3:
3595 // In a using-declaration used as a member-declaration, the
3596 // nested-name-specifier shall name a base class of the class
3597 // being defined.
3598
3599 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3600 cast<CXXRecordDecl>(NamedContext))) {
3601 if (CurContext == NamedContext) {
3602 Diag(NameLoc,
3603 diag::err_using_decl_nested_name_specifier_is_current_class)
3604 << SS.getRange();
3605 return true;
3606 }
3607
3608 Diag(SS.getRange().getBegin(),
3609 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3610 << (NestedNameSpecifier*) SS.getScopeRep()
3611 << cast<CXXRecordDecl>(CurContext)
3612 << SS.getRange();
3613 return true;
3614 }
3615
3616 return false;
3617 }
3618
3619 // C++03 [namespace.udecl]p4:
3620 // A using-declaration used as a member-declaration shall refer
3621 // to a member of a base class of the class being defined [etc.].
3622
3623 // Salient point: SS doesn't have to name a base class as long as
3624 // lookup only finds members from base classes. Therefore we can
3625 // diagnose here only if we can prove that that can't happen,
3626 // i.e. if the class hierarchies provably don't intersect.
3627
3628 // TODO: it would be nice if "definitely valid" results were cached
3629 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3630 // need to be repeated.
3631
3632 struct UserData {
3633 llvm::DenseSet<const CXXRecordDecl*> Bases;
3634
3635 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3636 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3637 Data->Bases.insert(Base);
3638 return true;
3639 }
3640
3641 bool hasDependentBases(const CXXRecordDecl *Class) {
3642 return !Class->forallBases(collect, this);
3643 }
3644
3645 /// Returns true if the base is dependent or is one of the
3646 /// accumulated base classes.
3647 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3648 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3649 return !Data->Bases.count(Base);
3650 }
3651
3652 bool mightShareBases(const CXXRecordDecl *Class) {
3653 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3654 }
3655 };
3656
3657 UserData Data;
3658
3659 // Returns false if we find a dependent base.
3660 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3661 return false;
3662
3663 // Returns false if the class has a dependent base or if it or one
3664 // of its bases is present in the base set of the current context.
3665 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3666 return false;
3667
3668 Diag(SS.getRange().getBegin(),
3669 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3670 << (NestedNameSpecifier*) SS.getScopeRep()
3671 << cast<CXXRecordDecl>(CurContext)
3672 << SS.getRange();
3673
3674 return true;
John McCalled976492009-12-04 22:46:56 +00003675}
3676
Mike Stump1eb44332009-09-09 15:08:12 +00003677Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003678 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003679 SourceLocation AliasLoc,
3680 IdentifierInfo *Alias,
3681 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003682 SourceLocation IdentLoc,
3683 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Anders Carlsson81c85c42009-03-28 23:53:49 +00003685 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003686 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3687 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003688
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003689 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003690 if (NamedDecl *PrevDecl
John McCall7d384dd2009-11-18 07:57:50 +00003691 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003692 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003693 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003694 // namespace, so don't create a new one.
John McCallf36e02d2009-10-09 21:13:30 +00003695 if (!R.isAmbiguous() && !R.empty() &&
3696 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003697 return DeclPtrTy();
3698 }
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003700 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3701 diag::err_redefinition_different_kind;
3702 Diag(AliasLoc, DiagID) << Alias;
3703 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003704 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003705 }
3706
John McCalla24dc2e2009-11-17 02:14:36 +00003707 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003708 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003709
John McCallf36e02d2009-10-09 21:13:30 +00003710 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003711 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003712 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003713 }
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003715 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003716 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3717 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00003718 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00003719 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003720
John McCall3dbd3d52010-02-16 06:53:13 +00003721 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00003722 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00003723}
3724
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003725void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3726 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00003727 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3728 !Constructor->isUsed()) &&
3729 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Eli Friedman80c30da2009-11-09 19:20:36 +00003731 CXXRecordDecl *ClassDecl
3732 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3733 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00003734
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003735 DeclContext *PreviousContext = CurContext;
3736 CurContext = Constructor;
3737 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00003738 Diag(CurrentLocation, diag::note_member_synthesized_at)
3739 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00003740 Constructor->setInvalidDecl();
3741 } else {
3742 Constructor->setUsed();
3743 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003744 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003745}
3746
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003747void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00003748 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003749 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3750 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00003751 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003752 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003753
3754 DeclContext *PreviousContext = CurContext;
3755 CurContext = Destructor;
3756
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003757 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00003758 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003759 // implicitly defined, all the implicitly-declared default destructors
3760 // for its base class and its non-static data members shall have been
3761 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003762 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3763 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003764 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003766 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003767 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003768 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3769 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3770 else
Mike Stump1eb44332009-09-09 15:08:12 +00003771 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003772 "DefineImplicitDestructor - missing dtor in a base class");
3773 }
3774 }
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3777 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003778 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3779 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3780 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003781 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003782 CXXRecordDecl *FieldClassDecl
3783 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3784 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003785 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003786 const_cast<CXXDestructorDecl*>(
3787 FieldClassDecl->getDestructor(Context)))
3788 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3789 else
Mike Stump1eb44332009-09-09 15:08:12 +00003790 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003791 "DefineImplicitDestructor - missing dtor in class of a data member");
3792 }
3793 }
3794 }
Anders Carlsson37909802009-11-30 21:24:50 +00003795
3796 // FIXME: If CheckDestructor fails, we should emit a note about where the
3797 // implicit destructor was needed.
3798 if (CheckDestructor(Destructor)) {
3799 Diag(CurrentLocation, diag::note_member_synthesized_at)
3800 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3801
3802 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003803 CurContext = PreviousContext;
3804
Anders Carlsson37909802009-11-30 21:24:50 +00003805 return;
3806 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003807 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00003808
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00003809 Destructor->setUsed();
3810}
3811
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003812void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3813 CXXMethodDecl *MethodDecl) {
3814 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3815 MethodDecl->getOverloadedOperator() == OO_Equal &&
3816 !MethodDecl->isUsed()) &&
3817 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003819 CXXRecordDecl *ClassDecl
3820 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003822 DeclContext *PreviousContext = CurContext;
3823 CurContext = MethodDecl;
3824
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00003825 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003826 // Before the implicitly-declared copy assignment operator for a class is
3827 // implicitly defined, all implicitly-declared copy assignment operators
3828 // for its direct base classes and its nonstatic data members shall have
3829 // been implicitly defined.
3830 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003831 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3832 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003833 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003834 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003835 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003836 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3837 BaseClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003838 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3839 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00003840 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3841 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003842 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3843 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3844 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003845 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003846 CXXRecordDecl *FieldClassDecl
3847 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003848 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003849 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3850 FieldClassDecl))
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003851 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003852 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003853 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003854 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3855 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003856 Diag(CurrentLocation, diag::note_first_required_here);
3857 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003858 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003859 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00003860 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3861 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003862 Diag(CurrentLocation, diag::note_first_required_here);
3863 err = true;
3864 }
3865 }
3866 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00003867 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003868
3869 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003870}
3871
3872CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003873Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3874 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003875 CXXRecordDecl *ClassDecl) {
3876 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3877 QualType RHSType(LHSType);
3878 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00003879 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003880 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00003881 RHSType = Context.getCVRQualifiedType(RHSType,
3882 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00003883 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003884 LHSType,
3885 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00003886 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003887 RHSType,
3888 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003889 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00003890 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00003891 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003892 CandidateSet);
3893 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00003894 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00003895 return cast<CXXMethodDecl>(Best->Function);
3896 assert(false &&
3897 "getAssignOperatorMethod - copy assignment operator method not found");
3898 return 0;
3899}
3900
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003901void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3902 CXXConstructorDecl *CopyConstructor,
3903 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00003904 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003905 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003906 !CopyConstructor->isUsed()) &&
3907 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003909 CXXRecordDecl *ClassDecl
3910 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3911 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003912
3913 DeclContext *PreviousContext = CurContext;
3914 CurContext = CopyConstructor;
3915
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003916 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00003917 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003918 // implicitly defined, all the implicitly-declared copy constructors
3919 // for its base class and its non-static data members shall have been
3920 // implicitly defined.
3921 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3922 Base != ClassDecl->bases_end(); ++Base) {
3923 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003924 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003925 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003926 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003927 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003928 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003929 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3930 FieldEnd = ClassDecl->field_end();
3931 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003932 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3933 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3934 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003935 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003936 CXXRecordDecl *FieldClassDecl
3937 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003938 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003939 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00003940 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003941 }
3942 }
3943 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003944
3945 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00003946}
3947
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003948Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003949Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00003950 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003951 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003952 bool RequiresZeroInit,
3953 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003954 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Douglas Gregor39da0b82009-09-09 23:08:42 +00003956 // C++ [class.copy]p15:
3957 // Whenever a temporary class object is copied using a copy constructor, and
3958 // this object and the copy have the same cv-unqualified type, an
3959 // implementation is permitted to treat the original and the copy as two
3960 // different ways of referring to the same object and not perform a copy at
3961 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003963 // FIXME: Is this enough?
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003964 if (Constructor->isCopyConstructor()) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003965 Expr *E = ((Expr **)ExprArgs.get())[0];
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003966 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3967 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3968 E = ICE->getSubExpr();
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003969 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3970 E = FCE->getSubExpr();
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003971 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3972 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00003973 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3974 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3975 E = ICE->getSubExpr();
Eli Friedman03368432009-12-06 09:26:33 +00003976
3977 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3978 Elidable = !CE->getCallReturnType()->isReferenceType();
3979 else if (isa<CXXTemporaryObjectExpr>(E))
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003980 Elidable = true;
Eli Friedmancb48f8a2009-12-24 23:33:34 +00003981 else if (isa<CXXConstructExpr>(E))
3982 Elidable = true;
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003983 }
Mike Stump1eb44332009-09-09 15:08:12 +00003984
3985 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003986 Elidable, move(ExprArgs), RequiresZeroInit,
3987 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00003988}
3989
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00003990/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3991/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00003992Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00003993Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3994 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00003995 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003996 bool RequiresZeroInit,
3997 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00003998 unsigned NumExprs = ExprArgs.size();
3999 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Douglas Gregor7edfb692009-11-23 12:27:39 +00004001 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004002 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004003 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004004 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004005}
4006
Mike Stump1eb44332009-09-09 15:08:12 +00004007bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004008 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004009 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004010 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004011 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004012 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004013 if (TempResult.isInvalid())
4014 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004016 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004017 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004018 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004019 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Anders Carlssonfe2de492009-08-25 05:18:00 +00004021 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004022}
4023
John McCall68c6c9a2010-02-02 09:10:11 +00004024void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4025 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
John McCall4f9506a2010-02-02 08:45:54 +00004026 if (!ClassDecl->hasTrivialDestructor()) {
4027 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4028 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall68c6c9a2010-02-02 09:10:11 +00004029 CheckDestructorAccess(VD->getLocation(), Record);
John McCall4f9506a2010-02-02 08:45:54 +00004030 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004031}
4032
Mike Stump1eb44332009-09-09 15:08:12 +00004033/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004034/// ActOnDeclarator, when a C++ direct initializer is present.
4035/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004036void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4037 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004038 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004039 SourceLocation *CommaLocs,
4040 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004041 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004042 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004043
4044 // If there is no declaration, there was an error parsing it. Just ignore
4045 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004046 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004047 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004049 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4050 if (!VDecl) {
4051 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4052 RealDecl->setInvalidDecl();
4053 return;
4054 }
4055
Douglas Gregor83ddad32009-08-26 21:14:46 +00004056 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004057 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004058 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4059 //
4060 // Clients that want to distinguish between the two forms, can check for
4061 // direct initializer using VarDecl::hasCXXDirectInitializer().
4062 // A major benefit is that clients that don't particularly care about which
4063 // exactly form was it (like the CodeGen) can handle both cases without
4064 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004065
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004066 // C++ 8.5p11:
4067 // The form of initialization (using parentheses or '=') is generally
4068 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004069 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004070 QualType DeclInitType = VDecl->getType();
4071 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004072 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004073
Douglas Gregor4dffad62010-02-11 22:55:30 +00004074 if (!VDecl->getType()->isDependentType() &&
4075 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004076 diag::err_typecheck_decl_incomplete_type)) {
4077 VDecl->setInvalidDecl();
4078 return;
4079 }
4080
Douglas Gregor90f93822009-12-22 22:17:25 +00004081 // The variable can not have an abstract class type.
4082 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4083 diag::err_abstract_type_in_decl,
4084 AbstractVariableType))
4085 VDecl->setInvalidDecl();
4086
Sebastian Redl31310a22010-02-01 20:16:42 +00004087 const VarDecl *Def;
4088 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004089 Diag(VDecl->getLocation(), diag::err_redefinition)
4090 << VDecl->getDeclName();
4091 Diag(Def->getLocation(), diag::note_previous_definition);
4092 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004093 return;
4094 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004095
4096 // If either the declaration has a dependent type or if any of the
4097 // expressions is type-dependent, we represent the initialization
4098 // via a ParenListExpr for later use during template instantiation.
4099 if (VDecl->getType()->isDependentType() ||
4100 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4101 // Let clients know that initialization was done with a direct initializer.
4102 VDecl->setCXXDirectInitializer(true);
4103
4104 // Store the initialization expressions as a ParenListExpr.
4105 unsigned NumExprs = Exprs.size();
4106 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4107 (Expr **)Exprs.release(),
4108 NumExprs, RParenLoc));
4109 return;
4110 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004111
4112 // Capture the variable that is being initialized and the style of
4113 // initialization.
4114 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4115
4116 // FIXME: Poor source location information.
4117 InitializationKind Kind
4118 = InitializationKind::CreateDirect(VDecl->getLocation(),
4119 LParenLoc, RParenLoc);
4120
4121 InitializationSequence InitSeq(*this, Entity, Kind,
4122 (Expr**)Exprs.get(), Exprs.size());
4123 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4124 if (Result.isInvalid()) {
4125 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004126 return;
4127 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004128
4129 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004130 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004131 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004132
John McCall68c6c9a2010-02-02 09:10:11 +00004133 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4134 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004135}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004136
Douglas Gregor19aeac62009-11-14 03:27:21 +00004137/// \brief Add the applicable constructor candidates for an initialization
4138/// by constructor.
4139static void AddConstructorInitializationCandidates(Sema &SemaRef,
4140 QualType ClassType,
4141 Expr **Args,
4142 unsigned NumArgs,
Douglas Gregor20093b42009-12-09 23:02:17 +00004143 InitializationKind Kind,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004144 OverloadCandidateSet &CandidateSet) {
4145 // C++ [dcl.init]p14:
4146 // If the initialization is direct-initialization, or if it is
4147 // copy-initialization where the cv-unqualified version of the
4148 // source type is the same class as, or a derived class of, the
4149 // class of the destination, constructors are considered. The
4150 // applicable constructors are enumerated (13.3.1.3), and the
4151 // best one is chosen through overload resolution (13.3). The
4152 // constructor so selected is called to initialize the object,
4153 // with the initializer expression(s) as its argument(s). If no
4154 // constructor applies, or the overload resolution is ambiguous,
4155 // the initialization is ill-formed.
4156 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4157 assert(ClassRec && "Can only initialize a class type here");
4158
4159 // FIXME: When we decide not to synthesize the implicitly-declared
4160 // constructors, we'll need to make them appear here.
4161
4162 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4163 DeclarationName ConstructorName
4164 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4165 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4166 DeclContext::lookup_const_iterator Con, ConEnd;
4167 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4168 Con != ConEnd; ++Con) {
4169 // Find the constructor (which may be a template).
4170 CXXConstructorDecl *Constructor = 0;
4171 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4172 if (ConstructorTmpl)
4173 Constructor
4174 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4175 else
4176 Constructor = cast<CXXConstructorDecl>(*Con);
4177
Douglas Gregor20093b42009-12-09 23:02:17 +00004178 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4179 (Kind.getKind() == InitializationKind::IK_Value) ||
4180 (Kind.getKind() == InitializationKind::IK_Copy &&
Douglas Gregor19aeac62009-11-14 03:27:21 +00004181 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004182 ((Kind.getKind() == InitializationKind::IK_Default) &&
4183 Constructor->isDefaultConstructor())) {
Douglas Gregor19aeac62009-11-14 03:27:21 +00004184 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00004185 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
John McCall86820f52010-01-26 01:37:31 +00004186 ConstructorTmpl->getAccess(),
John McCalld5532b62009-11-23 01:53:49 +00004187 /*ExplicitArgs*/ 0,
Douglas Gregor19aeac62009-11-14 03:27:21 +00004188 Args, NumArgs, CandidateSet);
4189 else
John McCall86820f52010-01-26 01:37:31 +00004190 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4191 Args, NumArgs, CandidateSet);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004192 }
4193 }
4194}
4195
4196/// \brief Attempt to perform initialization by constructor
4197/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4198/// copy-initialization.
4199///
4200/// This routine determines whether initialization by constructor is possible,
4201/// but it does not emit any diagnostics in the case where the initialization
4202/// is ill-formed.
4203///
4204/// \param ClassType the type of the object being initialized, which must have
4205/// class type.
4206///
4207/// \param Args the arguments provided to initialize the object
4208///
4209/// \param NumArgs the number of arguments provided to initialize the object
4210///
4211/// \param Kind the type of initialization being performed
4212///
4213/// \returns the constructor used to initialize the object, if successful.
4214/// Otherwise, emits a diagnostic and returns NULL.
4215CXXConstructorDecl *
4216Sema::TryInitializationByConstructor(QualType ClassType,
4217 Expr **Args, unsigned NumArgs,
4218 SourceLocation Loc,
4219 InitializationKind Kind) {
4220 // Build the overload candidate set
John McCall5769d612010-02-08 23:07:23 +00004221 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor19aeac62009-11-14 03:27:21 +00004222 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4223 CandidateSet);
4224
4225 // Determine whether we found a constructor we can use.
4226 OverloadCandidateSet::iterator Best;
4227 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4228 case OR_Success:
4229 case OR_Deleted:
4230 // We found a constructor. Return it.
4231 return cast<CXXConstructorDecl>(Best->Function);
4232
4233 case OR_No_Viable_Function:
4234 case OR_Ambiguous:
4235 // Overload resolution failed. Return nothing.
4236 return 0;
4237 }
4238
4239 // Silence GCC warning
4240 return 0;
4241}
4242
Douglas Gregor39da0b82009-09-09 23:08:42 +00004243/// \brief Given a constructor and the set of arguments provided for the
4244/// constructor, convert the arguments and add any required default arguments
4245/// to form a proper call to this constructor.
4246///
4247/// \returns true if an error occurred, false otherwise.
4248bool
4249Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4250 MultiExprArg ArgsPtr,
4251 SourceLocation Loc,
4252 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4253 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4254 unsigned NumArgs = ArgsPtr.size();
4255 Expr **Args = (Expr **)ArgsPtr.get();
4256
4257 const FunctionProtoType *Proto
4258 = Constructor->getType()->getAs<FunctionProtoType>();
4259 assert(Proto && "Constructor without a prototype?");
4260 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004261
4262 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004263 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004264 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004265 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004266 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004267
4268 VariadicCallType CallType =
4269 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4270 llvm::SmallVector<Expr *, 8> AllArgs;
4271 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4272 Proto, 0, Args, NumArgs, AllArgs,
4273 CallType);
4274 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4275 ConvertedArgs.push_back(AllArgs[i]);
4276 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004277}
4278
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004279/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4280/// determine whether they are reference-related,
4281/// reference-compatible, reference-compatible with added
4282/// qualification, or incompatible, for use in C++ initialization by
4283/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4284/// type, and the first type (T1) is the pointee type of the reference
4285/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00004286Sema::ReferenceCompareResult
Chandler Carruth28e318c2009-12-29 07:16:59 +00004287Sema::CompareReferenceRelationship(SourceLocation Loc,
Douglas Gregor393896f2009-11-05 13:06:35 +00004288 QualType OrigT1, QualType OrigT2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00004289 bool& DerivedToBase) {
Douglas Gregor393896f2009-11-05 13:06:35 +00004290 assert(!OrigT1->isReferenceType() &&
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004291 "T1 must be the pointee type of the reference type");
Douglas Gregor393896f2009-11-05 13:06:35 +00004292 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004293
Douglas Gregor393896f2009-11-05 13:06:35 +00004294 QualType T1 = Context.getCanonicalType(OrigT1);
4295 QualType T2 = Context.getCanonicalType(OrigT2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00004296 Qualifiers T1Quals, T2Quals;
4297 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4298 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004299
4300 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004301 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00004302 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004303 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004304 if (UnqualT1 == UnqualT2)
4305 DerivedToBase = false;
Douglas Gregor393896f2009-11-05 13:06:35 +00004306 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4307 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4308 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor15da57e2008-10-29 02:00:59 +00004309 DerivedToBase = true;
4310 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004311 return Ref_Incompatible;
4312
4313 // At this point, we know that T1 and T2 are reference-related (at
4314 // least).
4315
Chandler Carruth28e318c2009-12-29 07:16:59 +00004316 // If the type is an array type, promote the element qualifiers to the type
4317 // for comparison.
4318 if (isa<ArrayType>(T1) && T1Quals)
4319 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4320 if (isa<ArrayType>(T2) && T2Quals)
4321 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4322
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004323 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00004324 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004325 // reference-related to T2 and cv1 is the same cv-qualification
4326 // as, or greater cv-qualification than, cv2. For purposes of
4327 // overload resolution, cases for which cv1 is greater
4328 // cv-qualification than cv2 are identified as
4329 // reference-compatible with added qualification (see 13.3.3.2).
Chandler Carruth28e318c2009-12-29 07:16:59 +00004330 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004331 return Ref_Compatible;
4332 else if (T1.isMoreQualifiedThan(T2))
4333 return Ref_Compatible_With_Added_Qualification;
4334 else
4335 return Ref_Related;
4336}
4337
4338/// CheckReferenceInit - Check the initialization of a reference
4339/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4340/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00004341/// list), and DeclType is the type of the declaration. When ICS is
4342/// non-null, this routine will compute the implicit conversion
4343/// sequence according to C++ [over.ics.ref] and will not produce any
4344/// diagnostics; when ICS is null, it will emit diagnostics when any
4345/// errors are found. Either way, a return value of true indicates
4346/// that there was a failure, a return value of false indicates that
4347/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00004348///
4349/// When @p SuppressUserConversions, user-defined conversions are
4350/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004351/// When @p AllowExplicit, we also permit explicit user-defined
4352/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00004353/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004354/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4355/// This is used when this is called from a C-style cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004356bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004357Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +00004358 SourceLocation DeclLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004359 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00004360 bool AllowExplicit, bool ForceRValue,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004361 ImplicitConversionSequence *ICS,
4362 bool IgnoreBaseAccess) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004363 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4364
Ted Kremenek6217b802009-07-29 21:53:49 +00004365 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004366 QualType T2 = Init->getType();
4367
Douglas Gregor904eed32008-11-10 20:40:00 +00004368 // If the initializer is the address of an overloaded function, try
4369 // to resolve the overloaded function. If all goes well, T2 is the
4370 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00004371 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00004372 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004373 ICS != 0);
4374 if (Fn) {
4375 // Since we're performing this reference-initialization for
4376 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004377 if (!ICS) {
Douglas Gregor739d8282009-09-23 23:04:10 +00004378 if (DiagnoseUseOfDecl(Fn, DeclLoc))
Douglas Gregor20093b42009-12-09 23:02:17 +00004379 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004380
Anders Carlsson96ad5332009-10-21 17:16:23 +00004381 Init = FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004382 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004383
4384 T2 = Fn->getType();
4385 }
4386 }
4387
Douglas Gregor15da57e2008-10-29 02:00:59 +00004388 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004389 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004390 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00004391 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4392 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00004393 ReferenceCompareResult RefRelationship
Douglas Gregor393896f2009-11-05 13:06:35 +00004394 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004395
4396 // Most paths end in a failed conversion.
John McCalladbb8f82010-01-13 09:16:55 +00004397 if (ICS) {
4398 ICS->setBad();
4399 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4400 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004401
4402 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00004403 // A reference to type "cv1 T1" is initialized by an expression
4404 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004405
4406 // -- If the initializer expression
4407
Sebastian Redla9845802009-03-29 15:27:50 +00004408 // Rvalue references cannot bind to lvalues (N2812).
4409 // There is absolutely no situation where they can. In particular, note that
4410 // this is ill-formed, even if B has a user-defined conversion to A&&:
4411 // B b;
4412 // A&& r = b;
4413 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4414 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004415 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
Sebastian Redla9845802009-03-29 15:27:50 +00004416 << Init->getSourceRange();
4417 return true;
4418 }
4419
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004420 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00004421 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4422 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00004423 //
4424 // Note that the bit-field check is skipped if we are just computing
4425 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004426 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004427 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004428 BindsDirectly = true;
4429
Douglas Gregor15da57e2008-10-29 02:00:59 +00004430 if (ICS) {
4431 // C++ [over.ics.ref]p1:
4432 // When a parameter of reference type binds directly (8.5.3)
4433 // to an argument expression, the implicit conversion sequence
4434 // is the identity conversion, unless the argument expression
4435 // has a type that is a derived class of the parameter type,
4436 // in which case the implicit conversion sequence is a
4437 // derived-to-base Conversion (13.3.3.1).
John McCall1d318332010-01-12 00:44:57 +00004438 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004439 ICS->Standard.First = ICK_Identity;
4440 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4441 ICS->Standard.Third = ICK_Identity;
4442 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004443 ICS->Standard.setToType(0, T2);
4444 ICS->Standard.setToType(1, T1);
4445 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004446 ICS->Standard.ReferenceBinding = true;
4447 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004448 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00004449 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004450
4451 // Nothing more to do: the inaccessibility/ambiguity check for
4452 // derived-to-base conversions is suppressed when we're
4453 // computing the implicit conversion sequence (C++
4454 // [over.best.ics]p2).
4455 return false;
4456 } else {
4457 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00004458 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4459 if (DerivedToBase)
4460 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004461 else if(CheckExceptionSpecCompatibility(Init, T1))
4462 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004463 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004464 }
4465 }
4466
4467 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00004468 // implicitly converted to an lvalue of type "cv3 T3,"
4469 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004470 // 92) (this conversion is selected by enumerating the
4471 // applicable conversion functions (13.3.1.6) and choosing
4472 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00004473 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
Douglas Gregor573d9c32009-10-21 23:19:44 +00004474 !RequireCompleteType(DeclLoc, T2, 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004475 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004476 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004477
John McCall5769d612010-02-08 23:07:23 +00004478 OverloadCandidateSet CandidateSet(DeclLoc);
John McCalleec51cf2010-01-20 00:46:10 +00004479 const UnresolvedSetImpl *Conversions
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004480 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004481 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004482 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00004483 NamedDecl *D = *I;
4484 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4485 if (isa<UsingShadowDecl>(D))
4486 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4487
Mike Stump1eb44332009-09-09 15:08:12 +00004488 FunctionTemplateDecl *ConvTemplate
John McCall701c89e2009-12-03 04:06:58 +00004489 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004490 CXXConversionDecl *Conv;
4491 if (ConvTemplate)
4492 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4493 else
John McCall701c89e2009-12-03 04:06:58 +00004494 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004495
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004496 // If the conversion function doesn't return a reference type,
4497 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004498 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004499 (AllowExplicit || !Conv->isExplicit())) {
4500 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00004501 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
John McCall701c89e2009-12-03 04:06:58 +00004502 Init, DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004503 else
John McCall86820f52010-01-26 01:37:31 +00004504 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4505 DeclType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004506 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004507 }
4508
4509 OverloadCandidateSet::iterator Best;
Douglas Gregor739d8282009-09-23 23:04:10 +00004510 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004511 case OR_Success:
4512 // This is a direct binding.
4513 BindsDirectly = true;
4514
4515 if (ICS) {
4516 // C++ [over.ics.ref]p1:
4517 //
4518 // [...] If the parameter binds directly to the result of
4519 // applying a conversion function to the argument
4520 // expression, the implicit conversion sequence is a
4521 // user-defined conversion sequence (13.3.3.1.2), with the
4522 // second standard conversion sequence either an identity
4523 // conversion or, if the conversion function returns an
4524 // entity of a type that is a derived class of the parameter
4525 // type, a derived-to-base Conversion.
John McCall1d318332010-01-12 00:44:57 +00004526 ICS->setUserDefined();
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004527 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4528 ICS->UserDefined.After = Best->FinalConversion;
4529 ICS->UserDefined.ConversionFunction = Best->Function;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004530 ICS->UserDefined.EllipsisConversion = false;
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004531 assert(ICS->UserDefined.After.ReferenceBinding &&
4532 ICS->UserDefined.After.DirectBinding &&
4533 "Expected a direct reference binding!");
4534 return false;
4535 } else {
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004536 OwningExprResult InitConversion =
Douglas Gregor739d8282009-09-23 23:04:10 +00004537 BuildCXXCastArgument(DeclLoc, QualType(),
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004538 CastExpr::CK_UserDefinedConversion,
4539 cast<CXXMethodDecl>(Best->Function),
4540 Owned(Init));
4541 Init = InitConversion.takeAs<Expr>();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004542
4543 if (CheckExceptionSpecCompatibility(Init, T1))
4544 return true;
Fariborz Jahanian8f489d62009-09-23 22:34:00 +00004545 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4546 /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004547 }
4548 break;
4549
4550 case OR_Ambiguous:
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004551 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004552 ICS->setAmbiguous();
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004553 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4554 Cand != CandidateSet.end(); ++Cand)
4555 if (Cand->Viable)
John McCall1d318332010-01-12 00:44:57 +00004556 ICS->Ambiguous.addConversion(Cand->Function);
Fariborz Jahaniand9290cb2009-10-14 00:52:43 +00004557 break;
4558 }
4559 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4560 << Init->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00004561 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004562 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004563
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004564 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004565 case OR_Deleted:
4566 // There was no suitable conversion, or we found a deleted
4567 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00004568 break;
4569 }
4570 }
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004572 if (BindsDirectly) {
4573 // C++ [dcl.init.ref]p4:
4574 // [...] In all cases where the reference-related or
4575 // reference-compatible relationship of two types is used to
4576 // establish the validity of a reference binding, and T1 is a
4577 // base class of T2, a program that necessitates such a binding
4578 // is ill-formed if T1 is an inaccessible (clause 11) or
4579 // ambiguous (10.2) base class of T2.
4580 //
4581 // Note that we only check this condition when we're allowed to
4582 // complain about errors, because we should not be checking for
4583 // ambiguity (or inaccessibility) unless the reference binding
4584 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00004585 if (DerivedToBase)
Douglas Gregor739d8282009-09-23 23:04:10 +00004586 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00004587 Init->getSourceRange(),
4588 IgnoreBaseAccess);
Douglas Gregor15da57e2008-10-29 02:00:59 +00004589 else
4590 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004591 }
4592
4593 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00004594 // type (i.e., cv1 shall be const), or the reference shall be an
4595 // rvalue reference and the initializer expression shall be an rvalue.
John McCall0953e762009-09-24 19:53:00 +00004596 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00004597 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004598 Diag(DeclLoc, diag::err_not_reference_to_const_init)
Douglas Gregoref06e242010-01-29 19:39:15 +00004599 << T1.isVolatileQualified()
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004600 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004601 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004602 return true;
4603 }
4604
4605 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00004606 // class type, and "cv1 T1" is reference-compatible with
4607 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004608 // following ways (the choice is implementation-defined):
4609 //
4610 // -- The reference is bound to the object represented by
4611 // the rvalue (see 3.10) or to a sub-object within that
4612 // object.
4613 //
Eli Friedman33a31382009-08-05 19:21:58 +00004614 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004615 // a constructor is called to copy the entire rvalue
4616 // object into the temporary. The reference is bound to
4617 // the temporary or to a sub-object within the
4618 // temporary.
4619 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004620 // The constructor that would be used to make the copy
4621 // shall be callable whether or not the copy is actually
4622 // done.
4623 //
Sebastian Redla9845802009-03-29 15:27:50 +00004624 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004625 // freedom, so we will always take the first option and never build
4626 // a temporary in this case. FIXME: We will, however, have to check
4627 // for the presence of a copy constructor in C++98/03 mode.
4628 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00004629 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4630 if (ICS) {
John McCall1d318332010-01-12 00:44:57 +00004631 ICS->setStandard();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004632 ICS->Standard.First = ICK_Identity;
4633 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4634 ICS->Standard.Third = ICK_Identity;
4635 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
Douglas Gregorad323a82010-01-27 03:51:04 +00004636 ICS->Standard.setToType(0, T2);
4637 ICS->Standard.setToType(1, T1);
4638 ICS->Standard.setToType(2, T1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00004639 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00004640 ICS->Standard.DirectBinding = false;
4641 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00004642 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004643 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00004644 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4645 if (DerivedToBase)
4646 CK = CastExpr::CK_DerivedToBase;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00004647 else if(CheckExceptionSpecCompatibility(Init, T1))
4648 return true;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004649 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004650 }
4651 return false;
4652 }
4653
Eli Friedman33a31382009-08-05 19:21:58 +00004654 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004655 // initialized from the initializer expression using the
4656 // rules for a non-reference copy initialization (8.5). The
4657 // reference is then bound to the temporary. If T1 is
4658 // reference-related to T2, cv1 must be the same
4659 // cv-qualification as, or greater cv-qualification than,
4660 // cv2; otherwise, the program is ill-formed.
4661 if (RefRelationship == Ref_Related) {
4662 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4663 // we would be reference-compatible or reference-compatible with
4664 // added qualification. But that wasn't the case, so the reference
4665 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004666 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004667 Diag(DeclLoc, diag::err_reference_init_drops_quals)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00004668 << T1 << int(InitLvalue != Expr::LV_Valid)
Chris Lattnerd1625842008-11-24 06:25:27 +00004669 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004670 return true;
4671 }
4672
Douglas Gregor734d9862009-01-30 23:27:23 +00004673 // If at least one of the types is a class type, the types are not
4674 // related, and we aren't allowed any user conversions, the
4675 // reference binding fails. This case is important for breaking
4676 // recursion, since TryImplicitConversion below will attempt to
4677 // create a temporary through the use of a copy constructor.
4678 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4679 (T1->isRecordType() || T2->isRecordType())) {
4680 if (!ICS)
Douglas Gregor739d8282009-09-23 23:04:10 +00004681 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00004682 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
Douglas Gregor734d9862009-01-30 23:27:23 +00004683 return true;
4684 }
4685
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004686 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00004687 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00004688 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004689 //
Sebastian Redla9845802009-03-29 15:27:50 +00004690 // When a parameter of reference type is not bound directly to
4691 // an argument expression, the conversion sequence is the one
4692 // required to convert the argument expression to the
4693 // underlying type of the reference according to
4694 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4695 // to copy-initializing a temporary of the underlying type with
4696 // the argument expression. Any difference in top-level
4697 // cv-qualification is subsumed by the initialization itself
4698 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004699 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4700 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00004701 /*ForceRValue=*/false,
4702 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Sebastian Redla9845802009-03-29 15:27:50 +00004704 // Of course, that's still a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004705 if (ICS->isStandard()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004706 ICS->Standard.ReferenceBinding = true;
4707 ICS->Standard.RRefBinding = isRValRef;
John McCall1d318332010-01-12 00:44:57 +00004708 } else if (ICS->isUserDefined()) {
Sebastian Redla9845802009-03-29 15:27:50 +00004709 ICS->UserDefined.After.ReferenceBinding = true;
4710 ICS->UserDefined.After.RRefBinding = isRValRef;
4711 }
John McCall1d318332010-01-12 00:44:57 +00004712 return ICS->isBad();
Douglas Gregor15da57e2008-10-29 02:00:59 +00004713 } else {
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004714 ImplicitConversionSequence Conversions;
Douglas Gregor68647482009-12-16 03:45:30 +00004715 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004716 false, false,
4717 Conversions);
4718 if (badConversion) {
John McCall1d318332010-01-12 00:44:57 +00004719 if (Conversions.isAmbiguous()) {
Fariborz Jahanian7ad2d562009-09-24 00:42:43 +00004720 Diag(DeclLoc,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004721 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
John McCall1d318332010-01-12 00:44:57 +00004722 for (int j = Conversions.Ambiguous.conversions().size()-1;
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004723 j >= 0; j--) {
John McCall1d318332010-01-12 00:44:57 +00004724 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
John McCallb1622a12010-01-06 09:43:14 +00004725 NoteOverloadCandidate(Func);
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004726 }
4727 }
Fariborz Jahanian893f9552009-09-30 21:23:30 +00004728 else {
4729 if (isRValRef)
4730 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4731 << Init->getSourceRange();
4732 else
4733 Diag(DeclLoc, diag::err_invalid_initialization)
4734 << DeclType << Init->getType() << Init->getSourceRange();
4735 }
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00004736 }
4737 return badConversion;
Douglas Gregor15da57e2008-10-29 02:00:59 +00004738 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004739}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004740
Anders Carlsson20d45d22009-12-12 00:32:00 +00004741static inline bool
4742CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4743 const FunctionDecl *FnDecl) {
4744 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4745 if (isa<NamespaceDecl>(DC)) {
4746 return SemaRef.Diag(FnDecl->getLocation(),
4747 diag::err_operator_new_delete_declared_in_namespace)
4748 << FnDecl->getDeclName();
4749 }
4750
4751 if (isa<TranslationUnitDecl>(DC) &&
4752 FnDecl->getStorageClass() == FunctionDecl::Static) {
4753 return SemaRef.Diag(FnDecl->getLocation(),
4754 diag::err_operator_new_delete_declared_static)
4755 << FnDecl->getDeclName();
4756 }
4757
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004758 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004759}
4760
Anders Carlsson156c78e2009-12-13 17:53:43 +00004761static inline bool
4762CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4763 CanQualType ExpectedResultType,
4764 CanQualType ExpectedFirstParamType,
4765 unsigned DependentParamTypeDiag,
4766 unsigned InvalidParamTypeDiag) {
4767 QualType ResultType =
4768 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4769
4770 // Check that the result type is not dependent.
4771 if (ResultType->isDependentType())
4772 return SemaRef.Diag(FnDecl->getLocation(),
4773 diag::err_operator_new_delete_dependent_result_type)
4774 << FnDecl->getDeclName() << ExpectedResultType;
4775
4776 // Check that the result type is what we expect.
4777 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4778 return SemaRef.Diag(FnDecl->getLocation(),
4779 diag::err_operator_new_delete_invalid_result_type)
4780 << FnDecl->getDeclName() << ExpectedResultType;
4781
4782 // A function template must have at least 2 parameters.
4783 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4784 return SemaRef.Diag(FnDecl->getLocation(),
4785 diag::err_operator_new_delete_template_too_few_parameters)
4786 << FnDecl->getDeclName();
4787
4788 // The function decl must have at least 1 parameter.
4789 if (FnDecl->getNumParams() == 0)
4790 return SemaRef.Diag(FnDecl->getLocation(),
4791 diag::err_operator_new_delete_too_few_parameters)
4792 << FnDecl->getDeclName();
4793
4794 // Check the the first parameter type is not dependent.
4795 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4796 if (FirstParamType->isDependentType())
4797 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4798 << FnDecl->getDeclName() << ExpectedFirstParamType;
4799
4800 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004801 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004802 ExpectedFirstParamType)
4803 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4804 << FnDecl->getDeclName() << ExpectedFirstParamType;
4805
4806 return false;
4807}
4808
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004809static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004810CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004811 // C++ [basic.stc.dynamic.allocation]p1:
4812 // A program is ill-formed if an allocation function is declared in a
4813 // namespace scope other than global scope or declared static in global
4814 // scope.
4815 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4816 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004817
4818 CanQualType SizeTy =
4819 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4820
4821 // C++ [basic.stc.dynamic.allocation]p1:
4822 // The return type shall be void*. The first parameter shall have type
4823 // std::size_t.
4824 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4825 SizeTy,
4826 diag::err_operator_new_dependent_param_type,
4827 diag::err_operator_new_param_type))
4828 return true;
4829
4830 // C++ [basic.stc.dynamic.allocation]p1:
4831 // The first parameter shall not have an associated default argument.
4832 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004833 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004834 diag::err_operator_new_default_arg)
4835 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4836
4837 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004838}
4839
4840static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004841CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4842 // C++ [basic.stc.dynamic.deallocation]p1:
4843 // A program is ill-formed if deallocation functions are declared in a
4844 // namespace scope other than global scope or declared static in global
4845 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004846 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4847 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004848
4849 // C++ [basic.stc.dynamic.deallocation]p2:
4850 // Each deallocation function shall return void and its first parameter
4851 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004852 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4853 SemaRef.Context.VoidPtrTy,
4854 diag::err_operator_delete_dependent_param_type,
4855 diag::err_operator_delete_param_type))
4856 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004857
Anders Carlsson46991d62009-12-12 00:16:02 +00004858 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4859 if (FirstParamType->isDependentType())
4860 return SemaRef.Diag(FnDecl->getLocation(),
4861 diag::err_operator_delete_dependent_param_type)
4862 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4863
4864 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4865 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004866 return SemaRef.Diag(FnDecl->getLocation(),
4867 diag::err_operator_delete_param_type)
4868 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004869
4870 return false;
4871}
4872
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004873/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4874/// of this overloaded operator is well-formed. If so, returns false;
4875/// otherwise, emits appropriate diagnostics and returns true.
4876bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004877 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004878 "Expected an overloaded operator declaration");
4879
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004880 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4881
Mike Stump1eb44332009-09-09 15:08:12 +00004882 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004883 // The allocation and deallocation functions, operator new,
4884 // operator new[], operator delete and operator delete[], are
4885 // described completely in 3.7.3. The attributes and restrictions
4886 // found in the rest of this subclause do not apply to them unless
4887 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004888 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004889 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004890
Anders Carlssona3ccda52009-12-12 00:26:23 +00004891 if (Op == OO_New || Op == OO_Array_New)
4892 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004893
4894 // C++ [over.oper]p6:
4895 // An operator function shall either be a non-static member
4896 // function or be a non-member function and have at least one
4897 // parameter whose type is a class, a reference to a class, an
4898 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004899 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4900 if (MethodDecl->isStatic())
4901 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004902 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004903 } else {
4904 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004905 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4906 ParamEnd = FnDecl->param_end();
4907 Param != ParamEnd; ++Param) {
4908 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004909 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4910 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004911 ClassOrEnumParam = true;
4912 break;
4913 }
4914 }
4915
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004916 if (!ClassOrEnumParam)
4917 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004918 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004919 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004920 }
4921
4922 // C++ [over.oper]p8:
4923 // An operator function cannot have default arguments (8.3.6),
4924 // except where explicitly stated below.
4925 //
Mike Stump1eb44332009-09-09 15:08:12 +00004926 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004927 // (C++ [over.call]p1).
4928 if (Op != OO_Call) {
4929 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4930 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004931 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004932 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004933 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004934 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004935 }
4936 }
4937
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004938 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4939 { false, false, false }
4940#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4941 , { Unary, Binary, MemberOnly }
4942#include "clang/Basic/OperatorKinds.def"
4943 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004944
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004945 bool CanBeUnaryOperator = OperatorUses[Op][0];
4946 bool CanBeBinaryOperator = OperatorUses[Op][1];
4947 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004948
4949 // C++ [over.oper]p8:
4950 // [...] Operator functions cannot have more or fewer parameters
4951 // than the number required for the corresponding operator, as
4952 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004953 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004954 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004955 if (Op != OO_Call &&
4956 ((NumParams == 1 && !CanBeUnaryOperator) ||
4957 (NumParams == 2 && !CanBeBinaryOperator) ||
4958 (NumParams < 1) || (NumParams > 2))) {
4959 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004960 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004961 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004962 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004963 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004964 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004965 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004966 assert(CanBeBinaryOperator &&
4967 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004968 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004969 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004970
Chris Lattner416e46f2008-11-21 07:57:12 +00004971 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004972 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004973 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004974
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004975 // Overloaded operators other than operator() cannot be variadic.
4976 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004977 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004978 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004979 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004980 }
4981
4982 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004983 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4984 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004985 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004986 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004987 }
4988
4989 // C++ [over.inc]p1:
4990 // The user-defined function called operator++ implements the
4991 // prefix and postfix ++ operator. If this function is a member
4992 // function with no parameters, or a non-member function with one
4993 // parameter of class or enumeration type, it defines the prefix
4994 // increment operator ++ for objects of that type. If the function
4995 // is a member function with one parameter (which shall be of type
4996 // int) or a non-member function with two parameters (the second
4997 // of which shall be of type int), it defines the postfix
4998 // increment operator ++ for objects of that type.
4999 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5000 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5001 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005002 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005003 ParamIsInt = BT->getKind() == BuiltinType::Int;
5004
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005005 if (!ParamIsInt)
5006 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005007 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005008 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005009 }
5010
Sebastian Redl64b45f72009-01-05 20:52:13 +00005011 // Notify the class if it got an assignment operator.
5012 if (Op == OO_Equal) {
5013 // Would have returned earlier otherwise.
5014 assert(isa<CXXMethodDecl>(FnDecl) &&
5015 "Overloaded = not member, but not filtered.");
5016 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5017 Method->getParent()->addedAssignmentOperator(Context, Method);
5018 }
5019
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005020 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005021}
Chris Lattner5a003a42008-12-17 07:09:26 +00005022
Sean Hunta6c058d2010-01-13 09:01:02 +00005023/// CheckLiteralOperatorDeclaration - Check whether the declaration
5024/// of this literal operator function is well-formed. If so, returns
5025/// false; otherwise, emits appropriate diagnostics and returns true.
5026bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5027 DeclContext *DC = FnDecl->getDeclContext();
5028 Decl::Kind Kind = DC->getDeclKind();
5029 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5030 Kind != Decl::LinkageSpec) {
5031 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5032 << FnDecl->getDeclName();
5033 return true;
5034 }
5035
5036 bool Valid = false;
5037
5038 // FIXME: Check for the one valid template signature
5039 // template <char...> type operator "" name();
5040
5041 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5042 // Check the first parameter
5043 QualType T = (*Param)->getType();
5044
5045 // unsigned long long int and long double are allowed, but only
5046 // alone.
5047 // We also allow any character type; their omission seems to be a bug
5048 // in n3000
5049 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5050 Context.hasSameType(T, Context.LongDoubleTy) ||
5051 Context.hasSameType(T, Context.CharTy) ||
5052 Context.hasSameType(T, Context.WCharTy) ||
5053 Context.hasSameType(T, Context.Char16Ty) ||
5054 Context.hasSameType(T, Context.Char32Ty)) {
5055 if (++Param == FnDecl->param_end())
5056 Valid = true;
5057 goto FinishedParams;
5058 }
5059
5060 // Otherwise it must be a pointer to const; let's strip those.
5061 const PointerType *PT = T->getAs<PointerType>();
5062 if (!PT)
5063 goto FinishedParams;
5064 T = PT->getPointeeType();
5065 if (!T.isConstQualified())
5066 goto FinishedParams;
5067 T = T.getUnqualifiedType();
5068
5069 // Move on to the second parameter;
5070 ++Param;
5071
5072 // If there is no second parameter, the first must be a const char *
5073 if (Param == FnDecl->param_end()) {
5074 if (Context.hasSameType(T, Context.CharTy))
5075 Valid = true;
5076 goto FinishedParams;
5077 }
5078
5079 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5080 // are allowed as the first parameter to a two-parameter function
5081 if (!(Context.hasSameType(T, Context.CharTy) ||
5082 Context.hasSameType(T, Context.WCharTy) ||
5083 Context.hasSameType(T, Context.Char16Ty) ||
5084 Context.hasSameType(T, Context.Char32Ty)))
5085 goto FinishedParams;
5086
5087 // The second and final parameter must be an std::size_t
5088 T = (*Param)->getType().getUnqualifiedType();
5089 if (Context.hasSameType(T, Context.getSizeType()) &&
5090 ++Param == FnDecl->param_end())
5091 Valid = true;
5092 }
5093
5094 // FIXME: This diagnostic is absolutely terrible.
5095FinishedParams:
5096 if (!Valid) {
5097 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5098 << FnDecl->getDeclName();
5099 return true;
5100 }
5101
5102 return false;
5103}
5104
Douglas Gregor074149e2009-01-05 19:45:36 +00005105/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5106/// linkage specification, including the language and (if present)
5107/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5108/// the location of the language string literal, which is provided
5109/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5110/// the '{' brace. Otherwise, this linkage specification does not
5111/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005112Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5113 SourceLocation ExternLoc,
5114 SourceLocation LangLoc,
5115 const char *Lang,
5116 unsigned StrSize,
5117 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005118 LinkageSpecDecl::LanguageIDs Language;
5119 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5120 Language = LinkageSpecDecl::lang_c;
5121 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5122 Language = LinkageSpecDecl::lang_cxx;
5123 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005124 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005125 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005126 }
Mike Stump1eb44332009-09-09 15:08:12 +00005127
Chris Lattnercc98eac2008-12-17 07:13:27 +00005128 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005129
Douglas Gregor074149e2009-01-05 19:45:36 +00005130 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005131 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005132 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005133 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005134 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005135 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005136}
5137
Douglas Gregor074149e2009-01-05 19:45:36 +00005138/// ActOnFinishLinkageSpecification - Completely the definition of
5139/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5140/// valid, it's the position of the closing '}' brace in a linkage
5141/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005142Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5143 DeclPtrTy LinkageSpec,
5144 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005145 if (LinkageSpec)
5146 PopDeclContext();
5147 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005148}
5149
Douglas Gregord308e622009-05-18 20:51:54 +00005150/// \brief Perform semantic analysis for the variable declaration that
5151/// occurs within a C++ catch clause, returning the newly-created
5152/// variable.
5153VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005154 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005155 IdentifierInfo *Name,
5156 SourceLocation Loc,
5157 SourceRange Range) {
5158 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005159
5160 // Arrays and functions decay.
5161 if (ExDeclType->isArrayType())
5162 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5163 else if (ExDeclType->isFunctionType())
5164 ExDeclType = Context.getPointerType(ExDeclType);
5165
5166 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5167 // The exception-declaration shall not denote a pointer or reference to an
5168 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005169 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005170 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005171 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005172 Invalid = true;
5173 }
Douglas Gregord308e622009-05-18 20:51:54 +00005174
Sebastian Redl4b07b292008-12-22 19:15:10 +00005175 QualType BaseType = ExDeclType;
5176 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005177 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00005178 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005179 BaseType = Ptr->getPointeeType();
5180 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005181 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00005182 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005183 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005184 BaseType = Ref->getPointeeType();
5185 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005186 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005187 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005188 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00005189 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00005190 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005191
Mike Stump1eb44332009-09-09 15:08:12 +00005192 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005193 RequireNonAbstractType(Loc, ExDeclType,
5194 diag::err_abstract_type_in_decl,
5195 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005196 Invalid = true;
5197
Douglas Gregord308e622009-05-18 20:51:54 +00005198 // FIXME: Need to test for ability to copy-construct and destroy the
5199 // exception variable.
5200
Sebastian Redl8351da02008-12-22 21:35:02 +00005201 // FIXME: Need to check for abstract classes.
5202
Mike Stump1eb44332009-09-09 15:08:12 +00005203 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalla93c9342009-12-07 02:54:59 +00005204 Name, ExDeclType, TInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005205
5206 if (Invalid)
5207 ExDecl->setInvalidDecl();
5208
5209 return ExDecl;
5210}
5211
5212/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5213/// handler.
5214Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005215 TypeSourceInfo *TInfo = 0;
5216 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005217
5218 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005219 IdentifierInfo *II = D.getIdentifier();
John McCallf36e02d2009-10-09 21:13:30 +00005220 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005221 // The scope should be freshly made just for us. There is just no way
5222 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005223 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005224 if (PrevDecl->isTemplateParameter()) {
5225 // Maybe we will complain about the shadowed template parameter.
5226 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005227 }
5228 }
5229
Chris Lattnereaaebc72009-04-25 08:06:05 +00005230 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005231 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5232 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005233 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005234 }
5235
John McCalla93c9342009-12-07 02:54:59 +00005236 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005237 D.getIdentifier(),
5238 D.getIdentifierLoc(),
5239 D.getDeclSpec().getSourceRange());
5240
Chris Lattnereaaebc72009-04-25 08:06:05 +00005241 if (Invalid)
5242 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Sebastian Redl4b07b292008-12-22 19:15:10 +00005244 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005245 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005246 PushOnScopeChains(ExDecl, S);
5247 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005248 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005249
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005250 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005251 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005252}
Anders Carlssonfb311762009-03-14 00:25:26 +00005253
Mike Stump1eb44332009-09-09 15:08:12 +00005254Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005255 ExprArg assertexpr,
5256 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005257 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005258 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005259 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5260
Anders Carlssonc3082412009-03-14 00:33:21 +00005261 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5262 llvm::APSInt Value(32);
5263 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5264 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5265 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005266 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005267 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005268
Anders Carlssonc3082412009-03-14 00:33:21 +00005269 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005270 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005271 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005272 }
5273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Anders Carlsson77d81422009-03-15 17:35:16 +00005275 assertexpr.release();
5276 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005278 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005279
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005280 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005281 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005282}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005283
John McCalldd4a3b02009-09-16 22:47:08 +00005284/// Handle a friend type declaration. This works in tandem with
5285/// ActOnTag.
5286///
5287/// Notes on friend class templates:
5288///
5289/// We generally treat friend class declarations as if they were
5290/// declaring a class. So, for example, the elaborated type specifier
5291/// in a friend declaration is required to obey the restrictions of a
5292/// class-head (i.e. no typedefs in the scope chain), template
5293/// parameters are required to match up with simple template-ids, &c.
5294/// However, unlike when declaring a template specialization, it's
5295/// okay to refer to a template specialization without an empty
5296/// template parameter declaration, e.g.
5297/// friend class A<T>::B<unsigned>;
5298/// We permit this as a special case; if there are any template
5299/// parameters present at all, require proper matching, i.e.
5300/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005301Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005302 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005303 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005304
5305 assert(DS.isFriendSpecified());
5306 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5307
John McCalldd4a3b02009-09-16 22:47:08 +00005308 // Try to convert the decl specifier to a type. This works for
5309 // friend templates because ActOnTag never produces a ClassTemplateDecl
5310 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005311 Declarator TheDeclarator(DS, Declarator::MemberContext);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005312 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5313 if (TheDeclarator.isInvalidType())
5314 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005315
John McCalldd4a3b02009-09-16 22:47:08 +00005316 // This is definitely an error in C++98. It's probably meant to
5317 // be forbidden in C++0x, too, but the specification is just
5318 // poorly written.
5319 //
5320 // The problem is with declarations like the following:
5321 // template <T> friend A<T>::foo;
5322 // where deciding whether a class C is a friend or not now hinges
5323 // on whether there exists an instantiation of A that causes
5324 // 'foo' to equal C. There are restrictions on class-heads
5325 // (which we declare (by fiat) elaborated friend declarations to
5326 // be) that makes this tractable.
5327 //
5328 // FIXME: handle "template <> friend class A<T>;", which
5329 // is possibly well-formed? Who even knows?
5330 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5331 Diag(Loc, diag::err_tagless_friend_type_template)
5332 << DS.getSourceRange();
5333 return DeclPtrTy();
5334 }
5335
John McCall02cace72009-08-28 07:59:38 +00005336 // C++ [class.friend]p2:
5337 // An elaborated-type-specifier shall be used in a friend declaration
5338 // for a class.*
5339 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00005340 // This is one of the rare places in Clang where it's legitimate to
5341 // ask about the "spelling" of the type.
5342 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5343 // If we evaluated the type to a record type, suggest putting
5344 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00005345 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00005346 RecordDecl *RD = RT->getDecl();
5347
5348 std::string InsertionText = std::string(" ") + RD->getKindName();
5349
John McCalle3af0232009-10-07 23:34:25 +00005350 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5351 << (unsigned) RD->getTagKind()
5352 << T
5353 << SourceRange(DS.getFriendSpecLoc())
John McCall6b2becf2009-09-08 17:47:29 +00005354 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5355 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00005356 return DeclPtrTy();
5357 }else {
John McCall6b2becf2009-09-08 17:47:29 +00005358 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5359 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005360 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00005361 }
5362 }
5363
John McCalle3af0232009-10-07 23:34:25 +00005364 // Enum types cannot be friends.
5365 if (T->getAs<EnumType>()) {
5366 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5367 << SourceRange(DS.getFriendSpecLoc());
5368 return DeclPtrTy();
John McCall6b2becf2009-09-08 17:47:29 +00005369 }
John McCall02cace72009-08-28 07:59:38 +00005370
John McCall02cace72009-08-28 07:59:38 +00005371 // C++98 [class.friend]p1: A friend of a class is a function
5372 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005373 // This is fixed in DR77, which just barely didn't make the C++03
5374 // deadline. It's also a very silly restriction that seriously
5375 // affects inner classes and which nobody else seems to implement;
5376 // thus we never diagnose it, not even in -pedantic.
John McCall02cace72009-08-28 07:59:38 +00005377
John McCalldd4a3b02009-09-16 22:47:08 +00005378 Decl *D;
5379 if (TempParams.size())
5380 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5381 TempParams.size(),
5382 (TemplateParameterList**) TempParams.release(),
5383 T.getTypePtr(),
5384 DS.getFriendSpecLoc());
5385 else
5386 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5387 DS.getFriendSpecLoc());
5388 D->setAccess(AS_public);
5389 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005390
John McCalldd4a3b02009-09-16 22:47:08 +00005391 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005392}
5393
John McCallbbbcdd92009-09-11 21:02:39 +00005394Sema::DeclPtrTy
5395Sema::ActOnFriendFunctionDecl(Scope *S,
5396 Declarator &D,
5397 bool IsDefinition,
5398 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005399 const DeclSpec &DS = D.getDeclSpec();
5400
5401 assert(DS.isFriendSpecified());
5402 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5403
5404 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005405 TypeSourceInfo *TInfo = 0;
5406 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005407
5408 // C++ [class.friend]p1
5409 // A friend of a class is a function or class....
5410 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005411 // It *doesn't* see through dependent types, which is correct
5412 // according to [temp.arg.type]p3:
5413 // If a declaration acquires a function type through a
5414 // type dependent on a template-parameter and this causes
5415 // a declaration that does not use the syntactic form of a
5416 // function declarator to have a function type, the program
5417 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005418 if (!T->isFunctionType()) {
5419 Diag(Loc, diag::err_unexpected_friend);
5420
5421 // It might be worthwhile to try to recover by creating an
5422 // appropriate declaration.
5423 return DeclPtrTy();
5424 }
5425
5426 // C++ [namespace.memdef]p3
5427 // - If a friend declaration in a non-local class first declares a
5428 // class or function, the friend class or function is a member
5429 // of the innermost enclosing namespace.
5430 // - The name of the friend is not found by simple name lookup
5431 // until a matching declaration is provided in that namespace
5432 // scope (either before or after the class declaration granting
5433 // friendship).
5434 // - If a friend function is called, its name may be found by the
5435 // name lookup that considers functions from namespaces and
5436 // classes associated with the types of the function arguments.
5437 // - When looking for a prior declaration of a class or a function
5438 // declared as a friend, scopes outside the innermost enclosing
5439 // namespace scope are not considered.
5440
John McCall02cace72009-08-28 07:59:38 +00005441 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5442 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005443 assert(Name);
5444
John McCall67d1a672009-08-06 02:15:43 +00005445 // The context we found the declaration in, or in which we should
5446 // create the declaration.
5447 DeclContext *DC;
5448
5449 // FIXME: handle local classes
5450
5451 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005452 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5453 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005454 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005455 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005456 DC = computeDeclContext(ScopeQual);
5457
5458 // FIXME: handle dependent contexts
5459 if (!DC) return DeclPtrTy();
5460
John McCall68263142009-11-18 22:49:29 +00005461 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005462
5463 // If searching in that context implicitly found a declaration in
5464 // a different context, treat it like it wasn't found at all.
5465 // TODO: better diagnostics for this case. Suggesting the right
5466 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005467 // FIXME: getRepresentativeDecl() is not right here at all
5468 if (Previous.empty() ||
5469 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005470 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005471 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5472 return DeclPtrTy();
5473 }
5474
5475 // C++ [class.friend]p1: A friend of a class is a function or
5476 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005477 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005478 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5479
John McCall67d1a672009-08-06 02:15:43 +00005480 // Otherwise walk out to the nearest namespace scope looking for matches.
5481 } else {
5482 // TODO: handle local class contexts.
5483
5484 DC = CurContext;
5485 while (true) {
5486 // Skip class contexts. If someone can cite chapter and verse
5487 // for this behavior, that would be nice --- it's what GCC and
5488 // EDG do, and it seems like a reasonable intent, but the spec
5489 // really only says that checks for unqualified existing
5490 // declarations should stop at the nearest enclosing namespace,
5491 // not that they should only consider the nearest enclosing
5492 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005493 while (DC->isRecord())
5494 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005495
John McCall68263142009-11-18 22:49:29 +00005496 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005497
5498 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005499 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005500 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005501
John McCall67d1a672009-08-06 02:15:43 +00005502 if (DC->isFileContext()) break;
5503 DC = DC->getParent();
5504 }
5505
5506 // C++ [class.friend]p1: A friend of a class is a function or
5507 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005508 // C++0x changes this for both friend types and functions.
5509 // Most C++ 98 compilers do seem to give an error here, so
5510 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005511 if (!Previous.empty() && DC->Equals(CurContext)
5512 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005513 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5514 }
5515
Douglas Gregor182ddf02009-09-28 00:08:27 +00005516 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005517 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005518 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5519 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5520 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005521 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005522 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5523 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005524 return DeclPtrTy();
5525 }
John McCall67d1a672009-08-06 02:15:43 +00005526 }
5527
Douglas Gregor182ddf02009-09-28 00:08:27 +00005528 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005529 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005530 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005531 IsDefinition,
5532 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005533 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005534
Douglas Gregor182ddf02009-09-28 00:08:27 +00005535 assert(ND->getDeclContext() == DC);
5536 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005537
John McCallab88d972009-08-31 22:39:49 +00005538 // Add the function declaration to the appropriate lookup tables,
5539 // adjusting the redeclarations list as necessary. We don't
5540 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005541 //
John McCallab88d972009-08-31 22:39:49 +00005542 // Also update the scope-based lookup if the target context's
5543 // lookup context is in lexical scope.
5544 if (!CurContext->isDependentContext()) {
5545 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005546 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005547 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005548 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005549 }
John McCall02cace72009-08-28 07:59:38 +00005550
5551 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005552 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005553 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005554 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005555 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005556
Douglas Gregor7557a132009-12-24 20:56:24 +00005557 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5558 FrD->setSpecialization(true);
5559
Douglas Gregor182ddf02009-09-28 00:08:27 +00005560 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005561}
5562
Chris Lattnerb28317a2009-03-28 19:18:32 +00005563void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005564 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Chris Lattnerb28317a2009-03-28 19:18:32 +00005566 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005567 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5568 if (!Fn) {
5569 Diag(DelLoc, diag::err_deleted_non_function);
5570 return;
5571 }
5572 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5573 Diag(DelLoc, diag::err_deleted_decl_not_first);
5574 Diag(Prev->getLocation(), diag::note_previous_declaration);
5575 // If the declaration wasn't the first, we delete the function anyway for
5576 // recovery.
5577 }
5578 Fn->setDeleted();
5579}
Sebastian Redl13e88542009-04-27 21:33:24 +00005580
5581static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5582 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5583 ++CI) {
5584 Stmt *SubStmt = *CI;
5585 if (!SubStmt)
5586 continue;
5587 if (isa<ReturnStmt>(SubStmt))
5588 Self.Diag(SubStmt->getSourceRange().getBegin(),
5589 diag::err_return_in_constructor_handler);
5590 if (!isa<Expr>(SubStmt))
5591 SearchForReturnInStmt(Self, SubStmt);
5592 }
5593}
5594
5595void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5596 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5597 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5598 SearchForReturnInStmt(*this, Handler);
5599 }
5600}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005601
Mike Stump1eb44332009-09-09 15:08:12 +00005602bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005603 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005604 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5605 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005606
Chandler Carruth73857792010-02-15 11:53:20 +00005607 if (Context.hasSameType(NewTy, OldTy) ||
5608 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005609 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005610
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005611 // Check if the return types are covariant
5612 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005614 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005615 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5616 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005617 NewClassTy = NewPT->getPointeeType();
5618 OldClassTy = OldPT->getPointeeType();
5619 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005620 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5621 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5622 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5623 NewClassTy = NewRT->getPointeeType();
5624 OldClassTy = OldRT->getPointeeType();
5625 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005626 }
5627 }
Mike Stump1eb44332009-09-09 15:08:12 +00005628
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005629 // The return types aren't either both pointers or references to a class type.
5630 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005631 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005632 diag::err_different_return_type_for_overriding_virtual_function)
5633 << New->getDeclName() << NewTy << OldTy;
5634 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005635
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005636 return true;
5637 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005638
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005639 // C++ [class.virtual]p6:
5640 // If the return type of D::f differs from the return type of B::f, the
5641 // class type in the return type of D::f shall be complete at the point of
5642 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005643 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5644 if (!RT->isBeingDefined() &&
5645 RequireCompleteType(New->getLocation(), NewClassTy,
5646 PDiag(diag::err_covariant_return_incomplete)
5647 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005648 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005649 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005650
Douglas Gregora4923eb2009-11-16 21:35:15 +00005651 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005652 // Check if the new class derives from the old class.
5653 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5654 Diag(New->getLocation(),
5655 diag::err_covariant_return_not_derived)
5656 << New->getDeclName() << NewTy << OldTy;
5657 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5658 return true;
5659 }
Mike Stump1eb44332009-09-09 15:08:12 +00005660
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005661 // Check if we the conversion from derived to base is valid.
John McCall6b2accb2010-02-10 09:31:12 +00005662 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005663 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5664 // FIXME: Should this point to the return type?
5665 New->getLocation(), SourceRange(), New->getDeclName())) {
5666 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5667 return true;
5668 }
5669 }
Mike Stump1eb44332009-09-09 15:08:12 +00005670
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005671 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005672 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005673 Diag(New->getLocation(),
5674 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005675 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005676 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5677 return true;
5678 };
Mike Stump1eb44332009-09-09 15:08:12 +00005679
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005680
5681 // The new class type must have the same or less qualifiers as the old type.
5682 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5683 Diag(New->getLocation(),
5684 diag::err_covariant_return_type_class_type_more_qualified)
5685 << New->getDeclName() << NewTy << OldTy;
5686 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5687 return true;
5688 };
Mike Stump1eb44332009-09-09 15:08:12 +00005689
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005690 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005691}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005692
Sean Huntbbd37c62009-11-21 08:43:09 +00005693bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5694 const CXXMethodDecl *Old)
5695{
5696 if (Old->hasAttr<FinalAttr>()) {
5697 Diag(New->getLocation(), diag::err_final_function_overridden)
5698 << New->getDeclName();
5699 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5700 return true;
5701 }
5702
5703 return false;
5704}
5705
Douglas Gregor4ba31362009-12-01 17:24:26 +00005706/// \brief Mark the given method pure.
5707///
5708/// \param Method the method to be marked pure.
5709///
5710/// \param InitRange the source range that covers the "0" initializer.
5711bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5712 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5713 Method->setPure();
5714
5715 // A class is abstract if at least one function is pure virtual.
5716 Method->getParent()->setAbstract(true);
5717 return false;
5718 }
5719
5720 if (!Method->isInvalidDecl())
5721 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5722 << Method->getDeclName() << InitRange;
5723 return true;
5724}
5725
John McCall731ad842009-12-19 09:28:58 +00005726/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5727/// an initializer for the out-of-line declaration 'Dcl'. The scope
5728/// is a fresh scope pushed for just this purpose.
5729///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005730/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5731/// static data member of class X, names should be looked up in the scope of
5732/// class X.
5733void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005734 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005735 Decl *D = Dcl.getAs<Decl>();
5736 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005737
John McCall731ad842009-12-19 09:28:58 +00005738 // We should only get called for declarations with scope specifiers, like:
5739 // int foo::bar;
5740 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005741 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005742}
5743
5744/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005745/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005746void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005747 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005748 Decl *D = Dcl.getAs<Decl>();
5749 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005750
John McCall731ad842009-12-19 09:28:58 +00005751 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005752 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005753}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005754
5755/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5756/// C++ if/switch/while/for statement.
5757/// e.g: "if (int x = f()) {...}"
5758Action::DeclResult
5759Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5760 // C++ 6.4p2:
5761 // The declarator shall not specify a function or an array.
5762 // The type-specifier-seq shall not contain typedef and shall not declare a
5763 // new class or enumeration.
5764 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5765 "Parser allowed 'typedef' as storage class of condition decl.");
5766
John McCalla93c9342009-12-07 02:54:59 +00005767 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005768 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005769 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005770
5771 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5772 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5773 // would be created and CXXConditionDeclExpr wants a VarDecl.
5774 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5775 << D.getSourceRange();
5776 return DeclResult();
5777 } else if (OwnedTag && OwnedTag->isDefinition()) {
5778 // The type-specifier-seq shall not declare a new class or enumeration.
5779 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5780 }
5781
5782 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5783 if (!Dcl)
5784 return DeclResult();
5785
5786 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5787 VD->setDeclaredInCondition(true);
5788 return Dcl;
5789}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005790
Anders Carlssond6a637f2009-12-07 08:24:59 +00005791void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5792 CXXMethodDecl *MD) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005793 // Ignore dependent types.
5794 if (MD->isDependentContext())
5795 return;
5796
5797 CXXRecordDecl *RD = MD->getParent();
Anders Carlssonf53df232009-12-07 04:35:11 +00005798
5799 // Ignore classes without a vtable.
5800 if (!RD->isDynamicClass())
5801 return;
5802
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005803 // Ignore declarations that are not definitions.
5804 if (!MD->isThisDeclarationADefinition())
Anders Carlssond6a637f2009-12-07 08:24:59 +00005805 return;
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005806
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005807 if (isa<CXXConstructorDecl>(MD)) {
5808 switch (MD->getParent()->getTemplateSpecializationKind()) {
5809 case TSK_Undeclared:
5810 case TSK_ExplicitSpecialization:
5811 // Classes that aren't instantiations of templates don't need their
5812 // virtual methods marked until we see the definition of the key
5813 // function.
5814 return;
5815
5816 case TSK_ImplicitInstantiation:
5817 case TSK_ExplicitInstantiationDeclaration:
5818 case TSK_ExplicitInstantiationDefinition:
5819 // This is a constructor of a class template; mark all of the virtual
5820 // members as referenced to ensure that they get instantiatied.
5821 break;
5822 }
5823 } else if (!MD->isOutOfLine()) {
5824 // Consider only out-of-line definitions of member functions. When we see
5825 // an inline definition, it's too early to compute the key function.
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005826 return;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005827 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5828 // If this is not the key function, we don't need to mark virtual members.
5829 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5830 return;
5831 } else {
5832 // The class has no key function, so we've already noted that we need to
5833 // mark the virtual members of this class.
5834 return;
5835 }
5836
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005837 // We will need to mark all of the virtual members as referenced to build the
5838 // vtable.
5839 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
Anders Carlssond6a637f2009-12-07 08:24:59 +00005840}
5841
5842bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5843 if (ClassesWithUnmarkedVirtualMembers.empty())
5844 return false;
5845
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005846 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5847 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5848 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5849 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005850 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005851 }
5852
Anders Carlssond6a637f2009-12-07 08:24:59 +00005853 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005854}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005855
5856void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5857 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5858 e = RD->method_end(); i != e; ++i) {
5859 CXXMethodDecl *MD = *i;
5860
5861 // C++ [basic.def.odr]p2:
5862 // [...] A virtual member function is used if it is not pure. [...]
5863 if (MD->isVirtual() && !MD->isPure())
5864 MarkDeclarationReferenced(Loc, MD);
5865 }
5866}
5867