blob: 243d854a941b76478319188518ec5e037409887c [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000019#include "clang/AST/RecordLayout.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000022#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000023#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000025#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000028#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000029#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000030#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000031#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000032
33using namespace clang;
34
Chris Lattner8123a952008-04-10 02:22:51 +000035//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
Chris Lattner9e979552008-04-12 23:52:44 +000039namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000045 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000046 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000047 Expr *DefaultArg;
48 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 public:
Mike Stump1eb44332009-09-09 15:08:12 +000051 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000052 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000056 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000057 };
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000062 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000063 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000065 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000066 }
67
Chris Lattner9e979552008-04-12 23:52:44 +000068 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000073 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000082 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000083 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000084 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000085 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000086 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000089 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000090 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000091 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000092 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000093 }
Chris Lattner8123a952008-04-10 02:22:51 +000094
Douglas Gregor3996f232008-11-04 13:41:56 +000095 return false;
96 }
Chris Lattner9e979552008-04-12 23:52:44 +000097
Douglas Gregor796da182008-11-04 14:32:21 +000098 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107}
108
Anders Carlssoned961f92009-08-25 02:29:20 +0000109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000111 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Anders Carlssoned961f92009-08-25 02:29:20 +0000120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000133 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000135
Anders Carlsson0ece4912009-12-15 20:51:39 +0000136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Anders Carlssoned961f92009-08-25 02:29:20 +0000138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Anders Carlssoned961f92009-08-25 02:29:20 +0000141 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
Mike Stump1eb44332009-09-09 15:08:12 +0000150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000151 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000152 if (!param || !defarg.get())
153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Chris Lattnerb28317a2009-03-28 19:18:32 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000164 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000165 return;
166 }
167
Anders Carlsson66e30672009-08-25 01:02:06 +0000168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Anders Carlssoned961f92009-08-25 02:29:20 +0000175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000176}
177
Douglas Gregor61366e92008-12-24 00:01:03 +0000178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerb28317a2009-03-28 19:18:32 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000189 if (Param)
190 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Anders Carlsson5e300d12009-06-12 16:51:40 +0000192 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193}
194
Douglas Gregor72b505b2008-12-16 21:30:33 +0000195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000198 if (!param)
199 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000204
Anders Carlsson5e300d12009-06-12 16:51:40 +0000205 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000206}
207
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000237 }
238 }
239 }
240 }
241}
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
Chris Lattner3d1cee32008-04-08 05:04:30 +0000250 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
Douglas Gregor6cc15182009-09-11 18:44:32 +0000272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000284 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000298 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000299 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300 // Merge the old default argument into the new parameter
John McCallbf73b352010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
306 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000412 if (!Param->hasUnparsedDefaultArg())
413 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000414 Param->setDefaultArg(0);
415 }
416 }
417 }
418}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000419
Douglas Gregorb48fe382008-10-31 09:07:45 +0000420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000426 assert(getLangOptions().CPlusPlus && "No class names in C!");
427
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000428 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000429 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000430 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432 } else
433 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000435 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000436 return &II == CurDecl->getIdentifier();
437 else
438 return false;
439}
440
Mike Stump1eb44332009-09-09 15:08:12 +0000441/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447 SourceRange SpecifierRange,
448 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450 SourceLocation BaseLoc) {
451 // C++ [class.union]p1:
452 // A union shall not have base classes.
453 if (Class->isUnion()) {
454 Diag(Class->getLocation(), diag::err_base_clause_on_union)
455 << SpecifierRange;
456 return 0;
457 }
458
459 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000461 Class->getTagKind() == RecordDecl::TK_class,
462 Access, BaseType);
463
464 // Base specifiers must be record types.
465 if (!BaseType->isRecordType()) {
466 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467 return 0;
468 }
469
470 // C++ [class.union]p1:
471 // A union shall not be used as a base class.
472 if (BaseType->isUnionType()) {
473 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474 return 0;
475 }
476
477 // C++ [class.derived]p2:
478 // The class-name in a base-specifier shall not be an incompletely
479 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000480 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000481 PDiag(diag::err_incomplete_base_class)
482 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000483 return 0;
484
Eli Friedman1d954f62009-08-15 21:55:26 +0000485 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000486 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000487 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000488 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000490 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
491 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000492
Sean Huntbbd37c62009-11-21 08:43:09 +0000493 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
494 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
495 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000496 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
497 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000498 return 0;
499 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000500
Eli Friedmand0137332009-12-05 23:03:49 +0000501 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000502
503 // Create the base specifier.
504 // FIXME: Allocate via ASTContext?
505 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506 Class->getTagKind() == RecordDecl::TK_class,
507 Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511 const CXXRecordDecl *BaseClass,
512 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000513 // A class with a non-empty base class is not empty.
514 // FIXME: Standard ref?
515 if (!BaseClass->isEmpty())
516 Class->setEmpty(false);
517
518 // C++ [class.virtual]p1:
519 // A class that [...] inherits a virtual function is called a polymorphic
520 // class.
521 if (BaseClass->isPolymorphic())
522 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000523
Douglas Gregor2943aed2009-03-03 04:44:36 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is [...] a class with [...] no base classes [...].
526 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000527
528 // C++ [class]p4:
529 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000530 Class->setPOD(false);
531
Anders Carlsson51f94042009-12-03 17:49:57 +0000532 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000533 // C++ [class.ctor]p5:
534 // A constructor is trivial if its class has no virtual base classes.
535 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000536
537 // C++ [class.copy]p6:
538 // A copy constructor is trivial if its class has no virtual base classes.
539 Class->setHasTrivialCopyConstructor(false);
540
541 // C++ [class.copy]p11:
542 // A copy assignment operator is trivial if its class has no virtual
543 // base classes.
544 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000545
546 // C++0x [meta.unary.prop] is_empty:
547 // T is a class type, but not a union type, with ... no virtual base
548 // classes
549 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000550 } else {
551 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000552 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000553 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000554 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000555 Class->setHasTrivialConstructor(false);
556
557 // C++ [class.copy]p6:
558 // A copy constructor is trivial if all the direct base classes of its
559 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000560 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000561 Class->setHasTrivialCopyConstructor(false);
562
563 // C++ [class.copy]p11:
564 // A copy assignment operator is trivial if all the direct base classes
565 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000566 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000567 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000568 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000569
570 // C++ [class.ctor]p3:
571 // A destructor is trivial if all the direct base classes of its class
572 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000573 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000574 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000575}
576
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000579/// example:
580/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000581/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000582Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000584 bool Virtual, AccessSpecifier Access,
585 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000586 if (!classdecl)
587 return true;
588
Douglas Gregor40808ce2009-03-09 23:48:35 +0000589 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000590 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591 if (!Class)
592 return true;
593
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000594 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000595 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596 Virtual, Access,
597 BaseType, BaseLoc))
598 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Douglas Gregor2943aed2009-03-03 04:44:36 +0000600 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000601}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000602
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606 unsigned NumBases) {
607 if (NumBases == 0)
608 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609
610 // Used to keep track of which base types we have already seen, so
611 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000612 // that the key is always the unqualified canonical type of the base
613 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000618 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000619 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000620 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000621 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000622 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000623
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000624 if (KnownBaseTypes[NewBaseType]) {
625 // C++ [class.mi]p3:
626 // A class shall not be specified as a direct base class of a
627 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000628 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000629 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000630 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000632
633 // Delete the duplicate base class specifier; we're going to
634 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000635 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000636
637 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 } else {
639 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000640 KnownBaseTypes[NewBaseType] = Bases[idx];
641 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000642 }
643 }
644
645 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000646 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000647
648 // Delete the remaining (good) base class specifiers, since their
649 // data has been copied into the CXXRecordDecl.
650 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000651 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000652
653 return Invalid;
654}
655
656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
657/// class, after checking whether there are any duplicate base
658/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000660 unsigned NumBases) {
661 if (!ClassDecl || !Bases || !NumBases)
662 return;
663
664 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000666 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000667}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000668
John McCall3cb0ebd2010-03-10 03:28:59 +0000669static CXXRecordDecl *GetClassForType(QualType T) {
670 if (const RecordType *RT = T->getAs<RecordType>())
671 return cast<CXXRecordDecl>(RT->getDecl());
672 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
673 return ICT->getDecl();
674 else
675 return 0;
676}
677
Douglas Gregora8f32e02009-10-06 17:59:45 +0000678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
681 if (!getLangOptions().CPlusPlus)
682 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000683
684 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 return false;
687
John McCall3cb0ebd2010-03-10 03:28:59 +0000688 CXXRecordDecl *BaseRD = GetClassForType(Base);
689 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000690 return false;
691
John McCall86ff3082010-02-04 22:26:26 +0000692 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
693 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000694}
695
696/// \brief Determine whether the type \p Derived is a C++ class that is
697/// derived from the type \p Base.
698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
699 if (!getLangOptions().CPlusPlus)
700 return false;
701
John McCall3cb0ebd2010-03-10 03:28:59 +0000702 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
703 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704 return false;
705
John McCall3cb0ebd2010-03-10 03:28:59 +0000706 CXXRecordDecl *BaseRD = GetClassForType(Base);
707 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000708 return false;
709
Douglas Gregora8f32e02009-10-06 17:59:45 +0000710 return DerivedRD->isDerivedFrom(BaseRD, Paths);
711}
712
713/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
714/// conversion (where Derived and Base are class types) is
715/// well-formed, meaning that the conversion is unambiguous (and
716/// that all of the base classes are accessible). Returns true
717/// and emits a diagnostic if the code is ill-formed, returns false
718/// otherwise. Loc is the location where this routine should point to
719/// if there is an error, and Range is the source range to highlight
720/// if there is an error.
721bool
722Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000723 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000724 unsigned AmbigiousBaseConvID,
725 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000726 DeclarationName Name,
727 CXXBaseSpecifierArray *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000728 // First, determine whether the path from Derived to Base is
729 // ambiguous. This is slightly more expensive than checking whether
730 // the Derived to Base conversion exists, because here we need to
731 // explore multiple paths to determine if there is an ambiguity.
732 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
733 /*DetectVirtual=*/false);
734 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
735 assert(DerivationOkay &&
736 "Can only be used with a derived-to-base conversion");
737 (void)DerivationOkay;
738
739 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
John McCall58e6f342010-03-16 05:22:47 +0000740 if (!InaccessibleBaseID)
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000741 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000742
Douglas Gregora8f32e02009-10-06 17:59:45 +0000743 // Check that the base class can be accessed.
John McCall58e6f342010-03-16 05:22:47 +0000744 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
745 InaccessibleBaseID)) {
Anders Carlssone25a96c2010-04-24 17:11:09 +0000746 case AR_inaccessible:
747 return true;
748 case AR_accessible:
749 case AR_dependent:
750 case AR_delayed:
751 // Build a base path if necessary.
752 if (BasePath) {
753 // FIXME: Do this!
754 }
755 return false;
John McCall6b2accb2010-02-10 09:31:12 +0000756 }
Douglas Gregora8f32e02009-10-06 17:59:45 +0000757 }
758
759 // We know that the derived-to-base conversion is ambiguous, and
760 // we're going to produce a diagnostic. Perform the derived-to-base
761 // search just one more time to compute all of the possible paths so
762 // that we can print them out. This is more expensive than any of
763 // the previous derived-to-base checks we've done, but at this point
764 // performance isn't as much of an issue.
765 Paths.clear();
766 Paths.setRecordingPaths(true);
767 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
768 assert(StillOkay && "Can only be used with a derived-to-base conversion");
769 (void)StillOkay;
770
771 // Build up a textual representation of the ambiguous paths, e.g.,
772 // D -> B -> A, that will be used to illustrate the ambiguous
773 // conversions in the diagnostic. We only print one of the paths
774 // to each base class subobject.
775 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
776
777 Diag(Loc, AmbigiousBaseConvID)
778 << Derived << Base << PathDisplayStr << Range << Name;
779 return true;
780}
781
782bool
783Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000784 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000785 CXXBaseSpecifierArray *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000786 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000787 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000788 IgnoreAccess ? 0
789 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000790 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000791 Loc, Range, DeclarationName(),
792 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000793}
794
795
796/// @brief Builds a string representing ambiguous paths from a
797/// specific derived class to different subobjects of the same base
798/// class.
799///
800/// This function builds a string that can be used in error messages
801/// to show the different paths that one can take through the
802/// inheritance hierarchy to go from the derived class to different
803/// subobjects of a base class. The result looks something like this:
804/// @code
805/// struct D -> struct B -> struct A
806/// struct D -> struct C -> struct A
807/// @endcode
808std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
809 std::string PathDisplayStr;
810 std::set<unsigned> DisplayedPaths;
811 for (CXXBasePaths::paths_iterator Path = Paths.begin();
812 Path != Paths.end(); ++Path) {
813 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
814 // We haven't displayed a path to this particular base
815 // class subobject yet.
816 PathDisplayStr += "\n ";
817 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
818 for (CXXBasePath::const_iterator Element = Path->begin();
819 Element != Path->end(); ++Element)
820 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
821 }
822 }
823
824 return PathDisplayStr;
825}
826
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000827//===----------------------------------------------------------------------===//
828// C++ class member Handling
829//===----------------------------------------------------------------------===//
830
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000831/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
832/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
833/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000834/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000835Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000836Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000837 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000838 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
839 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000840 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000841 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000842 Expr *BitWidth = static_cast<Expr*>(BW);
843 Expr *Init = static_cast<Expr*>(InitExpr);
844 SourceLocation Loc = D.getIdentifierLoc();
845
Sebastian Redl669d5d72008-11-14 23:42:31 +0000846 bool isFunc = D.isFunctionDeclarator();
847
John McCall67d1a672009-08-06 02:15:43 +0000848 assert(!DS.isFriendSpecified());
849
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000850 // C++ 9.2p6: A member shall not be declared to have automatic storage
851 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000852 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
853 // data members and cannot be applied to names declared const or static,
854 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855 switch (DS.getStorageClassSpec()) {
856 case DeclSpec::SCS_unspecified:
857 case DeclSpec::SCS_typedef:
858 case DeclSpec::SCS_static:
859 // FALL THROUGH.
860 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000861 case DeclSpec::SCS_mutable:
862 if (isFunc) {
863 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000864 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000865 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000866 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Sebastian Redla11f42f2008-11-17 23:24:37 +0000868 // FIXME: It would be nicer if the keyword was ignored only for this
869 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000870 D.getMutableDeclSpec().ClearStorageClassSpecs();
871 } else {
872 QualType T = GetTypeForDeclarator(D, S);
873 diag::kind err = static_cast<diag::kind>(0);
874 if (T->isReferenceType())
875 err = diag::err_mutable_reference;
876 else if (T.isConstQualified())
877 err = diag::err_mutable_const;
878 if (err != 0) {
879 if (DS.getStorageClassSpecLoc().isValid())
880 Diag(DS.getStorageClassSpecLoc(), err);
881 else
882 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000883 // FIXME: It would be nicer if the keyword was ignored only for this
884 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000885 D.getMutableDeclSpec().ClearStorageClassSpecs();
886 }
887 }
888 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000889 default:
890 if (DS.getStorageClassSpecLoc().isValid())
891 Diag(DS.getStorageClassSpecLoc(),
892 diag::err_storageclass_invalid_for_member);
893 else
894 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
895 D.getMutableDeclSpec().ClearStorageClassSpecs();
896 }
897
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000898 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000899 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000900 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000901 // Check also for this case:
902 //
903 // typedef int f();
904 // f a;
905 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000906 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000907 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000908 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000909
Sebastian Redl669d5d72008-11-14 23:42:31 +0000910 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
911 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000912 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000913
914 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000915 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000916 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000917 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
918 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000919 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000920 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000921 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000922 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000923 if (!Member) {
924 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000925 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000926 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000927
928 // Non-instance-fields can't have a bitfield.
929 if (BitWidth) {
930 if (Member->isInvalidDecl()) {
931 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000932 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000933 // C++ 9.6p3: A bit-field shall not be a static member.
934 // "static member 'A' cannot be a bit-field"
935 Diag(Loc, diag::err_static_not_bitfield)
936 << Name << BitWidth->getSourceRange();
937 } else if (isa<TypedefDecl>(Member)) {
938 // "typedef member 'x' cannot be a bit-field"
939 Diag(Loc, diag::err_typedef_not_bitfield)
940 << Name << BitWidth->getSourceRange();
941 } else {
942 // A function typedef ("typedef int f(); f a;").
943 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
944 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000945 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000946 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner8b963ef2009-03-05 23:01:03 +0000949 DeleteExpr(BitWidth);
950 BitWidth = 0;
951 Member->setInvalidDecl();
952 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000953
954 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregor37b372b2009-08-20 22:52:58 +0000956 // If we have declared a member function template, set the access of the
957 // templated declaration as well.
958 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
959 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000960 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000961
Douglas Gregor10bd3682008-11-17 22:58:34 +0000962 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000963
Douglas Gregor021c3b32009-03-11 23:00:04 +0000964 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000965 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000966 if (Deleted) // FIXME: Source location is not very good.
967 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000968
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000969 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000970 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000971 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000972 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000973 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000974}
975
Douglas Gregorfe0241e2009-12-31 09:10:24 +0000976/// \brief Find the direct and/or virtual base specifiers that
977/// correspond to the given base type, for use in base initialization
978/// within a constructor.
979static bool FindBaseInitializer(Sema &SemaRef,
980 CXXRecordDecl *ClassDecl,
981 QualType BaseType,
982 const CXXBaseSpecifier *&DirectBaseSpec,
983 const CXXBaseSpecifier *&VirtualBaseSpec) {
984 // First, check for a direct base class.
985 DirectBaseSpec = 0;
986 for (CXXRecordDecl::base_class_const_iterator Base
987 = ClassDecl->bases_begin();
988 Base != ClassDecl->bases_end(); ++Base) {
989 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
990 // We found a direct base of this type. That's what we're
991 // initializing.
992 DirectBaseSpec = &*Base;
993 break;
994 }
995 }
996
997 // Check for a virtual base class.
998 // FIXME: We might be able to short-circuit this if we know in advance that
999 // there are no virtual bases.
1000 VirtualBaseSpec = 0;
1001 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1002 // We haven't found a base yet; search the class hierarchy for a
1003 // virtual base class.
1004 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1005 /*DetectVirtual=*/false);
1006 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1007 BaseType, Paths)) {
1008 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1009 Path != Paths.end(); ++Path) {
1010 if (Path->back().Base->isVirtual()) {
1011 VirtualBaseSpec = Path->back().Base;
1012 break;
1013 }
1014 }
1015 }
1016 }
1017
1018 return DirectBaseSpec || VirtualBaseSpec;
1019}
1020
Douglas Gregor7ad83902008-11-05 04:29:56 +00001021/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001022Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001023Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001024 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001025 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001026 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001027 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001028 SourceLocation IdLoc,
1029 SourceLocation LParenLoc,
1030 ExprTy **Args, unsigned NumArgs,
1031 SourceLocation *CommaLocs,
1032 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001033 if (!ConstructorD)
1034 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001036 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001037
1038 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001039 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001040 if (!Constructor) {
1041 // The user wrote a constructor initializer on a function that is
1042 // not a C++ constructor. Ignore the error for now, because we may
1043 // have more member initializers coming; we'll diagnose it just
1044 // once in ActOnMemInitializers.
1045 return true;
1046 }
1047
1048 CXXRecordDecl *ClassDecl = Constructor->getParent();
1049
1050 // C++ [class.base.init]p2:
1051 // Names in a mem-initializer-id are looked up in the scope of the
1052 // constructor’s class and, if not found in that scope, are looked
1053 // up in the scope containing the constructor’s
1054 // definition. [Note: if the constructor’s class contains a member
1055 // with the same name as a direct or virtual base class of the
1056 // class, a mem-initializer-id naming the member or base class and
1057 // composed of a single identifier refers to the class member. A
1058 // mem-initializer-id for the hidden base class may be specified
1059 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001060 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001061 // Look for a member, first.
1062 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001063 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001064 = ClassDecl->lookup(MemberOrBase);
1065 if (Result.first != Result.second)
1066 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001067
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001068 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001069
Eli Friedman59c04372009-07-29 19:44:27 +00001070 if (Member)
1071 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001072 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001073 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001074 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001075 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001076 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001077
1078 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001079 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001080 } else {
1081 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1082 LookupParsedName(R, S, &SS);
1083
1084 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1085 if (!TyD) {
1086 if (R.isAmbiguous()) return true;
1087
John McCallfd225442010-04-09 19:01:14 +00001088 // We don't want access-control diagnostics here.
1089 R.suppressDiagnostics();
1090
Douglas Gregor7a886e12010-01-19 06:46:48 +00001091 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1092 bool NotUnknownSpecialization = false;
1093 DeclContext *DC = computeDeclContext(SS, false);
1094 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1095 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1096
1097 if (!NotUnknownSpecialization) {
1098 // When the scope specifier can refer to a member of an unknown
1099 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001100 BaseType = CheckTypenameType(ETK_None,
1101 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregor7a886e12010-01-19 06:46:48 +00001102 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001103 if (BaseType.isNull())
1104 return true;
1105
Douglas Gregor7a886e12010-01-19 06:46:48 +00001106 R.clear();
1107 }
1108 }
1109
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001110 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001111 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001112 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1113 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001114 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1115 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1116 // We have found a non-static data member with a similar
1117 // name to what was typed; complain and initialize that
1118 // member.
1119 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1120 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001121 << FixItHint::CreateReplacement(R.getNameLoc(),
1122 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001123 Diag(Member->getLocation(), diag::note_previous_decl)
1124 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001125
1126 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1127 LParenLoc, RParenLoc);
1128 }
1129 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1130 const CXXBaseSpecifier *DirectBaseSpec;
1131 const CXXBaseSpecifier *VirtualBaseSpec;
1132 if (FindBaseInitializer(*this, ClassDecl,
1133 Context.getTypeDeclType(Type),
1134 DirectBaseSpec, VirtualBaseSpec)) {
1135 // We have found a direct or virtual base class with a
1136 // similar name to what was typed; complain and initialize
1137 // that base class.
1138 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1139 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001140 << FixItHint::CreateReplacement(R.getNameLoc(),
1141 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001142
1143 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1144 : VirtualBaseSpec;
1145 Diag(BaseSpec->getSourceRange().getBegin(),
1146 diag::note_base_class_specified_here)
1147 << BaseSpec->getType()
1148 << BaseSpec->getSourceRange();
1149
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001150 TyD = Type;
1151 }
1152 }
1153 }
1154
Douglas Gregor7a886e12010-01-19 06:46:48 +00001155 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001156 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1157 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1158 return true;
1159 }
John McCall2b194412009-12-21 10:41:20 +00001160 }
1161
Douglas Gregor7a886e12010-01-19 06:46:48 +00001162 if (BaseType.isNull()) {
1163 BaseType = Context.getTypeDeclType(TyD);
1164 if (SS.isSet()) {
1165 NestedNameSpecifier *Qualifier =
1166 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001167
Douglas Gregor7a886e12010-01-19 06:46:48 +00001168 // FIXME: preserve source range information
1169 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1170 }
John McCall2b194412009-12-21 10:41:20 +00001171 }
1172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
John McCalla93c9342009-12-07 02:54:59 +00001174 if (!TInfo)
1175 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001176
John McCalla93c9342009-12-07 02:54:59 +00001177 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001178 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001179}
1180
John McCallb4190042009-11-04 23:02:40 +00001181/// Checks an initializer expression for use of uninitialized fields, such as
1182/// containing the field that is being initialized. Returns true if there is an
1183/// uninitialized field was used an updates the SourceLocation parameter; false
1184/// otherwise.
1185static bool InitExprContainsUninitializedFields(const Stmt* S,
1186 const FieldDecl* LhsField,
1187 SourceLocation* L) {
1188 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1189 if (ME) {
1190 const NamedDecl* RhsField = ME->getMemberDecl();
1191 if (RhsField == LhsField) {
1192 // Initializing a field with itself. Throw a warning.
1193 // But wait; there are exceptions!
1194 // Exception #1: The field may not belong to this record.
1195 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1196 const Expr* base = ME->getBase();
1197 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1198 // Even though the field matches, it does not belong to this record.
1199 return false;
1200 }
1201 // None of the exceptions triggered; return true to indicate an
1202 // uninitialized field was used.
1203 *L = ME->getMemberLoc();
1204 return true;
1205 }
1206 }
1207 bool found = false;
1208 for (Stmt::const_child_iterator it = S->child_begin();
1209 it != S->child_end() && found == false;
1210 ++it) {
1211 if (isa<CallExpr>(S)) {
1212 // Do not descend into function calls or constructors, as the use
1213 // of an uninitialized field may be valid. One would have to inspect
1214 // the contents of the function/ctor to determine if it is safe or not.
1215 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1216 // may be safe, depending on what the function/ctor does.
1217 continue;
1218 }
1219 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1220 }
1221 return found;
1222}
1223
Eli Friedman59c04372009-07-29 19:44:27 +00001224Sema::MemInitResult
1225Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1226 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001227 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001228 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001229 // Diagnose value-uses of fields to initialize themselves, e.g.
1230 // foo(foo)
1231 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001232 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001233 for (unsigned i = 0; i < NumArgs; ++i) {
1234 SourceLocation L;
1235 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1236 // FIXME: Return true in the case when other fields are used before being
1237 // uninitialized. For example, let this field be the i'th field. When
1238 // initializing the i'th field, throw a warning if any of the >= i'th
1239 // fields are used, as they are not yet initialized.
1240 // Right now we are only handling the case where the i'th field uses
1241 // itself in its initializer.
1242 Diag(L, diag::warn_field_is_uninit);
1243 }
1244 }
1245
Eli Friedman59c04372009-07-29 19:44:27 +00001246 bool HasDependentArg = false;
1247 for (unsigned i = 0; i < NumArgs; i++)
1248 HasDependentArg |= Args[i]->isTypeDependent();
1249
Eli Friedman59c04372009-07-29 19:44:27 +00001250 QualType FieldType = Member->getType();
1251 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1252 FieldType = Array->getElementType();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001253 if (FieldType->isDependentType() || HasDependentArg) {
1254 // Can't check initialization for a member of dependent type or when
1255 // any of the arguments are type-dependent expressions.
1256 OwningExprResult Init
1257 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1258 RParenLoc));
1259
1260 // Erase any temporaries within this evaluation context; we're not
1261 // going to track them in the AST, since we'll be rebuilding the
1262 // ASTs during template instantiation.
1263 ExprTemporaries.erase(
1264 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1265 ExprTemporaries.end());
1266
1267 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1268 LParenLoc,
1269 Init.takeAs<Expr>(),
1270 RParenLoc);
1271
Douglas Gregor7ad83902008-11-05 04:29:56 +00001272 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001273
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001274 if (Member->isInvalidDecl())
1275 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001276
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001277 // Initialize the member.
1278 InitializedEntity MemberEntity =
1279 InitializedEntity::InitializeMember(Member, 0);
1280 InitializationKind Kind =
1281 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1282
1283 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1284
1285 OwningExprResult MemberInit =
1286 InitSeq.Perform(*this, MemberEntity, Kind,
1287 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1288 if (MemberInit.isInvalid())
1289 return true;
1290
1291 // C++0x [class.base.init]p7:
1292 // The initialization of each base and member constitutes a
1293 // full-expression.
1294 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1295 if (MemberInit.isInvalid())
1296 return true;
1297
1298 // If we are in a dependent context, template instantiation will
1299 // perform this type-checking again. Just save the arguments that we
1300 // received in a ParenListExpr.
1301 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1302 // of the information that we have about the member
1303 // initializer. However, deconstructing the ASTs is a dicey process,
1304 // and this approach is far more likely to get the corner cases right.
1305 if (CurContext->isDependentContext()) {
1306 // Bump the reference count of all of the arguments.
1307 for (unsigned I = 0; I != NumArgs; ++I)
1308 Args[I]->Retain();
1309
1310 OwningExprResult Init
1311 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1312 RParenLoc));
1313 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1314 LParenLoc,
1315 Init.takeAs<Expr>(),
1316 RParenLoc);
1317 }
1318
Douglas Gregor802ab452009-12-02 22:36:29 +00001319 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001320 LParenLoc,
1321 MemberInit.takeAs<Expr>(),
1322 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001323}
1324
1325Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001326Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001327 Expr **Args, unsigned NumArgs,
1328 SourceLocation LParenLoc, SourceLocation RParenLoc,
1329 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001330 bool HasDependentArg = false;
1331 for (unsigned i = 0; i < NumArgs; i++)
1332 HasDependentArg |= Args[i]->isTypeDependent();
1333
John McCalla93c9342009-12-07 02:54:59 +00001334 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001335 if (BaseType->isDependentType() || HasDependentArg) {
1336 // Can't check initialization for a base of dependent type or when
1337 // any of the arguments are type-dependent expressions.
1338 OwningExprResult BaseInit
1339 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1340 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001341
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001342 // Erase any temporaries within this evaluation context; we're not
1343 // going to track them in the AST, since we'll be rebuilding the
1344 // ASTs during template instantiation.
1345 ExprTemporaries.erase(
1346 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1347 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001349 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001350 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001351 LParenLoc,
1352 BaseInit.takeAs<Expr>(),
1353 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001354 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001355
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001356 if (!BaseType->isRecordType())
1357 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1358 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1359
1360 // C++ [class.base.init]p2:
1361 // [...] Unless the mem-initializer-id names a nonstatic data
1362 // member of the constructor’s class or a direct or virtual base
1363 // of that class, the mem-initializer is ill-formed. A
1364 // mem-initializer-list can initialize a base class using any
1365 // name that denotes that base class type.
1366
1367 // Check for direct and virtual base classes.
1368 const CXXBaseSpecifier *DirectBaseSpec = 0;
1369 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1370 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1371 VirtualBaseSpec);
1372
1373 // C++ [base.class.init]p2:
1374 // If a mem-initializer-id is ambiguous because it designates both
1375 // a direct non-virtual base class and an inherited virtual base
1376 // class, the mem-initializer is ill-formed.
1377 if (DirectBaseSpec && VirtualBaseSpec)
1378 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1379 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1380 // C++ [base.class.init]p2:
1381 // Unless the mem-initializer-id names a nonstatic data membeer of the
1382 // constructor's class ot a direst or virtual base of that class, the
1383 // mem-initializer is ill-formed.
1384 if (!DirectBaseSpec && !VirtualBaseSpec)
1385 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1386 << BaseType << ClassDecl->getNameAsCString()
1387 << BaseTInfo->getTypeLoc().getSourceRange();
1388
1389 CXXBaseSpecifier *BaseSpec
1390 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1391 if (!BaseSpec)
1392 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1393
1394 // Initialize the base.
1395 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001396 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001397 InitializationKind Kind =
1398 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1399
1400 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1401
1402 OwningExprResult BaseInit =
1403 InitSeq.Perform(*this, BaseEntity, Kind,
1404 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1405 if (BaseInit.isInvalid())
1406 return true;
1407
1408 // C++0x [class.base.init]p7:
1409 // The initialization of each base and member constitutes a
1410 // full-expression.
1411 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1412 if (BaseInit.isInvalid())
1413 return true;
1414
1415 // If we are in a dependent context, template instantiation will
1416 // perform this type-checking again. Just save the arguments that we
1417 // received in a ParenListExpr.
1418 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1419 // of the information that we have about the base
1420 // initializer. However, deconstructing the ASTs is a dicey process,
1421 // and this approach is far more likely to get the corner cases right.
1422 if (CurContext->isDependentContext()) {
1423 // Bump the reference count of all of the arguments.
1424 for (unsigned I = 0; I != NumArgs; ++I)
1425 Args[I]->Retain();
1426
1427 OwningExprResult Init
1428 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1429 RParenLoc));
1430 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001431 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001432 LParenLoc,
1433 Init.takeAs<Expr>(),
1434 RParenLoc);
1435 }
1436
1437 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001438 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001439 LParenLoc,
1440 BaseInit.takeAs<Expr>(),
1441 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001442}
1443
Anders Carlssone5ef7402010-04-23 03:10:23 +00001444/// ImplicitInitializerKind - How an implicit base or member initializer should
1445/// initialize its base or member.
1446enum ImplicitInitializerKind {
1447 IIK_Default,
1448 IIK_Copy,
1449 IIK_Move
1450};
1451
Anders Carlssondefefd22010-04-23 02:00:02 +00001452static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001453BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001454 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001455 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001456 bool IsInheritedVirtualBase,
1457 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001458 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001459 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1460 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001461
Anders Carlssone5ef7402010-04-23 03:10:23 +00001462 Sema::OwningExprResult BaseInit(SemaRef);
1463
1464 switch (ImplicitInitKind) {
1465 case IIK_Default: {
1466 InitializationKind InitKind
1467 = InitializationKind::CreateDefault(Constructor->getLocation());
1468 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1469 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1470 Sema::MultiExprArg(SemaRef, 0, 0));
1471 break;
1472 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001473
Anders Carlssone5ef7402010-04-23 03:10:23 +00001474 case IIK_Copy: {
1475 ParmVarDecl *Param = Constructor->getParamDecl(0);
1476 QualType ParamType = Param->getType().getNonReferenceType();
1477
1478 Expr *CopyCtorArg =
1479 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1480 SourceLocation(), ParamType, 0);
1481
1482 InitializationKind InitKind
1483 = InitializationKind::CreateDirect(Constructor->getLocation(),
1484 SourceLocation(), SourceLocation());
1485 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1486 &CopyCtorArg, 1);
1487 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1488 Sema::MultiExprArg(SemaRef,
1489 (void**)&CopyCtorArg, 1));
1490 break;
1491 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001492
Anders Carlssone5ef7402010-04-23 03:10:23 +00001493 case IIK_Move:
1494 assert(false && "Unhandled initializer kind!");
1495 }
1496
Anders Carlsson84688f22010-04-20 23:11:20 +00001497 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1498 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001499 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001500
Anders Carlssondefefd22010-04-23 02:00:02 +00001501 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001502 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1503 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1504 SourceLocation()),
1505 BaseSpec->isVirtual(),
1506 SourceLocation(),
1507 BaseInit.takeAs<Expr>(),
1508 SourceLocation());
1509
Anders Carlssondefefd22010-04-23 02:00:02 +00001510 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001511}
1512
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001513static bool
1514BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001515 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001516 FieldDecl *Field,
1517 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001518 if (ImplicitInitKind == IIK_Copy) {
1519 ParmVarDecl *Param = Constructor->getParamDecl(0);
1520 QualType ParamType = Param->getType().getNonReferenceType();
1521
1522 Expr *MemberExprBase =
1523 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1524 SourceLocation(), ParamType, 0);
1525
1526
1527 Expr *CopyCtorArg =
1528 MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1529 0, SourceRange(), Field,
1530 DeclAccessPair::make(Field, Field->getAccess()),
1531 SourceLocation(), 0,
1532 Field->getType().getNonReferenceType());
1533
1534 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1535 InitializationKind InitKind =
1536 InitializationKind::CreateDirect(Constructor->getLocation(),
1537 SourceLocation(), SourceLocation());
1538
1539 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1540 &CopyCtorArg, 1);
1541
1542 Sema::OwningExprResult MemberInit =
1543 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1544 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1545 if (MemberInit.isInvalid())
1546 return true;
1547
Anders Carlssone5ef7402010-04-23 03:10:23 +00001548 CXXMemberInit = 0;
1549 return false;
1550 }
1551
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001552 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1553
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001554 QualType FieldBaseElementType =
1555 SemaRef.Context.getBaseElementType(Field->getType());
1556
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001557 if (FieldBaseElementType->isRecordType()) {
1558 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001559 InitializationKind InitKind =
1560 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001561
1562 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1563 Sema::OwningExprResult MemberInit =
1564 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1565 Sema::MultiExprArg(SemaRef, 0, 0));
1566 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1567 if (MemberInit.isInvalid())
1568 return true;
1569
1570 CXXMemberInit =
1571 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1572 Field, SourceLocation(),
1573 SourceLocation(),
1574 MemberInit.takeAs<Expr>(),
1575 SourceLocation());
1576 return false;
1577 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001578
1579 if (FieldBaseElementType->isReferenceType()) {
1580 SemaRef.Diag(Constructor->getLocation(),
1581 diag::err_uninitialized_member_in_ctor)
1582 << (int)Constructor->isImplicit()
1583 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1584 << 0 << Field->getDeclName();
1585 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1586 return true;
1587 }
1588
1589 if (FieldBaseElementType.isConstQualified()) {
1590 SemaRef.Diag(Constructor->getLocation(),
1591 diag::err_uninitialized_member_in_ctor)
1592 << (int)Constructor->isImplicit()
1593 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1594 << 1 << Field->getDeclName();
1595 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1596 return true;
1597 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001598
1599 // Nothing to initialize.
1600 CXXMemberInit = 0;
1601 return false;
1602}
1603
Eli Friedman80c30da2009-11-09 19:20:36 +00001604bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001605Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001606 CXXBaseOrMemberInitializer **Initializers,
1607 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001608 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001609 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001610 // Just store the initializers as written, they will be checked during
1611 // instantiation.
1612 if (NumInitializers > 0) {
1613 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1614 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1615 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1616 memcpy(baseOrMemberInitializers, Initializers,
1617 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1618 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1619 }
1620
1621 return false;
1622 }
1623
Anders Carlssone5ef7402010-04-23 03:10:23 +00001624 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1625
1626 // FIXME: Handle implicit move constructors.
1627 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1628 ImplicitInitKind = IIK_Copy;
1629
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001630 // We need to build the initializer AST according to order of construction
1631 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001632 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001633 if (!ClassDecl)
1634 return true;
1635
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001636 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1637 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman80c30da2009-11-09 19:20:36 +00001638 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001640 for (unsigned i = 0; i < NumInitializers; i++) {
1641 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001642
1643 if (Member->isBaseInitializer())
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001644 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001645 else
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001646 AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001647 }
1648
Anders Carlsson711f34a2010-04-21 19:52:01 +00001649 // Keep track of the direct virtual bases.
1650 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1651 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1652 E = ClassDecl->bases_end(); I != E; ++I) {
1653 if (I->isVirtual())
1654 DirectVBases.insert(I);
1655 }
1656
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001657 // Push virtual bases before others.
1658 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1659 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1660
1661 if (CXXBaseOrMemberInitializer *Value
1662 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1663 AllToInit.push_back(Value);
1664 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001665 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001666 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001667 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1668 VBase, IsInheritedVirtualBase,
1669 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001670 HadError = true;
1671 continue;
1672 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001673
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001674 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001675 }
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1679 E = ClassDecl->bases_end(); Base != E; ++Base) {
1680 // Virtuals are in the virtual base list and already constructed.
1681 if (Base->isVirtual())
1682 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001684 if (CXXBaseOrMemberInitializer *Value
1685 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1686 AllToInit.push_back(Value);
1687 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001688 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001689 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1690 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001691 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001692 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001693 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001694 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001695
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001696 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001697 }
1698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001700 // non-static data members.
1701 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1702 E = ClassDecl->field_end(); Field != E; ++Field) {
1703 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001704 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001705 Field->getType()->getAs<RecordType>()) {
1706 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001707 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001708 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001709 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1710 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1711 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1712 // set to the anonymous union data member used in the initializer
1713 // list.
1714 Value->setMember(*Field);
1715 Value->setAnonUnionMember(*FA);
1716 AllToInit.push_back(Value);
1717 break;
1718 }
1719 }
1720 }
1721 continue;
1722 }
1723 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1724 AllToInit.push_back(Value);
1725 continue;
1726 }
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Anders Carlssondefefd22010-04-23 02:00:02 +00001728 if (AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001729 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001730
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001731 CXXBaseOrMemberInitializer *Member;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001732 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1733 *Field, Member)) {
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001734 HadError = true;
1735 continue;
1736 }
1737
1738 // If the member doesn't need to be initialized, it will be null.
1739 if (Member)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001740 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001741 }
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001743 NumInitializers = AllToInit.size();
1744 if (NumInitializers > 0) {
1745 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1746 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1747 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallef027fe2010-03-16 21:39:52 +00001748 memcpy(baseOrMemberInitializers, AllToInit.data(),
1749 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001750 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001751
John McCallef027fe2010-03-16 21:39:52 +00001752 // Constructors implicitly reference the base and member
1753 // destructors.
1754 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1755 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001756 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001757
1758 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001759}
1760
Eli Friedman6347f422009-07-21 19:28:10 +00001761static void *GetKeyForTopLevelField(FieldDecl *Field) {
1762 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001763 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001764 if (RT->getDecl()->isAnonymousStructOrUnion())
1765 return static_cast<void *>(RT->getDecl());
1766 }
1767 return static_cast<void *>(Field);
1768}
1769
Anders Carlssonea356fb2010-04-02 05:42:15 +00001770static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1771 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001772}
1773
Anders Carlssonea356fb2010-04-02 05:42:15 +00001774static void *GetKeyForMember(ASTContext &Context,
1775 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001776 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001777 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001778 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001779
Eli Friedman6347f422009-07-21 19:28:10 +00001780 // For fields injected into the class via declaration of an anonymous union,
1781 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001782 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001784 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1785 // data member of the class. Data member used in the initializer list is
1786 // in AnonUnionMember field.
1787 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1788 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001789
John McCall3c3ccdb2010-04-10 09:28:51 +00001790 // If the field is a member of an anonymous struct or union, our key
1791 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001792 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001793 if (RD->isAnonymousStructOrUnion()) {
1794 while (true) {
1795 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1796 if (Parent->isAnonymousStructOrUnion())
1797 RD = Parent;
1798 else
1799 break;
1800 }
1801
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001802 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001803 }
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001805 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001806}
1807
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001808static void
1809DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001810 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001811 CXXBaseOrMemberInitializer **Inits,
1812 unsigned NumInits) {
1813 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001814 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001815
John McCalld6ca8da2010-04-10 07:37:23 +00001816 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1817 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001818 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001819
John McCalld6ca8da2010-04-10 07:37:23 +00001820 // Build the list of bases and members in the order that they'll
1821 // actually be initialized. The explicit initializers should be in
1822 // this same order but may be missing things.
1823 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Anders Carlsson071d6102010-04-02 03:38:04 +00001825 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1826
John McCalld6ca8da2010-04-10 07:37:23 +00001827 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001828 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001829 ClassDecl->vbases_begin(),
1830 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00001831 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001832
John McCalld6ca8da2010-04-10 07:37:23 +00001833 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001834 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001835 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001836 if (Base->isVirtual())
1837 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00001838 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
John McCalld6ca8da2010-04-10 07:37:23 +00001841 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001842 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1843 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00001844 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001845
John McCalld6ca8da2010-04-10 07:37:23 +00001846 unsigned NumIdealInits = IdealInitKeys.size();
1847 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00001848
John McCalld6ca8da2010-04-10 07:37:23 +00001849 CXXBaseOrMemberInitializer *PrevInit = 0;
1850 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1851 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1852 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1853
1854 // Scan forward to try to find this initializer in the idealized
1855 // initializers list.
1856 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1857 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001858 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001859
1860 // If we didn't find this initializer, it must be because we
1861 // scanned past it on a previous iteration. That can only
1862 // happen if we're out of order; emit a warning.
1863 if (IdealIndex == NumIdealInits) {
1864 assert(PrevInit && "initializer not found in initializer list");
1865
1866 Sema::SemaDiagnosticBuilder D =
1867 SemaRef.Diag(PrevInit->getSourceLocation(),
1868 diag::warn_initializer_out_of_order);
1869
1870 if (PrevInit->isMemberInitializer())
1871 D << 0 << PrevInit->getMember()->getDeclName();
1872 else
1873 D << 1 << PrevInit->getBaseClassInfo()->getType();
1874
1875 if (Init->isMemberInitializer())
1876 D << 0 << Init->getMember()->getDeclName();
1877 else
1878 D << 1 << Init->getBaseClassInfo()->getType();
1879
1880 // Move back to the initializer's location in the ideal list.
1881 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1882 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001883 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001884
1885 assert(IdealIndex != NumIdealInits &&
1886 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001887 }
John McCalld6ca8da2010-04-10 07:37:23 +00001888
1889 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001890 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001891}
1892
John McCall3c3ccdb2010-04-10 09:28:51 +00001893namespace {
1894bool CheckRedundantInit(Sema &S,
1895 CXXBaseOrMemberInitializer *Init,
1896 CXXBaseOrMemberInitializer *&PrevInit) {
1897 if (!PrevInit) {
1898 PrevInit = Init;
1899 return false;
1900 }
1901
1902 if (FieldDecl *Field = Init->getMember())
1903 S.Diag(Init->getSourceLocation(),
1904 diag::err_multiple_mem_initialization)
1905 << Field->getDeclName()
1906 << Init->getSourceRange();
1907 else {
1908 Type *BaseClass = Init->getBaseClass();
1909 assert(BaseClass && "neither field nor base");
1910 S.Diag(Init->getSourceLocation(),
1911 diag::err_multiple_base_initialization)
1912 << QualType(BaseClass, 0)
1913 << Init->getSourceRange();
1914 }
1915 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1916 << 0 << PrevInit->getSourceRange();
1917
1918 return true;
1919}
1920
1921typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1922typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1923
1924bool CheckRedundantUnionInit(Sema &S,
1925 CXXBaseOrMemberInitializer *Init,
1926 RedundantUnionMap &Unions) {
1927 FieldDecl *Field = Init->getMember();
1928 RecordDecl *Parent = Field->getParent();
1929 if (!Parent->isAnonymousStructOrUnion())
1930 return false;
1931
1932 NamedDecl *Child = Field;
1933 do {
1934 if (Parent->isUnion()) {
1935 UnionEntry &En = Unions[Parent];
1936 if (En.first && En.first != Child) {
1937 S.Diag(Init->getSourceLocation(),
1938 diag::err_multiple_mem_union_initialization)
1939 << Field->getDeclName()
1940 << Init->getSourceRange();
1941 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1942 << 0 << En.second->getSourceRange();
1943 return true;
1944 } else if (!En.first) {
1945 En.first = Child;
1946 En.second = Init;
1947 }
1948 }
1949
1950 Child = Parent;
1951 Parent = cast<RecordDecl>(Parent->getDeclContext());
1952 } while (Parent->isAnonymousStructOrUnion());
1953
1954 return false;
1955}
1956}
1957
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001958/// ActOnMemInitializers - Handle the member initializers for a constructor.
1959void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1960 SourceLocation ColonLoc,
1961 MemInitTy **meminits, unsigned NumMemInits,
1962 bool AnyErrors) {
1963 if (!ConstructorDecl)
1964 return;
1965
1966 AdjustDeclIfTemplate(ConstructorDecl);
1967
1968 CXXConstructorDecl *Constructor
1969 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1970
1971 if (!Constructor) {
1972 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1973 return;
1974 }
1975
1976 CXXBaseOrMemberInitializer **MemInits =
1977 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00001978
1979 // Mapping for the duplicate initializers check.
1980 // For member initializers, this is keyed with a FieldDecl*.
1981 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001982 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00001983
1984 // Mapping for the inconsistent anonymous-union initializers check.
1985 RedundantUnionMap MemberUnions;
1986
Anders Carlssonea356fb2010-04-02 05:42:15 +00001987 bool HadError = false;
1988 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00001989 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001990
John McCall3c3ccdb2010-04-10 09:28:51 +00001991 if (Init->isMemberInitializer()) {
1992 FieldDecl *Field = Init->getMember();
1993 if (CheckRedundantInit(*this, Init, Members[Field]) ||
1994 CheckRedundantUnionInit(*this, Init, MemberUnions))
1995 HadError = true;
1996 } else {
1997 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
1998 if (CheckRedundantInit(*this, Init, Members[Key]))
1999 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002000 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002001 }
2002
Anders Carlssonea356fb2010-04-02 05:42:15 +00002003 if (HadError)
2004 return;
2005
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002006 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002007
2008 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002009}
2010
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002011void
John McCallef027fe2010-03-16 21:39:52 +00002012Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2013 CXXRecordDecl *ClassDecl) {
2014 // Ignore dependent contexts.
2015 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002016 return;
John McCall58e6f342010-03-16 05:22:47 +00002017
2018 // FIXME: all the access-control diagnostics are positioned on the
2019 // field/base declaration. That's probably good; that said, the
2020 // user might reasonably want to know why the destructor is being
2021 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002022
Anders Carlsson9f853df2009-11-17 04:44:12 +00002023 // Non-static data members.
2024 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2025 E = ClassDecl->field_end(); I != E; ++I) {
2026 FieldDecl *Field = *I;
2027
2028 QualType FieldType = Context.getBaseElementType(Field->getType());
2029
2030 const RecordType* RT = FieldType->getAs<RecordType>();
2031 if (!RT)
2032 continue;
2033
2034 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2035 if (FieldClassDecl->hasTrivialDestructor())
2036 continue;
2037
John McCall58e6f342010-03-16 05:22:47 +00002038 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2039 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002040 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002041 << Field->getDeclName()
2042 << FieldType);
2043
John McCallef027fe2010-03-16 21:39:52 +00002044 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002045 }
2046
John McCall58e6f342010-03-16 05:22:47 +00002047 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2048
Anders Carlsson9f853df2009-11-17 04:44:12 +00002049 // Bases.
2050 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2051 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002052 // Bases are always records in a well-formed non-dependent class.
2053 const RecordType *RT = Base->getType()->getAs<RecordType>();
2054
2055 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002056 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002057 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002058
2059 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002060 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002061 if (BaseClassDecl->hasTrivialDestructor())
2062 continue;
John McCall58e6f342010-03-16 05:22:47 +00002063
2064 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2065
2066 // FIXME: caret should be on the start of the class name
2067 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002068 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002069 << Base->getType()
2070 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002071
John McCallef027fe2010-03-16 21:39:52 +00002072 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002073 }
2074
2075 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002076 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2077 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002078
2079 // Bases are always records in a well-formed non-dependent class.
2080 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2081
2082 // Ignore direct virtual bases.
2083 if (DirectVirtualBases.count(RT))
2084 continue;
2085
Anders Carlsson9f853df2009-11-17 04:44:12 +00002086 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002087 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002088 if (BaseClassDecl->hasTrivialDestructor())
2089 continue;
John McCall58e6f342010-03-16 05:22:47 +00002090
2091 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2092 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002093 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002094 << VBase->getType());
2095
John McCallef027fe2010-03-16 21:39:52 +00002096 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002097 }
2098}
2099
Fariborz Jahanian393612e2009-07-21 22:36:06 +00002100void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002101 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002102 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Mike Stump1eb44332009-09-09 15:08:12 +00002104 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00002105 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002106 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002107}
2108
Mike Stump1eb44332009-09-09 15:08:12 +00002109bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002110 unsigned DiagID, AbstractDiagSelID SelID,
2111 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002112 if (SelID == -1)
2113 return RequireNonAbstractType(Loc, T,
2114 PDiag(DiagID), CurrentRD);
2115 else
2116 return RequireNonAbstractType(Loc, T,
2117 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002118}
2119
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002120bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2121 const PartialDiagnostic &PD,
2122 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002123 if (!getLangOptions().CPlusPlus)
2124 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Anders Carlsson11f21a02009-03-23 19:10:31 +00002126 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002127 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002128 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Ted Kremenek6217b802009-07-29 21:53:49 +00002130 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002131 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002132 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002133 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002135 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002136 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002137 }
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Ted Kremenek6217b802009-07-29 21:53:49 +00002139 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002140 if (!RT)
2141 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
John McCall86ff3082010-02-04 22:26:26 +00002143 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002144
Anders Carlssone65a3c82009-03-24 17:23:42 +00002145 if (CurrentRD && CurrentRD != RD)
2146 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002147
John McCall86ff3082010-02-04 22:26:26 +00002148 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002149 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002150 return false;
2151
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002152 if (!RD->isAbstract())
2153 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002155 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002157 // Check if we've already emitted the list of pure virtual functions for this
2158 // class.
2159 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2160 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002162 CXXFinalOverriderMap FinalOverriders;
2163 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002165 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2166 MEnd = FinalOverriders.end();
2167 M != MEnd;
2168 ++M) {
2169 for (OverridingMethods::iterator SO = M->second.begin(),
2170 SOEnd = M->second.end();
2171 SO != SOEnd; ++SO) {
2172 // C++ [class.abstract]p4:
2173 // A class is abstract if it contains or inherits at least one
2174 // pure virtual function for which the final overrider is pure
2175 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002177 //
2178 if (SO->second.size() != 1)
2179 continue;
2180
2181 if (!SO->second.front().Method->isPure())
2182 continue;
2183
2184 Diag(SO->second.front().Method->getLocation(),
2185 diag::note_pure_virtual_function)
2186 << SO->second.front().Method->getDeclName();
2187 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002188 }
2189
2190 if (!PureVirtualClassDiagSet)
2191 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2192 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002194 return true;
2195}
2196
Anders Carlsson8211eff2009-03-24 01:19:16 +00002197namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002198 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002199 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2200 Sema &SemaRef;
2201 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Anders Carlssone65a3c82009-03-24 17:23:42 +00002203 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002204 bool Invalid = false;
2205
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002206 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2207 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002208 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002209
Anders Carlsson8211eff2009-03-24 01:19:16 +00002210 return Invalid;
2211 }
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Anders Carlssone65a3c82009-03-24 17:23:42 +00002213 public:
2214 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2215 : SemaRef(SemaRef), AbstractClass(ac) {
2216 Visit(SemaRef.Context.getTranslationUnitDecl());
2217 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002218
Anders Carlssone65a3c82009-03-24 17:23:42 +00002219 bool VisitFunctionDecl(const FunctionDecl *FD) {
2220 if (FD->isThisDeclarationADefinition()) {
2221 // No need to do the check if we're in a definition, because it requires
2222 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002223 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002224 return VisitDeclContext(FD);
2225 }
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Anders Carlssone65a3c82009-03-24 17:23:42 +00002227 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002228 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002229 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002230 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2231 diag::err_abstract_type_in_decl,
2232 Sema::AbstractReturnType,
2233 AbstractClass);
2234
Mike Stump1eb44332009-09-09 15:08:12 +00002235 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002236 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002237 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002238 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002239 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002240 VD->getOriginalType(),
2241 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002242 Sema::AbstractParamType,
2243 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002244 }
2245
2246 return Invalid;
2247 }
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Anders Carlssone65a3c82009-03-24 17:23:42 +00002249 bool VisitDecl(const Decl* D) {
2250 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2251 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Anders Carlssone65a3c82009-03-24 17:23:42 +00002253 return false;
2254 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002255 };
2256}
2257
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002258/// \brief Perform semantic checks on a class definition that has been
2259/// completing, introducing implicitly-declared members, checking for
2260/// abstract types, etc.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002261void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002262 if (!Record || Record->isInvalidDecl())
2263 return;
2264
Eli Friedmanff2d8782009-12-16 20:00:27 +00002265 if (!Record->isDependentType())
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002266 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002267
Eli Friedmanff2d8782009-12-16 20:00:27 +00002268 if (Record->isInvalidDecl())
2269 return;
2270
John McCall233a6412010-01-28 07:38:46 +00002271 // Set access bits correctly on the directly-declared conversions.
2272 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2273 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2274 Convs->setAccess(I, (*I)->getAccess());
2275
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002276 // Determine whether we need to check for final overriders. We do
2277 // this either when there are virtual base classes (in which case we
2278 // may end up finding multiple final overriders for a given virtual
2279 // function) or any of the base classes is abstract (in which case
2280 // we might detect that this class is abstract).
2281 bool CheckFinalOverriders = false;
2282 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2283 !Record->isDependentType()) {
2284 if (Record->getNumVBases())
2285 CheckFinalOverriders = true;
2286 else if (!Record->isAbstract()) {
2287 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2288 BEnd = Record->bases_end();
2289 B != BEnd; ++B) {
2290 CXXRecordDecl *BaseDecl
2291 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2292 if (BaseDecl->isAbstract()) {
2293 CheckFinalOverriders = true;
2294 break;
2295 }
2296 }
2297 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002298 }
2299
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002300 if (CheckFinalOverriders) {
2301 CXXFinalOverriderMap FinalOverriders;
2302 Record->getFinalOverriders(FinalOverriders);
2303
2304 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2305 MEnd = FinalOverriders.end();
2306 M != MEnd; ++M) {
2307 for (OverridingMethods::iterator SO = M->second.begin(),
2308 SOEnd = M->second.end();
2309 SO != SOEnd; ++SO) {
2310 assert(SO->second.size() > 0 &&
2311 "All virtual functions have overridding virtual functions");
2312 if (SO->second.size() == 1) {
2313 // C++ [class.abstract]p4:
2314 // A class is abstract if it contains or inherits at least one
2315 // pure virtual function for which the final overrider is pure
2316 // virtual.
2317 if (SO->second.front().Method->isPure())
2318 Record->setAbstract(true);
2319 continue;
2320 }
2321
2322 // C++ [class.virtual]p2:
2323 // In a derived class, if a virtual member function of a base
2324 // class subobject has more than one final overrider the
2325 // program is ill-formed.
2326 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2327 << (NamedDecl *)M->first << Record;
2328 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2329 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2330 OMEnd = SO->second.end();
2331 OM != OMEnd; ++OM)
2332 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2333 << (NamedDecl *)M->first << OM->Method->getParent();
2334
2335 Record->setInvalidDecl();
2336 }
2337 }
2338 }
2339
2340 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002341 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor325e5932010-04-15 00:00:53 +00002342
2343 // If this is not an aggregate type and has no user-declared constructor,
2344 // complain about any non-static data members of reference or const scalar
2345 // type, since they will never get initializers.
2346 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2347 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2348 bool Complained = false;
2349 for (RecordDecl::field_iterator F = Record->field_begin(),
2350 FEnd = Record->field_end();
2351 F != FEnd; ++F) {
2352 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002353 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002354 if (!Complained) {
2355 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2356 << Record->getTagKind() << Record;
2357 Complained = true;
2358 }
2359
2360 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2361 << F->getType()->isReferenceType()
2362 << F->getDeclName();
2363 }
2364 }
2365 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002366}
2367
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002368void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002369 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002370 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002371 SourceLocation RBrac,
2372 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002373 if (!TagDecl)
2374 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Douglas Gregor42af25f2009-05-11 19:58:34 +00002376 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002377
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002378 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002379 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002380 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002381
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002382 CheckCompletedCXXClass(S,
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002383 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002384}
2385
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002386/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2387/// special functions, such as the default constructor, copy
2388/// constructor, or destructor, to the given C++ class (C++
2389/// [special]p1). This routine can only be executed just before the
2390/// definition of the class is complete.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002391///
2392/// The scope, if provided, is the class scope.
2393void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2394 CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002395 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002396 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002397
Sebastian Redl465226e2009-05-27 22:11:52 +00002398 // FIXME: Implicit declarations have exception specifications, which are
2399 // the union of the specifications of the implicitly called functions.
2400
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002401 if (!ClassDecl->hasUserDeclaredConstructor()) {
2402 // C++ [class.ctor]p5:
2403 // A default constructor for a class X is a constructor of class X
2404 // that can be called without an argument. If there is no
2405 // user-declared constructor for class X, a default constructor is
2406 // implicitly declared. An implicitly-declared default constructor
2407 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002408 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002409 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002410 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002411 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002412 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002413 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002414 0, 0, false, 0,
2415 /*FIXME*/false, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002416 0, 0,
2417 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002418 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002419 /*isExplicit=*/false,
2420 /*isInline=*/true,
2421 /*isImplicitlyDeclared=*/true);
2422 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002423 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002424 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002425 if (S)
2426 PushOnScopeChains(DefaultCon, S, true);
2427 else
2428 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002429 }
2430
2431 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2432 // C++ [class.copy]p4:
2433 // If the class definition does not explicitly declare a copy
2434 // constructor, one is declared implicitly.
2435
2436 // C++ [class.copy]p5:
2437 // The implicitly-declared copy constructor for a class X will
2438 // have the form
2439 //
2440 // X::X(const X&)
2441 //
2442 // if
2443 bool HasConstCopyConstructor = true;
2444
2445 // -- each direct or virtual base class B of X has a copy
2446 // constructor whose first parameter is of type const B& or
2447 // const volatile B&, and
2448 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2449 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2450 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002451 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002452 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002453 = BaseClassDecl->hasConstCopyConstructor(Context);
2454 }
2455
2456 // -- for all the nonstatic data members of X that are of a
2457 // class type M (or array thereof), each such class type
2458 // has a copy constructor whose first parameter is of type
2459 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002460 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2461 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002462 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002463 QualType FieldType = (*Field)->getType();
2464 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2465 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002466 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002467 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002468 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002469 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002470 = FieldClassDecl->hasConstCopyConstructor(Context);
2471 }
2472 }
2473
Sebastian Redl64b45f72009-01-05 20:52:13 +00002474 // Otherwise, the implicitly declared copy constructor will have
2475 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002476 //
2477 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002478 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002479 if (HasConstCopyConstructor)
2480 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002481 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002482
Sebastian Redl64b45f72009-01-05 20:52:13 +00002483 // An implicitly-declared copy constructor is an inline public
2484 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002485 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002486 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002487 CXXConstructorDecl *CopyConstructor
2488 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002489 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002490 Context.getFunctionType(Context.VoidTy,
2491 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002492 false, 0,
2493 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002494 false, 0, 0,
2495 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002496 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002497 /*isExplicit=*/false,
2498 /*isInline=*/true,
2499 /*isImplicitlyDeclared=*/true);
2500 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002501 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002502 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002503
2504 // Add the parameter to the constructor.
2505 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2506 ClassDecl->getLocation(),
2507 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002508 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002509 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002510 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002511 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002512 if (S)
2513 PushOnScopeChains(CopyConstructor, S, true);
2514 else
2515 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002516 }
2517
Sebastian Redl64b45f72009-01-05 20:52:13 +00002518 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2519 // Note: The following rules are largely analoguous to the copy
2520 // constructor rules. Note that virtual bases are not taken into account
2521 // for determining the argument type of the operator. Note also that
2522 // operators taking an object instead of a reference are allowed.
2523 //
2524 // C++ [class.copy]p10:
2525 // If the class definition does not explicitly declare a copy
2526 // assignment operator, one is declared implicitly.
2527 // The implicitly-defined copy assignment operator for a class X
2528 // will have the form
2529 //
2530 // X& X::operator=(const X&)
2531 //
2532 // if
2533 bool HasConstCopyAssignment = true;
2534
2535 // -- each direct base class B of X has a copy assignment operator
2536 // whose parameter is of type const B&, const volatile B& or B,
2537 // and
2538 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2539 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002540 assert(!Base->getType()->isDependentType() &&
2541 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002542 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002543 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002544 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002545 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002546 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002547 }
2548
2549 // -- for all the nonstatic data members of X that are of a class
2550 // type M (or array thereof), each such class type has a copy
2551 // assignment operator whose parameter is of type const M&,
2552 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002553 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2554 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002555 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002556 QualType FieldType = (*Field)->getType();
2557 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2558 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002559 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002560 const CXXRecordDecl *FieldClassDecl
2561 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002562 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002563 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002564 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002565 }
2566 }
2567
2568 // Otherwise, the implicitly declared copy assignment operator will
2569 // have the form
2570 //
2571 // X& X::operator=(X&)
2572 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002573 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002574 if (HasConstCopyAssignment)
2575 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002576 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002577
2578 // An implicitly-declared copy assignment operator is an inline public
2579 // member of its class.
2580 DeclarationName Name =
2581 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2582 CXXMethodDecl *CopyAssignment =
2583 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2584 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002585 false, 0,
2586 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002587 false, 0, 0,
2588 FunctionType::ExtInfo()),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002589 /*TInfo=*/0, /*isStatic=*/false,
2590 /*StorageClassAsWritten=*/FunctionDecl::None,
2591 /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002592 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002593 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002594 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002595 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002596
2597 // Add the parameter to the operator.
2598 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2599 ClassDecl->getLocation(),
2600 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002601 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002602 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002603 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002604 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002605
2606 // Don't call addedAssignmentOperator. There is no way to distinguish an
2607 // implicit from an explicit assignment operator.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002608 if (S)
2609 PushOnScopeChains(CopyAssignment, S, true);
2610 else
2611 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002612 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002613 }
2614
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002615 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002616 // C++ [class.dtor]p2:
2617 // If a class has no user-declared destructor, a destructor is
2618 // declared implicitly. An implicitly-declared destructor is an
2619 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002620 QualType Ty = Context.getFunctionType(Context.VoidTy,
2621 0, 0, false, 0,
2622 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002623 false, 0, 0, FunctionType::ExtInfo());
John McCall21ef0fa2010-03-11 09:03:00 +00002624
Mike Stump1eb44332009-09-09 15:08:12 +00002625 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002626 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002627 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002628 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002629 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002630 /*isInline=*/true,
2631 /*isImplicitlyDeclared=*/true);
2632 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002633 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002634 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002635 if (S)
2636 PushOnScopeChains(Destructor, S, true);
2637 else
2638 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002639
2640 // This could be uniqued if it ever proves significant.
2641 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002642
2643 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002644 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002645}
2646
Douglas Gregor6569d682009-05-27 23:11:45 +00002647void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002648 Decl *D = TemplateD.getAs<Decl>();
2649 if (!D)
2650 return;
2651
2652 TemplateParameterList *Params = 0;
2653 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2654 Params = Template->getTemplateParameters();
2655 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2656 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2657 Params = PartialSpec->getTemplateParameters();
2658 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002659 return;
2660
Douglas Gregor6569d682009-05-27 23:11:45 +00002661 for (TemplateParameterList::iterator Param = Params->begin(),
2662 ParamEnd = Params->end();
2663 Param != ParamEnd; ++Param) {
2664 NamedDecl *Named = cast<NamedDecl>(*Param);
2665 if (Named->getDeclName()) {
2666 S->AddDecl(DeclPtrTy::make(Named));
2667 IdResolver.AddDecl(Named);
2668 }
2669 }
2670}
2671
John McCall7a1dc562009-12-19 10:49:29 +00002672void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2673 if (!RecordD) return;
2674 AdjustDeclIfTemplate(RecordD);
2675 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2676 PushDeclContext(S, Record);
2677}
2678
2679void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2680 if (!RecordD) return;
2681 PopDeclContext();
2682}
2683
Douglas Gregor72b505b2008-12-16 21:30:33 +00002684/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2685/// parsing a top-level (non-nested) C++ class, and we are now
2686/// parsing those parts of the given Method declaration that could
2687/// not be parsed earlier (C++ [class.mem]p2), such as default
2688/// arguments. This action should enter the scope of the given
2689/// Method declaration as if we had just parsed the qualified method
2690/// name. However, it should not bring the parameters into scope;
2691/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002692void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002693}
2694
2695/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2696/// C++ method declaration. We're (re-)introducing the given
2697/// function parameter into scope for use in parsing later parts of
2698/// the method declaration. For example, we could see an
2699/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002700void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002701 if (!ParamD)
2702 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Chris Lattnerb28317a2009-03-28 19:18:32 +00002704 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002705
2706 // If this parameter has an unparsed default argument, clear it out
2707 // to make way for the parsed default argument.
2708 if (Param->hasUnparsedDefaultArg())
2709 Param->setDefaultArg(0);
2710
Chris Lattnerb28317a2009-03-28 19:18:32 +00002711 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002712 if (Param->getDeclName())
2713 IdResolver.AddDecl(Param);
2714}
2715
2716/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2717/// processing the delayed method declaration for Method. The method
2718/// declaration is now considered finished. There may be a separate
2719/// ActOnStartOfFunctionDef action later (not necessarily
2720/// immediately!) for this method, if it was also defined inside the
2721/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002722void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002723 if (!MethodD)
2724 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002726 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Chris Lattnerb28317a2009-03-28 19:18:32 +00002728 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002729
2730 // Now that we have our default arguments, check the constructor
2731 // again. It could produce additional diagnostics or affect whether
2732 // the class has implicitly-declared destructors, among other
2733 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002734 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2735 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002736
2737 // Check the default arguments, which we may have added.
2738 if (!Method->isInvalidDecl())
2739 CheckCXXDefaultArguments(Method);
2740}
2741
Douglas Gregor42a552f2008-11-05 20:51:48 +00002742/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002743/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002744/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002745/// emit diagnostics and set the invalid bit to true. In any case, the type
2746/// will be updated to reflect a well-formed type for the constructor and
2747/// returned.
2748QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2749 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002750 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002751
2752 // C++ [class.ctor]p3:
2753 // A constructor shall not be virtual (10.3) or static (9.4). A
2754 // constructor can be invoked for a const, volatile or const
2755 // volatile object. A constructor shall not be declared const,
2756 // volatile, or const volatile (9.3.2).
2757 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002758 if (!D.isInvalidType())
2759 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2760 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2761 << SourceRange(D.getIdentifierLoc());
2762 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002763 }
2764 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002765 if (!D.isInvalidType())
2766 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2767 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2768 << SourceRange(D.getIdentifierLoc());
2769 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002770 SC = FunctionDecl::None;
2771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Chris Lattner65401802009-04-25 08:28:21 +00002773 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2774 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002775 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002776 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2777 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002778 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002779 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2780 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002781 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002782 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2783 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002784 }
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Douglas Gregor42a552f2008-11-05 20:51:48 +00002786 // Rebuild the function type "R" without any type qualifiers (in
2787 // case any of the errors above fired) and with "void" as the
2788 // return type, since constructors don't have return types. We
2789 // *always* have to do this, because GetTypeForDeclarator will
2790 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002791 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002792 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2793 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002794 Proto->isVariadic(), 0,
2795 Proto->hasExceptionSpec(),
2796 Proto->hasAnyExceptionSpec(),
2797 Proto->getNumExceptions(),
2798 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002799 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002800}
2801
Douglas Gregor72b505b2008-12-16 21:30:33 +00002802/// CheckConstructor - Checks a fully-formed constructor for
2803/// well-formedness, issuing any diagnostics required. Returns true if
2804/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002805void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002806 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002807 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2808 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002809 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002810
2811 // C++ [class.copy]p3:
2812 // A declaration of a constructor for a class X is ill-formed if
2813 // its first parameter is of type (optionally cv-qualified) X and
2814 // either there are no other parameters or else all other
2815 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002816 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002817 ((Constructor->getNumParams() == 1) ||
2818 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002819 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2820 Constructor->getTemplateSpecializationKind()
2821 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002822 QualType ParamType = Constructor->getParamDecl(0)->getType();
2823 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2824 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002825 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2826 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor849b2432010-03-31 17:46:05 +00002827 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002828
2829 // FIXME: Rather that making the constructor invalid, we should endeavor
2830 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002831 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002832 }
2833 }
Mike Stump1eb44332009-09-09 15:08:12 +00002834
John McCall3d043362010-04-13 07:45:41 +00002835 // Notify the class that we've added a constructor. In principle we
2836 // don't need to do this for out-of-line declarations; in practice
2837 // we only instantiate the most recent declaration of a method, so
2838 // we have to call this for everything but friends.
2839 if (!Constructor->getFriendObjectKind())
2840 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002841}
2842
Anders Carlsson37909802009-11-30 21:24:50 +00002843/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2844/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002845bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002846 CXXRecordDecl *RD = Destructor->getParent();
2847
2848 if (Destructor->isVirtual()) {
2849 SourceLocation Loc;
2850
2851 if (!Destructor->isImplicit())
2852 Loc = Destructor->getLocation();
2853 else
2854 Loc = RD->getLocation();
2855
2856 // If we have a virtual destructor, look up the deallocation function
2857 FunctionDecl *OperatorDelete = 0;
2858 DeclarationName Name =
2859 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002860 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002861 return true;
2862
2863 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002864 }
Anders Carlsson37909802009-11-30 21:24:50 +00002865
2866 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002867}
2868
Mike Stump1eb44332009-09-09 15:08:12 +00002869static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002870FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2871 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2872 FTI.ArgInfo[0].Param &&
2873 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2874}
2875
Douglas Gregor42a552f2008-11-05 20:51:48 +00002876/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2877/// the well-formednes of the destructor declarator @p D with type @p
2878/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002879/// emit diagnostics and set the declarator to invalid. Even if this happens,
2880/// will be updated to reflect a well-formed type for the destructor and
2881/// returned.
2882QualType Sema::CheckDestructorDeclarator(Declarator &D,
2883 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002884 // C++ [class.dtor]p1:
2885 // [...] A typedef-name that names a class is a class-name
2886 // (7.1.3); however, a typedef-name that names a class shall not
2887 // be used as the identifier in the declarator for a destructor
2888 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002889 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002890 if (isa<TypedefType>(DeclaratorType)) {
2891 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002892 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002893 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002894 }
2895
2896 // C++ [class.dtor]p2:
2897 // A destructor is used to destroy objects of its class type. A
2898 // destructor takes no parameters, and no return type can be
2899 // specified for it (not even void). The address of a destructor
2900 // shall not be taken. A destructor shall not be static. A
2901 // destructor can be invoked for a const, volatile or const
2902 // volatile object. A destructor shall not be declared const,
2903 // volatile or const volatile (9.3.2).
2904 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002905 if (!D.isInvalidType())
2906 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2907 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2908 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002909 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002910 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002911 }
Chris Lattner65401802009-04-25 08:28:21 +00002912 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002913 // Destructors don't have return types, but the parser will
2914 // happily parse something like:
2915 //
2916 // class X {
2917 // float ~X();
2918 // };
2919 //
2920 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002921 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2922 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2923 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
Chris Lattner65401802009-04-25 08:28:21 +00002926 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2927 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002928 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002929 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2930 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002931 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002932 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2933 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002934 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002935 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2936 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002937 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002938 }
2939
2940 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002941 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002942 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2943
2944 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002945 FTI.freeArgs();
2946 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002947 }
2948
Mike Stump1eb44332009-09-09 15:08:12 +00002949 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002950 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002951 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002952 D.setInvalidType();
2953 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002954
2955 // Rebuild the function type "R" without any type qualifiers or
2956 // parameters (in case any of the errors above fired) and with
2957 // "void" as the return type, since destructors don't have return
2958 // types. We *always* have to do this, because GetTypeForDeclarator
2959 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002960 // FIXME: Exceptions!
2961 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002962 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002963}
2964
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002965/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2966/// well-formednes of the conversion function declarator @p D with
2967/// type @p R. If there are any errors in the declarator, this routine
2968/// will emit diagnostics and return true. Otherwise, it will return
2969/// false. Either way, the type @p R will be updated to reflect a
2970/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002971void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002972 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002973 // C++ [class.conv.fct]p1:
2974 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002975 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002976 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002977 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002978 if (!D.isInvalidType())
2979 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2980 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2981 << SourceRange(D.getIdentifierLoc());
2982 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002983 SC = FunctionDecl::None;
2984 }
John McCalla3f81372010-04-13 00:04:31 +00002985
2986 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2987
Chris Lattner6e475012009-04-25 08:35:12 +00002988 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002989 // Conversion functions don't have return types, but the parser will
2990 // happily parse something like:
2991 //
2992 // class X {
2993 // float operator bool();
2994 // };
2995 //
2996 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002997 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2998 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2999 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003000 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003001 }
3002
John McCalla3f81372010-04-13 00:04:31 +00003003 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3004
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003005 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003006 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003007 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3008
3009 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003010 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003011 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003012 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003013 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003014 D.setInvalidType();
3015 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003016
John McCalla3f81372010-04-13 00:04:31 +00003017 // Diagnose "&operator bool()" and other such nonsense. This
3018 // is actually a gcc extension which we don't support.
3019 if (Proto->getResultType() != ConvType) {
3020 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3021 << Proto->getResultType();
3022 D.setInvalidType();
3023 ConvType = Proto->getResultType();
3024 }
3025
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003026 // C++ [class.conv.fct]p4:
3027 // The conversion-type-id shall not represent a function type nor
3028 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003029 if (ConvType->isArrayType()) {
3030 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3031 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003032 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003033 } else if (ConvType->isFunctionType()) {
3034 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3035 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003036 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003037 }
3038
3039 // Rebuild the function type "R" without any parameters (in case any
3040 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003041 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003042 if (D.isInvalidType()) {
3043 R = Context.getFunctionType(ConvType, 0, 0, false,
3044 Proto->getTypeQuals(),
3045 Proto->hasExceptionSpec(),
3046 Proto->hasAnyExceptionSpec(),
3047 Proto->getNumExceptions(),
3048 Proto->exception_begin(),
3049 Proto->getExtInfo());
3050 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003051
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003052 // C++0x explicit conversion operators.
3053 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003054 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003055 diag::warn_explicit_conversion_functions)
3056 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003057}
3058
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003059/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3060/// the declaration of the given C++ conversion function. This routine
3061/// is responsible for recording the conversion function in the C++
3062/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003063Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003064 assert(Conversion && "Expected to receive a conversion function declaration");
3065
Douglas Gregor9d350972008-12-12 08:25:50 +00003066 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003067
3068 // Make sure we aren't redeclaring the conversion function.
3069 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003070
3071 // C++ [class.conv.fct]p1:
3072 // [...] A conversion function is never used to convert a
3073 // (possibly cv-qualified) object to the (possibly cv-qualified)
3074 // same object type (or a reference to it), to a (possibly
3075 // cv-qualified) base class of that type (or a reference to it),
3076 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003077 // FIXME: Suppress this warning if the conversion function ends up being a
3078 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003079 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003080 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003081 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003082 ConvType = ConvTypeRef->getPointeeType();
3083 if (ConvType->isRecordType()) {
3084 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3085 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003086 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003087 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003088 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003089 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003090 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003091 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003092 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003093 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003094 }
3095
Douglas Gregor48026d22010-01-11 18:40:55 +00003096 if (Conversion->getPrimaryTemplate()) {
3097 // ignore specializations
3098 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003099 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003100 = Conversion->getDescribedFunctionTemplate()) {
3101 if (ClassDecl->replaceConversion(
3102 ConversionTemplate->getPreviousDeclaration(),
3103 ConversionTemplate))
3104 return DeclPtrTy::make(ConversionTemplate);
3105 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3106 Conversion))
John McCallba135432009-11-21 08:51:07 +00003107 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00003108 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003109 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003110 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003111 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003112 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003113 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003114
Chris Lattnerb28317a2009-03-28 19:18:32 +00003115 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003116}
3117
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003118//===----------------------------------------------------------------------===//
3119// Namespace Handling
3120//===----------------------------------------------------------------------===//
3121
3122/// ActOnStartNamespaceDef - This is called at the start of a namespace
3123/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003124Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3125 SourceLocation IdentLoc,
3126 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003127 SourceLocation LBrace,
3128 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003129 NamespaceDecl *Namespc =
3130 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3131 Namespc->setLBracLoc(LBrace);
3132
3133 Scope *DeclRegionScope = NamespcScope->getParent();
3134
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003135 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3136
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003137 if (II) {
3138 // C++ [namespace.def]p2:
3139 // The identifier in an original-namespace-definition shall not have been
3140 // previously defined in the declarative region in which the
3141 // original-namespace-definition appears. The identifier in an
3142 // original-namespace-definition is the name of the namespace. Subsequently
3143 // in that declarative region, it is treated as an original-namespace-name.
3144
John McCallf36e02d2009-10-09 21:13:30 +00003145 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003146 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003147 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003148
Douglas Gregor44b43212008-12-11 16:49:14 +00003149 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3150 // This is an extended namespace definition.
3151 // Attach this namespace decl to the chain of extended namespace
3152 // definitions.
3153 OrigNS->setNextNamespace(Namespc);
3154 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003155
Mike Stump1eb44332009-09-09 15:08:12 +00003156 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003157 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003158 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003159 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003160 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003161 } else if (PrevDecl) {
3162 // This is an invalid name redefinition.
3163 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3164 << Namespc->getDeclName();
3165 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3166 Namespc->setInvalidDecl();
3167 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003168 } else if (II->isStr("std") &&
3169 CurContext->getLookupContext()->isTranslationUnit()) {
3170 // This is the first "real" definition of the namespace "std", so update
3171 // our cache of the "std" namespace to point at this definition.
3172 if (StdNamespace) {
3173 // We had already defined a dummy namespace "std". Link this new
3174 // namespace definition to the dummy namespace "std".
3175 StdNamespace->setNextNamespace(Namespc);
3176 StdNamespace->setLocation(IdentLoc);
3177 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3178 }
3179
3180 // Make our StdNamespace cache point at the first real definition of the
3181 // "std" namespace.
3182 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003183 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003184
3185 PushOnScopeChains(Namespc, DeclRegionScope);
3186 } else {
John McCall9aeed322009-10-01 00:25:31 +00003187 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003188 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003189
3190 // Link the anonymous namespace into its parent.
3191 NamespaceDecl *PrevDecl;
3192 DeclContext *Parent = CurContext->getLookupContext();
3193 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3194 PrevDecl = TU->getAnonymousNamespace();
3195 TU->setAnonymousNamespace(Namespc);
3196 } else {
3197 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3198 PrevDecl = ND->getAnonymousNamespace();
3199 ND->setAnonymousNamespace(Namespc);
3200 }
3201
3202 // Link the anonymous namespace with its previous declaration.
3203 if (PrevDecl) {
3204 assert(PrevDecl->isAnonymousNamespace());
3205 assert(!PrevDecl->getNextNamespace());
3206 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3207 PrevDecl->setNextNamespace(Namespc);
3208 }
John McCall9aeed322009-10-01 00:25:31 +00003209
Douglas Gregora4181472010-03-24 00:46:35 +00003210 CurContext->addDecl(Namespc);
3211
John McCall9aeed322009-10-01 00:25:31 +00003212 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3213 // behaves as if it were replaced by
3214 // namespace unique { /* empty body */ }
3215 // using namespace unique;
3216 // namespace unique { namespace-body }
3217 // where all occurrences of 'unique' in a translation unit are
3218 // replaced by the same identifier and this identifier differs
3219 // from all other identifiers in the entire program.
3220
3221 // We just create the namespace with an empty name and then add an
3222 // implicit using declaration, just like the standard suggests.
3223 //
3224 // CodeGen enforces the "universally unique" aspect by giving all
3225 // declarations semantically contained within an anonymous
3226 // namespace internal linkage.
3227
John McCall5fdd7642009-12-16 02:06:49 +00003228 if (!PrevDecl) {
3229 UsingDirectiveDecl* UD
3230 = UsingDirectiveDecl::Create(Context, CurContext,
3231 /* 'using' */ LBrace,
3232 /* 'namespace' */ SourceLocation(),
3233 /* qualifier */ SourceRange(),
3234 /* NNS */ NULL,
3235 /* identifier */ SourceLocation(),
3236 Namespc,
3237 /* Ancestor */ CurContext);
3238 UD->setImplicit();
3239 CurContext->addDecl(UD);
3240 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003241 }
3242
3243 // Although we could have an invalid decl (i.e. the namespace name is a
3244 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003245 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3246 // for the namespace has the declarations that showed up in that particular
3247 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003248 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003249 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003250}
3251
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003252/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3253/// is a namespace alias, returns the namespace it points to.
3254static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3255 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3256 return AD->getNamespace();
3257 return dyn_cast_or_null<NamespaceDecl>(D);
3258}
3259
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003260/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3261/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003262void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3263 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003264 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3265 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3266 Namespc->setRBracLoc(RBrace);
3267 PopDeclContext();
3268}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003269
Chris Lattnerb28317a2009-03-28 19:18:32 +00003270Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3271 SourceLocation UsingLoc,
3272 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003273 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003274 SourceLocation IdentLoc,
3275 IdentifierInfo *NamespcName,
3276 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003277 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3278 assert(NamespcName && "Invalid NamespcName.");
3279 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003280 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003281
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003282 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003283
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003284 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003285 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3286 LookupParsedName(R, S, &SS);
3287 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003288 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003289
John McCallf36e02d2009-10-09 21:13:30 +00003290 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003291 NamedDecl *Named = R.getFoundDecl();
3292 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3293 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003294 // C++ [namespace.udir]p1:
3295 // A using-directive specifies that the names in the nominated
3296 // namespace can be used in the scope in which the
3297 // using-directive appears after the using-directive. During
3298 // unqualified name lookup (3.4.1), the names appear as if they
3299 // were declared in the nearest enclosing namespace which
3300 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003301 // namespace. [Note: in this context, "contains" means "contains
3302 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003303
3304 // Find enclosing context containing both using-directive and
3305 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003306 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003307 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3308 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3309 CommonAncestor = CommonAncestor->getParent();
3310
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003311 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003312 SS.getRange(),
3313 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003314 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003315 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003316 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003317 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003318 }
3319
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003320 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003321 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003322 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003323}
3324
3325void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3326 // If scope has associated entity, then using directive is at namespace
3327 // or translation unit scope. We add UsingDirectiveDecls, into
3328 // it's lookup structure.
3329 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003330 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003331 else
3332 // Otherwise it is block-sope. using-directives will affect lookup
3333 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003334 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003335}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003336
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003337
3338Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003339 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003340 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003341 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003342 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003343 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003344 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003345 bool IsTypeName,
3346 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003347 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Douglas Gregor12c118a2009-11-04 16:30:06 +00003349 switch (Name.getKind()) {
3350 case UnqualifiedId::IK_Identifier:
3351 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003352 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003353 case UnqualifiedId::IK_ConversionFunctionId:
3354 break;
3355
3356 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003357 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003358 // C++0x inherited constructors.
3359 if (getLangOptions().CPlusPlus0x) break;
3360
Douglas Gregor12c118a2009-11-04 16:30:06 +00003361 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3362 << SS.getRange();
3363 return DeclPtrTy();
3364
3365 case UnqualifiedId::IK_DestructorName:
3366 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3367 << SS.getRange();
3368 return DeclPtrTy();
3369
3370 case UnqualifiedId::IK_TemplateId:
3371 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3372 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3373 return DeclPtrTy();
3374 }
3375
3376 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003377 if (!TargetName)
3378 return DeclPtrTy();
3379
John McCall60fa3cf2009-12-11 02:10:03 +00003380 // Warn about using declarations.
3381 // TODO: store that the declaration was written without 'using' and
3382 // talk about access decls instead of using decls in the
3383 // diagnostics.
3384 if (!HasUsingKeyword) {
3385 UsingLoc = Name.getSourceRange().getBegin();
3386
3387 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003388 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003389 }
3390
John McCall9488ea12009-11-17 05:59:44 +00003391 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003392 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003393 TargetName, AttrList,
3394 /* IsInstantiation */ false,
3395 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003396 if (UD)
3397 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Anders Carlssonc72160b2009-08-28 05:40:36 +00003399 return DeclPtrTy::make(UD);
3400}
3401
John McCall9f54ad42009-12-10 09:41:52 +00003402/// Determines whether to create a using shadow decl for a particular
3403/// decl, given the set of decls existing prior to this using lookup.
3404bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3405 const LookupResult &Previous) {
3406 // Diagnose finding a decl which is not from a base class of the
3407 // current class. We do this now because there are cases where this
3408 // function will silently decide not to build a shadow decl, which
3409 // will pre-empt further diagnostics.
3410 //
3411 // We don't need to do this in C++0x because we do the check once on
3412 // the qualifier.
3413 //
3414 // FIXME: diagnose the following if we care enough:
3415 // struct A { int foo; };
3416 // struct B : A { using A::foo; };
3417 // template <class T> struct C : A {};
3418 // template <class T> struct D : C<T> { using B::foo; } // <---
3419 // This is invalid (during instantiation) in C++03 because B::foo
3420 // resolves to the using decl in B, which is not a base class of D<T>.
3421 // We can't diagnose it immediately because C<T> is an unknown
3422 // specialization. The UsingShadowDecl in D<T> then points directly
3423 // to A::foo, which will look well-formed when we instantiate.
3424 // The right solution is to not collapse the shadow-decl chain.
3425 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3426 DeclContext *OrigDC = Orig->getDeclContext();
3427
3428 // Handle enums and anonymous structs.
3429 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3430 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3431 while (OrigRec->isAnonymousStructOrUnion())
3432 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3433
3434 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3435 if (OrigDC == CurContext) {
3436 Diag(Using->getLocation(),
3437 diag::err_using_decl_nested_name_specifier_is_current_class)
3438 << Using->getNestedNameRange();
3439 Diag(Orig->getLocation(), diag::note_using_decl_target);
3440 return true;
3441 }
3442
3443 Diag(Using->getNestedNameRange().getBegin(),
3444 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3445 << Using->getTargetNestedNameDecl()
3446 << cast<CXXRecordDecl>(CurContext)
3447 << Using->getNestedNameRange();
3448 Diag(Orig->getLocation(), diag::note_using_decl_target);
3449 return true;
3450 }
3451 }
3452
3453 if (Previous.empty()) return false;
3454
3455 NamedDecl *Target = Orig;
3456 if (isa<UsingShadowDecl>(Target))
3457 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3458
John McCalld7533ec2009-12-11 02:33:26 +00003459 // If the target happens to be one of the previous declarations, we
3460 // don't have a conflict.
3461 //
3462 // FIXME: but we might be increasing its access, in which case we
3463 // should redeclare it.
3464 NamedDecl *NonTag = 0, *Tag = 0;
3465 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3466 I != E; ++I) {
3467 NamedDecl *D = (*I)->getUnderlyingDecl();
3468 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3469 return false;
3470
3471 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3472 }
3473
John McCall9f54ad42009-12-10 09:41:52 +00003474 if (Target->isFunctionOrFunctionTemplate()) {
3475 FunctionDecl *FD;
3476 if (isa<FunctionTemplateDecl>(Target))
3477 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3478 else
3479 FD = cast<FunctionDecl>(Target);
3480
3481 NamedDecl *OldDecl = 0;
3482 switch (CheckOverload(FD, Previous, OldDecl)) {
3483 case Ovl_Overload:
3484 return false;
3485
3486 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003487 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003488 break;
3489
3490 // We found a decl with the exact signature.
3491 case Ovl_Match:
3492 if (isa<UsingShadowDecl>(OldDecl)) {
3493 // Silently ignore the possible conflict.
3494 return false;
3495 }
3496
3497 // If we're in a record, we want to hide the target, so we
3498 // return true (without a diagnostic) to tell the caller not to
3499 // build a shadow decl.
3500 if (CurContext->isRecord())
3501 return true;
3502
3503 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003504 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003505 break;
3506 }
3507
3508 Diag(Target->getLocation(), diag::note_using_decl_target);
3509 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3510 return true;
3511 }
3512
3513 // Target is not a function.
3514
John McCall9f54ad42009-12-10 09:41:52 +00003515 if (isa<TagDecl>(Target)) {
3516 // No conflict between a tag and a non-tag.
3517 if (!Tag) return false;
3518
John McCall41ce66f2009-12-10 19:51:03 +00003519 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003520 Diag(Target->getLocation(), diag::note_using_decl_target);
3521 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3522 return true;
3523 }
3524
3525 // No conflict between a tag and a non-tag.
3526 if (!NonTag) return false;
3527
John McCall41ce66f2009-12-10 19:51:03 +00003528 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003529 Diag(Target->getLocation(), diag::note_using_decl_target);
3530 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3531 return true;
3532}
3533
John McCall9488ea12009-11-17 05:59:44 +00003534/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003535UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003536 UsingDecl *UD,
3537 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003538
3539 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003540 NamedDecl *Target = Orig;
3541 if (isa<UsingShadowDecl>(Target)) {
3542 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3543 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003544 }
3545
3546 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003547 = UsingShadowDecl::Create(Context, CurContext,
3548 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003549 UD->addShadowDecl(Shadow);
3550
3551 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003552 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003553 else
John McCall604e7f12009-12-08 07:46:18 +00003554 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003555 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003556
John McCall32daa422010-03-31 01:36:47 +00003557 // Register it as a conversion if appropriate.
3558 if (Shadow->getDeclName().getNameKind()
3559 == DeclarationName::CXXConversionFunctionName)
3560 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3561
John McCall604e7f12009-12-08 07:46:18 +00003562 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3563 Shadow->setInvalidDecl();
3564
John McCall9f54ad42009-12-10 09:41:52 +00003565 return Shadow;
3566}
John McCall604e7f12009-12-08 07:46:18 +00003567
John McCall9f54ad42009-12-10 09:41:52 +00003568/// Hides a using shadow declaration. This is required by the current
3569/// using-decl implementation when a resolvable using declaration in a
3570/// class is followed by a declaration which would hide or override
3571/// one or more of the using decl's targets; for example:
3572///
3573/// struct Base { void foo(int); };
3574/// struct Derived : Base {
3575/// using Base::foo;
3576/// void foo(int);
3577/// };
3578///
3579/// The governing language is C++03 [namespace.udecl]p12:
3580///
3581/// When a using-declaration brings names from a base class into a
3582/// derived class scope, member functions in the derived class
3583/// override and/or hide member functions with the same name and
3584/// parameter types in a base class (rather than conflicting).
3585///
3586/// There are two ways to implement this:
3587/// (1) optimistically create shadow decls when they're not hidden
3588/// by existing declarations, or
3589/// (2) don't create any shadow decls (or at least don't make them
3590/// visible) until we've fully parsed/instantiated the class.
3591/// The problem with (1) is that we might have to retroactively remove
3592/// a shadow decl, which requires several O(n) operations because the
3593/// decl structures are (very reasonably) not designed for removal.
3594/// (2) avoids this but is very fiddly and phase-dependent.
3595void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003596 if (Shadow->getDeclName().getNameKind() ==
3597 DeclarationName::CXXConversionFunctionName)
3598 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3599
John McCall9f54ad42009-12-10 09:41:52 +00003600 // Remove it from the DeclContext...
3601 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003602
John McCall9f54ad42009-12-10 09:41:52 +00003603 // ...and the scope, if applicable...
3604 if (S) {
3605 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3606 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003607 }
3608
John McCall9f54ad42009-12-10 09:41:52 +00003609 // ...and the using decl.
3610 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3611
3612 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003613 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003614}
3615
John McCall7ba107a2009-11-18 02:36:19 +00003616/// Builds a using declaration.
3617///
3618/// \param IsInstantiation - Whether this call arises from an
3619/// instantiation of an unresolved using declaration. We treat
3620/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003621NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3622 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003623 CXXScopeSpec &SS,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003624 SourceLocation IdentLoc,
3625 DeclarationName Name,
3626 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003627 bool IsInstantiation,
3628 bool IsTypeName,
3629 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003630 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3631 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003632
Anders Carlsson550b14b2009-08-28 05:49:21 +00003633 // FIXME: We ignore attributes for now.
3634 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003636 if (SS.isEmpty()) {
3637 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003638 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
John McCall9f54ad42009-12-10 09:41:52 +00003641 // Do the redeclaration lookup in the current scope.
3642 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3643 ForRedeclaration);
3644 Previous.setHideTags(false);
3645 if (S) {
3646 LookupName(Previous, S);
3647
3648 // It is really dumb that we have to do this.
3649 LookupResult::Filter F = Previous.makeFilter();
3650 while (F.hasNext()) {
3651 NamedDecl *D = F.next();
3652 if (!isDeclInScope(D, CurContext, S))
3653 F.erase();
3654 }
3655 F.done();
3656 } else {
3657 assert(IsInstantiation && "no scope in non-instantiation");
3658 assert(CurContext->isRecord() && "scope not record in instantiation");
3659 LookupQualifiedName(Previous, CurContext);
3660 }
3661
Mike Stump1eb44332009-09-09 15:08:12 +00003662 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003663 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3664
John McCall9f54ad42009-12-10 09:41:52 +00003665 // Check for invalid redeclarations.
3666 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3667 return 0;
3668
3669 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003670 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3671 return 0;
3672
John McCallaf8e6ed2009-11-12 03:15:40 +00003673 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003674 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003675 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003676 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003677 // FIXME: not all declaration name kinds are legal here
3678 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3679 UsingLoc, TypenameLoc,
3680 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003681 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003682 } else {
3683 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3684 UsingLoc, SS.getRange(), NNS,
3685 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003686 }
John McCalled976492009-12-04 22:46:56 +00003687 } else {
3688 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3689 SS.getRange(), UsingLoc, NNS, Name,
3690 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003691 }
John McCalled976492009-12-04 22:46:56 +00003692 D->setAccess(AS);
3693 CurContext->addDecl(D);
3694
3695 if (!LookupContext) return D;
3696 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003697
John McCall604e7f12009-12-08 07:46:18 +00003698 if (RequireCompleteDeclContext(SS)) {
3699 UD->setInvalidDecl();
3700 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003701 }
3702
John McCall604e7f12009-12-08 07:46:18 +00003703 // Look up the target name.
3704
John McCalla24dc2e2009-11-17 02:14:36 +00003705 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003706
John McCall604e7f12009-12-08 07:46:18 +00003707 // Unlike most lookups, we don't always want to hide tag
3708 // declarations: tag names are visible through the using declaration
3709 // even if hidden by ordinary names, *except* in a dependent context
3710 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003711 if (!IsInstantiation)
3712 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003713
John McCalla24dc2e2009-11-17 02:14:36 +00003714 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003715
John McCallf36e02d2009-10-09 21:13:30 +00003716 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003717 Diag(IdentLoc, diag::err_no_member)
3718 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003719 UD->setInvalidDecl();
3720 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003721 }
3722
John McCalled976492009-12-04 22:46:56 +00003723 if (R.isAmbiguous()) {
3724 UD->setInvalidDecl();
3725 return UD;
3726 }
Mike Stump1eb44332009-09-09 15:08:12 +00003727
John McCall7ba107a2009-11-18 02:36:19 +00003728 if (IsTypeName) {
3729 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003730 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003731 Diag(IdentLoc, diag::err_using_typename_non_type);
3732 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3733 Diag((*I)->getUnderlyingDecl()->getLocation(),
3734 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003735 UD->setInvalidDecl();
3736 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003737 }
3738 } else {
3739 // If we asked for a non-typename and we got a type, error out,
3740 // but only if this is an instantiation of an unresolved using
3741 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003742 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003743 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3744 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003745 UD->setInvalidDecl();
3746 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003747 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003748 }
3749
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003750 // C++0x N2914 [namespace.udecl]p6:
3751 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003752 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003753 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3754 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003755 UD->setInvalidDecl();
3756 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003757 }
Mike Stump1eb44332009-09-09 15:08:12 +00003758
John McCall9f54ad42009-12-10 09:41:52 +00003759 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3760 if (!CheckUsingShadowDecl(UD, *I, Previous))
3761 BuildUsingShadowDecl(S, UD, *I);
3762 }
John McCall9488ea12009-11-17 05:59:44 +00003763
3764 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003765}
3766
John McCall9f54ad42009-12-10 09:41:52 +00003767/// Checks that the given using declaration is not an invalid
3768/// redeclaration. Note that this is checking only for the using decl
3769/// itself, not for any ill-formedness among the UsingShadowDecls.
3770bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3771 bool isTypeName,
3772 const CXXScopeSpec &SS,
3773 SourceLocation NameLoc,
3774 const LookupResult &Prev) {
3775 // C++03 [namespace.udecl]p8:
3776 // C++0x [namespace.udecl]p10:
3777 // A using-declaration is a declaration and can therefore be used
3778 // repeatedly where (and only where) multiple declarations are
3779 // allowed.
3780 // That's only in file contexts.
3781 if (CurContext->getLookupContext()->isFileContext())
3782 return false;
3783
3784 NestedNameSpecifier *Qual
3785 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3786
3787 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3788 NamedDecl *D = *I;
3789
3790 bool DTypename;
3791 NestedNameSpecifier *DQual;
3792 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3793 DTypename = UD->isTypeName();
3794 DQual = UD->getTargetNestedNameDecl();
3795 } else if (UnresolvedUsingValueDecl *UD
3796 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3797 DTypename = false;
3798 DQual = UD->getTargetNestedNameSpecifier();
3799 } else if (UnresolvedUsingTypenameDecl *UD
3800 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3801 DTypename = true;
3802 DQual = UD->getTargetNestedNameSpecifier();
3803 } else continue;
3804
3805 // using decls differ if one says 'typename' and the other doesn't.
3806 // FIXME: non-dependent using decls?
3807 if (isTypeName != DTypename) continue;
3808
3809 // using decls differ if they name different scopes (but note that
3810 // template instantiation can cause this check to trigger when it
3811 // didn't before instantiation).
3812 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3813 Context.getCanonicalNestedNameSpecifier(DQual))
3814 continue;
3815
3816 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003817 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003818 return true;
3819 }
3820
3821 return false;
3822}
3823
John McCall604e7f12009-12-08 07:46:18 +00003824
John McCalled976492009-12-04 22:46:56 +00003825/// Checks that the given nested-name qualifier used in a using decl
3826/// in the current context is appropriately related to the current
3827/// scope. If an error is found, diagnoses it and returns true.
3828bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3829 const CXXScopeSpec &SS,
3830 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003831 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003832
John McCall604e7f12009-12-08 07:46:18 +00003833 if (!CurContext->isRecord()) {
3834 // C++03 [namespace.udecl]p3:
3835 // C++0x [namespace.udecl]p8:
3836 // A using-declaration for a class member shall be a member-declaration.
3837
3838 // If we weren't able to compute a valid scope, it must be a
3839 // dependent class scope.
3840 if (!NamedContext || NamedContext->isRecord()) {
3841 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3842 << SS.getRange();
3843 return true;
3844 }
3845
3846 // Otherwise, everything is known to be fine.
3847 return false;
3848 }
3849
3850 // The current scope is a record.
3851
3852 // If the named context is dependent, we can't decide much.
3853 if (!NamedContext) {
3854 // FIXME: in C++0x, we can diagnose if we can prove that the
3855 // nested-name-specifier does not refer to a base class, which is
3856 // still possible in some cases.
3857
3858 // Otherwise we have to conservatively report that things might be
3859 // okay.
3860 return false;
3861 }
3862
3863 if (!NamedContext->isRecord()) {
3864 // Ideally this would point at the last name in the specifier,
3865 // but we don't have that level of source info.
3866 Diag(SS.getRange().getBegin(),
3867 diag::err_using_decl_nested_name_specifier_is_not_class)
3868 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3869 return true;
3870 }
3871
3872 if (getLangOptions().CPlusPlus0x) {
3873 // C++0x [namespace.udecl]p3:
3874 // In a using-declaration used as a member-declaration, the
3875 // nested-name-specifier shall name a base class of the class
3876 // being defined.
3877
3878 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3879 cast<CXXRecordDecl>(NamedContext))) {
3880 if (CurContext == NamedContext) {
3881 Diag(NameLoc,
3882 diag::err_using_decl_nested_name_specifier_is_current_class)
3883 << SS.getRange();
3884 return true;
3885 }
3886
3887 Diag(SS.getRange().getBegin(),
3888 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3889 << (NestedNameSpecifier*) SS.getScopeRep()
3890 << cast<CXXRecordDecl>(CurContext)
3891 << SS.getRange();
3892 return true;
3893 }
3894
3895 return false;
3896 }
3897
3898 // C++03 [namespace.udecl]p4:
3899 // A using-declaration used as a member-declaration shall refer
3900 // to a member of a base class of the class being defined [etc.].
3901
3902 // Salient point: SS doesn't have to name a base class as long as
3903 // lookup only finds members from base classes. Therefore we can
3904 // diagnose here only if we can prove that that can't happen,
3905 // i.e. if the class hierarchies provably don't intersect.
3906
3907 // TODO: it would be nice if "definitely valid" results were cached
3908 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3909 // need to be repeated.
3910
3911 struct UserData {
3912 llvm::DenseSet<const CXXRecordDecl*> Bases;
3913
3914 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3915 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3916 Data->Bases.insert(Base);
3917 return true;
3918 }
3919
3920 bool hasDependentBases(const CXXRecordDecl *Class) {
3921 return !Class->forallBases(collect, this);
3922 }
3923
3924 /// Returns true if the base is dependent or is one of the
3925 /// accumulated base classes.
3926 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3927 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3928 return !Data->Bases.count(Base);
3929 }
3930
3931 bool mightShareBases(const CXXRecordDecl *Class) {
3932 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3933 }
3934 };
3935
3936 UserData Data;
3937
3938 // Returns false if we find a dependent base.
3939 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3940 return false;
3941
3942 // Returns false if the class has a dependent base or if it or one
3943 // of its bases is present in the base set of the current context.
3944 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3945 return false;
3946
3947 Diag(SS.getRange().getBegin(),
3948 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3949 << (NestedNameSpecifier*) SS.getScopeRep()
3950 << cast<CXXRecordDecl>(CurContext)
3951 << SS.getRange();
3952
3953 return true;
John McCalled976492009-12-04 22:46:56 +00003954}
3955
Mike Stump1eb44332009-09-09 15:08:12 +00003956Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003957 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003958 SourceLocation AliasLoc,
3959 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003960 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003961 SourceLocation IdentLoc,
3962 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Anders Carlsson81c85c42009-03-28 23:53:49 +00003964 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003965 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3966 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00003967
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003968 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00003969 if (NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003970 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
3971 ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00003972 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003973 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00003974 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00003975 // FIXME: At some point, we'll want to create the (redundant)
3976 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00003977 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00003978 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlsson81c85c42009-03-28 23:53:49 +00003979 return DeclPtrTy();
3980 }
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003982 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3983 diag::err_redefinition_different_kind;
3984 Diag(AliasLoc, DiagID) << Alias;
3985 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003986 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00003987 }
3988
John McCalla24dc2e2009-11-17 02:14:36 +00003989 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003990 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00003991
John McCallf36e02d2009-10-09 21:13:30 +00003992 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00003993 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003994 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00003995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00003997 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00003998 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3999 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004000 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004001 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004002
John McCall3dbd3d52010-02-16 06:53:13 +00004003 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00004004 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00004005}
4006
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004007void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4008 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004009 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4010 !Constructor->isUsed()) &&
4011 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004013 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004014 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004015
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004016 DeclContext *PreviousContext = CurContext;
4017 CurContext = Constructor;
Anders Carlssonec3332b2010-04-02 03:43:34 +00004018 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00004019 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004020 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004021 Constructor->setInvalidDecl();
4022 } else {
4023 Constructor->setUsed();
4024 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004025 CurContext = PreviousContext;
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004026}
4027
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004028void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004029 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004030 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4031 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004032 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004033 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004034
4035 DeclContext *PreviousContext = CurContext;
4036 CurContext = Destructor;
4037
John McCallef027fe2010-03-16 21:39:52 +00004038 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4039 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Anders Carlsson37909802009-11-30 21:24:50 +00004041 // FIXME: If CheckDestructor fails, we should emit a note about where the
4042 // implicit destructor was needed.
4043 if (CheckDestructor(Destructor)) {
4044 Diag(CurrentLocation, diag::note_member_synthesized_at)
4045 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4046
4047 Destructor->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004048 CurContext = PreviousContext;
4049
Anders Carlsson37909802009-11-30 21:24:50 +00004050 return;
4051 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004052 CurContext = PreviousContext;
Anders Carlsson37909802009-11-30 21:24:50 +00004053
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004054 Destructor->setUsed();
4055}
4056
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004057void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
4058 CXXMethodDecl *MethodDecl) {
4059 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
4060 MethodDecl->getOverloadedOperator() == OO_Equal &&
4061 !MethodDecl->isUsed()) &&
4062 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004064 CXXRecordDecl *ClassDecl
4065 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004067 DeclContext *PreviousContext = CurContext;
4068 CurContext = MethodDecl;
4069
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00004070 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004071 // Before the implicitly-declared copy assignment operator for a class is
4072 // implicitly defined, all implicitly-declared copy assignment operators
4073 // for its direct base classes and its nonstatic data members shall have
4074 // been implicitly defined.
4075 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00004076 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4077 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004078 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004079 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004080 if (CXXMethodDecl *BaseAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004081 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
John McCallb0207482010-03-16 06:11:48 +00004082 BaseClassDecl)) {
4083 CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4084 BaseAssignOpMethod,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004085 PDiag(diag::err_access_assign_base)
John McCallb0207482010-03-16 06:11:48 +00004086 << Base->getType());
4087
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004088 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
John McCallb0207482010-03-16 06:11:48 +00004089 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004090 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00004091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4092 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004093 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4094 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4095 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004096 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004097 CXXRecordDecl *FieldClassDecl
4098 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004099 if (CXXMethodDecl *FieldAssignOpMethod =
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004100 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
John McCallb0207482010-03-16 06:11:48 +00004101 FieldClassDecl)) {
4102 CheckDirectMemberAccess(Field->getLocation(),
4103 FieldAssignOpMethod,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004104 PDiag(diag::err_access_assign_field)
John McCallb0207482010-03-16 06:11:48 +00004105 << Field->getDeclName() << Field->getType());
4106
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004107 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
John McCallb0207482010-03-16 06:11:48 +00004108 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004109 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004110 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00004111 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4112 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004113 Diag(CurrentLocation, diag::note_first_required_here);
4114 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004115 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004116 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00004117 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4118 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004119 Diag(CurrentLocation, diag::note_first_required_here);
4120 err = true;
4121 }
4122 }
4123 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00004124 MethodDecl->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004125
4126 CurContext = PreviousContext;
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004127}
4128
4129CXXMethodDecl *
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004130Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
4131 ParmVarDecl *ParmDecl,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004132 CXXRecordDecl *ClassDecl) {
4133 QualType LHSType = Context.getTypeDeclType(ClassDecl);
4134 QualType RHSType(LHSType);
4135 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00004136 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004137 // operator = (B&).
John McCall0953e762009-09-24 19:53:00 +00004138 RHSType = Context.getCVRQualifiedType(RHSType,
4139 ParmDecl->getType().getCVRQualifiers());
Mike Stump1eb44332009-09-09 15:08:12 +00004140 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004141 LHSType,
4142 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00004143 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004144 RHSType,
4145 CurrentLocation));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004146 Expr *Args[2] = { &*LHS, &*RHS };
John McCall5769d612010-02-08 23:07:23 +00004147 OverloadCandidateSet CandidateSet(CurrentLocation);
Mike Stump1eb44332009-09-09 15:08:12 +00004148 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004149 CandidateSet);
4150 OverloadCandidateSet::iterator Best;
Anders Carlssonb6cc91b2009-12-09 03:01:51 +00004151 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004152 return cast<CXXMethodDecl>(Best->Function);
4153 assert(false &&
4154 "getAssignOperatorMethod - copy assignment operator method not found");
4155 return 0;
4156}
4157
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004158void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4159 CXXConstructorDecl *CopyConstructor,
4160 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00004161 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00004162 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004163 !CopyConstructor->isUsed()) &&
4164 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004165
Anders Carlsson63010a72010-04-23 16:24:12 +00004166 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004167 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004168
4169 DeclContext *PreviousContext = CurContext;
4170 CurContext = CopyConstructor;
4171
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00004172 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00004173 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004174 // implicitly defined, all the implicitly-declared copy constructors
4175 // for its base class and its non-static data members shall have been
4176 // implicitly defined.
4177 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
4178 Base != ClassDecl->bases_end(); ++Base) {
4179 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00004180 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004181 if (CXXConstructorDecl *BaseCopyCtor =
John McCallb0207482010-03-16 06:11:48 +00004182 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) {
4183 CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4184 BaseCopyCtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004185 PDiag(diag::err_access_copy_base)
John McCallb0207482010-03-16 06:11:48 +00004186 << Base->getType());
4187
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00004188 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
John McCallb0207482010-03-16 06:11:48 +00004189 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004190 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004191 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4192 FieldEnd = ClassDecl->field_end();
4193 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004194 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4195 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4196 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004197 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004198 CXXRecordDecl *FieldClassDecl
4199 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004200 if (CXXConstructorDecl *FieldCopyCtor =
John McCallb0207482010-03-16 06:11:48 +00004201 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4202 CheckDirectMemberAccess(Field->getLocation(),
4203 FieldCopyCtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004204 PDiag(diag::err_access_copy_field)
John McCallb0207482010-03-16 06:11:48 +00004205 << Field->getDeclName() << Field->getType());
4206
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00004207 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
John McCallb0207482010-03-16 06:11:48 +00004208 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004209 }
4210 }
4211 CopyConstructor->setUsed();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004212
4213 CurContext = PreviousContext;
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004214}
4215
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004216Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004217Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00004218 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00004219 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004220 bool RequiresZeroInit,
4221 bool BaseInitialization) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004222 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004223
Douglas Gregor2f599792010-04-02 18:24:57 +00004224 // C++0x [class.copy]p34:
4225 // When certain criteria are met, an implementation is allowed to
4226 // omit the copy/move construction of a class object, even if the
4227 // copy/move constructor and/or destructor for the object have
4228 // side effects. [...]
4229 // - when a temporary class object that has not been bound to a
4230 // reference (12.2) would be copied/moved to a class object
4231 // with the same cv-unqualified type, the copy/move operation
4232 // can be omitted by constructing the temporary object
4233 // directly into the target of the omitted copy/move
4234 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4235 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4236 Elidable = SubExpr->isTemporaryObject() &&
4237 Context.hasSameUnqualifiedType(SubExpr->getType(),
4238 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004239 }
Mike Stump1eb44332009-09-09 15:08:12 +00004240
4241 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004242 Elidable, move(ExprArgs), RequiresZeroInit,
4243 BaseInitialization);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004244}
4245
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004246/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4247/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004248Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004249Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4250 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004251 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004252 bool RequiresZeroInit,
4253 bool BaseInitialization) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004254 unsigned NumExprs = ExprArgs.size();
4255 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Douglas Gregor7edfb692009-11-23 12:27:39 +00004257 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004258 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004259 Constructor, Elidable, Exprs, NumExprs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004260 RequiresZeroInit, BaseInitialization));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004261}
4262
Mike Stump1eb44332009-09-09 15:08:12 +00004263bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004264 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004265 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004266 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004267 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004268 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004269 if (TempResult.isInvalid())
4270 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004272 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004273 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004274 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004275 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Anders Carlssonfe2de492009-08-25 05:18:00 +00004277 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004278}
4279
John McCall68c6c9a2010-02-02 09:10:11 +00004280void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4281 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004282 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4283 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004284 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4285 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00004286 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004287 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00004288 << VD->getDeclName()
4289 << VD->getType());
John McCall4f9506a2010-02-02 08:45:54 +00004290 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004291}
4292
Mike Stump1eb44332009-09-09 15:08:12 +00004293/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004294/// ActOnDeclarator, when a C++ direct initializer is present.
4295/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004296void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4297 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004298 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004299 SourceLocation *CommaLocs,
4300 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004301 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004302 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004303
4304 // If there is no declaration, there was an error parsing it. Just ignore
4305 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004306 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004307 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004309 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4310 if (!VDecl) {
4311 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4312 RealDecl->setInvalidDecl();
4313 return;
4314 }
4315
Douglas Gregor83ddad32009-08-26 21:14:46 +00004316 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004317 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004318 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4319 //
4320 // Clients that want to distinguish between the two forms, can check for
4321 // direct initializer using VarDecl::hasCXXDirectInitializer().
4322 // A major benefit is that clients that don't particularly care about which
4323 // exactly form was it (like the CodeGen) can handle both cases without
4324 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004325
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004326 // C++ 8.5p11:
4327 // The form of initialization (using parentheses or '=') is generally
4328 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004329 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004330 QualType DeclInitType = VDecl->getType();
4331 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004332 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004333
Douglas Gregor4dffad62010-02-11 22:55:30 +00004334 if (!VDecl->getType()->isDependentType() &&
4335 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004336 diag::err_typecheck_decl_incomplete_type)) {
4337 VDecl->setInvalidDecl();
4338 return;
4339 }
4340
Douglas Gregor90f93822009-12-22 22:17:25 +00004341 // The variable can not have an abstract class type.
4342 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4343 diag::err_abstract_type_in_decl,
4344 AbstractVariableType))
4345 VDecl->setInvalidDecl();
4346
Sebastian Redl31310a22010-02-01 20:16:42 +00004347 const VarDecl *Def;
4348 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004349 Diag(VDecl->getLocation(), diag::err_redefinition)
4350 << VDecl->getDeclName();
4351 Diag(Def->getLocation(), diag::note_previous_definition);
4352 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004353 return;
4354 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004355
4356 // If either the declaration has a dependent type or if any of the
4357 // expressions is type-dependent, we represent the initialization
4358 // via a ParenListExpr for later use during template instantiation.
4359 if (VDecl->getType()->isDependentType() ||
4360 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4361 // Let clients know that initialization was done with a direct initializer.
4362 VDecl->setCXXDirectInitializer(true);
4363
4364 // Store the initialization expressions as a ParenListExpr.
4365 unsigned NumExprs = Exprs.size();
4366 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4367 (Expr **)Exprs.release(),
4368 NumExprs, RParenLoc));
4369 return;
4370 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004371
4372 // Capture the variable that is being initialized and the style of
4373 // initialization.
4374 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4375
4376 // FIXME: Poor source location information.
4377 InitializationKind Kind
4378 = InitializationKind::CreateDirect(VDecl->getLocation(),
4379 LParenLoc, RParenLoc);
4380
4381 InitializationSequence InitSeq(*this, Entity, Kind,
4382 (Expr**)Exprs.get(), Exprs.size());
4383 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4384 if (Result.isInvalid()) {
4385 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004386 return;
4387 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004388
4389 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004390 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004391 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004392
John McCall68c6c9a2010-02-02 09:10:11 +00004393 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4394 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004395}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004396
Douglas Gregor39da0b82009-09-09 23:08:42 +00004397/// \brief Given a constructor and the set of arguments provided for the
4398/// constructor, convert the arguments and add any required default arguments
4399/// to form a proper call to this constructor.
4400///
4401/// \returns true if an error occurred, false otherwise.
4402bool
4403Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4404 MultiExprArg ArgsPtr,
4405 SourceLocation Loc,
4406 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4407 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4408 unsigned NumArgs = ArgsPtr.size();
4409 Expr **Args = (Expr **)ArgsPtr.get();
4410
4411 const FunctionProtoType *Proto
4412 = Constructor->getType()->getAs<FunctionProtoType>();
4413 assert(Proto && "Constructor without a prototype?");
4414 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004415
4416 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004417 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004418 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004419 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004420 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004421
4422 VariadicCallType CallType =
4423 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4424 llvm::SmallVector<Expr *, 8> AllArgs;
4425 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4426 Proto, 0, Args, NumArgs, AllArgs,
4427 CallType);
4428 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4429 ConvertedArgs.push_back(AllArgs[i]);
4430 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004431}
4432
Anders Carlsson20d45d22009-12-12 00:32:00 +00004433static inline bool
4434CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4435 const FunctionDecl *FnDecl) {
4436 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4437 if (isa<NamespaceDecl>(DC)) {
4438 return SemaRef.Diag(FnDecl->getLocation(),
4439 diag::err_operator_new_delete_declared_in_namespace)
4440 << FnDecl->getDeclName();
4441 }
4442
4443 if (isa<TranslationUnitDecl>(DC) &&
4444 FnDecl->getStorageClass() == FunctionDecl::Static) {
4445 return SemaRef.Diag(FnDecl->getLocation(),
4446 diag::err_operator_new_delete_declared_static)
4447 << FnDecl->getDeclName();
4448 }
4449
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004450 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004451}
4452
Anders Carlsson156c78e2009-12-13 17:53:43 +00004453static inline bool
4454CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4455 CanQualType ExpectedResultType,
4456 CanQualType ExpectedFirstParamType,
4457 unsigned DependentParamTypeDiag,
4458 unsigned InvalidParamTypeDiag) {
4459 QualType ResultType =
4460 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4461
4462 // Check that the result type is not dependent.
4463 if (ResultType->isDependentType())
4464 return SemaRef.Diag(FnDecl->getLocation(),
4465 diag::err_operator_new_delete_dependent_result_type)
4466 << FnDecl->getDeclName() << ExpectedResultType;
4467
4468 // Check that the result type is what we expect.
4469 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4470 return SemaRef.Diag(FnDecl->getLocation(),
4471 diag::err_operator_new_delete_invalid_result_type)
4472 << FnDecl->getDeclName() << ExpectedResultType;
4473
4474 // A function template must have at least 2 parameters.
4475 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4476 return SemaRef.Diag(FnDecl->getLocation(),
4477 diag::err_operator_new_delete_template_too_few_parameters)
4478 << FnDecl->getDeclName();
4479
4480 // The function decl must have at least 1 parameter.
4481 if (FnDecl->getNumParams() == 0)
4482 return SemaRef.Diag(FnDecl->getLocation(),
4483 diag::err_operator_new_delete_too_few_parameters)
4484 << FnDecl->getDeclName();
4485
4486 // Check the the first parameter type is not dependent.
4487 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4488 if (FirstParamType->isDependentType())
4489 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4490 << FnDecl->getDeclName() << ExpectedFirstParamType;
4491
4492 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004493 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004494 ExpectedFirstParamType)
4495 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4496 << FnDecl->getDeclName() << ExpectedFirstParamType;
4497
4498 return false;
4499}
4500
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004501static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004502CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004503 // C++ [basic.stc.dynamic.allocation]p1:
4504 // A program is ill-formed if an allocation function is declared in a
4505 // namespace scope other than global scope or declared static in global
4506 // scope.
4507 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4508 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004509
4510 CanQualType SizeTy =
4511 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4512
4513 // C++ [basic.stc.dynamic.allocation]p1:
4514 // The return type shall be void*. The first parameter shall have type
4515 // std::size_t.
4516 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4517 SizeTy,
4518 diag::err_operator_new_dependent_param_type,
4519 diag::err_operator_new_param_type))
4520 return true;
4521
4522 // C++ [basic.stc.dynamic.allocation]p1:
4523 // The first parameter shall not have an associated default argument.
4524 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004525 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004526 diag::err_operator_new_default_arg)
4527 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4528
4529 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004530}
4531
4532static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004533CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4534 // C++ [basic.stc.dynamic.deallocation]p1:
4535 // A program is ill-formed if deallocation functions are declared in a
4536 // namespace scope other than global scope or declared static in global
4537 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004538 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4539 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004540
4541 // C++ [basic.stc.dynamic.deallocation]p2:
4542 // Each deallocation function shall return void and its first parameter
4543 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004544 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4545 SemaRef.Context.VoidPtrTy,
4546 diag::err_operator_delete_dependent_param_type,
4547 diag::err_operator_delete_param_type))
4548 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004549
Anders Carlsson46991d62009-12-12 00:16:02 +00004550 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4551 if (FirstParamType->isDependentType())
4552 return SemaRef.Diag(FnDecl->getLocation(),
4553 diag::err_operator_delete_dependent_param_type)
4554 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4555
4556 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4557 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004558 return SemaRef.Diag(FnDecl->getLocation(),
4559 diag::err_operator_delete_param_type)
4560 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004561
4562 return false;
4563}
4564
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004565/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4566/// of this overloaded operator is well-formed. If so, returns false;
4567/// otherwise, emits appropriate diagnostics and returns true.
4568bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004569 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004570 "Expected an overloaded operator declaration");
4571
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004572 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4573
Mike Stump1eb44332009-09-09 15:08:12 +00004574 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004575 // The allocation and deallocation functions, operator new,
4576 // operator new[], operator delete and operator delete[], are
4577 // described completely in 3.7.3. The attributes and restrictions
4578 // found in the rest of this subclause do not apply to them unless
4579 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004580 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004581 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004582
Anders Carlssona3ccda52009-12-12 00:26:23 +00004583 if (Op == OO_New || Op == OO_Array_New)
4584 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004585
4586 // C++ [over.oper]p6:
4587 // An operator function shall either be a non-static member
4588 // function or be a non-member function and have at least one
4589 // parameter whose type is a class, a reference to a class, an
4590 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004591 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4592 if (MethodDecl->isStatic())
4593 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004594 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004595 } else {
4596 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004597 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4598 ParamEnd = FnDecl->param_end();
4599 Param != ParamEnd; ++Param) {
4600 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004601 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4602 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004603 ClassOrEnumParam = true;
4604 break;
4605 }
4606 }
4607
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004608 if (!ClassOrEnumParam)
4609 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004610 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004611 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004612 }
4613
4614 // C++ [over.oper]p8:
4615 // An operator function cannot have default arguments (8.3.6),
4616 // except where explicitly stated below.
4617 //
Mike Stump1eb44332009-09-09 15:08:12 +00004618 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004619 // (C++ [over.call]p1).
4620 if (Op != OO_Call) {
4621 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4622 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004623 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004624 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004625 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004626 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004627 }
4628 }
4629
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004630 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4631 { false, false, false }
4632#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4633 , { Unary, Binary, MemberOnly }
4634#include "clang/Basic/OperatorKinds.def"
4635 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004636
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004637 bool CanBeUnaryOperator = OperatorUses[Op][0];
4638 bool CanBeBinaryOperator = OperatorUses[Op][1];
4639 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004640
4641 // C++ [over.oper]p8:
4642 // [...] Operator functions cannot have more or fewer parameters
4643 // than the number required for the corresponding operator, as
4644 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00004645 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004646 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004647 if (Op != OO_Call &&
4648 ((NumParams == 1 && !CanBeUnaryOperator) ||
4649 (NumParams == 2 && !CanBeBinaryOperator) ||
4650 (NumParams < 1) || (NumParams > 2))) {
4651 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00004652 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004653 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004654 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004655 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00004656 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004657 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004658 assert(CanBeBinaryOperator &&
4659 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00004660 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004661 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004662
Chris Lattner416e46f2008-11-21 07:57:12 +00004663 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004664 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004665 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004666
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004667 // Overloaded operators other than operator() cannot be variadic.
4668 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00004669 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004670 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004671 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004672 }
4673
4674 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004675 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4676 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004677 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004678 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004679 }
4680
4681 // C++ [over.inc]p1:
4682 // The user-defined function called operator++ implements the
4683 // prefix and postfix ++ operator. If this function is a member
4684 // function with no parameters, or a non-member function with one
4685 // parameter of class or enumeration type, it defines the prefix
4686 // increment operator ++ for objects of that type. If the function
4687 // is a member function with one parameter (which shall be of type
4688 // int) or a non-member function with two parameters (the second
4689 // of which shall be of type int), it defines the postfix
4690 // increment operator ++ for objects of that type.
4691 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4692 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4693 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00004694 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004695 ParamIsInt = BT->getKind() == BuiltinType::Int;
4696
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00004697 if (!ParamIsInt)
4698 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004699 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00004700 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004701 }
4702
Sebastian Redl64b45f72009-01-05 20:52:13 +00004703 // Notify the class if it got an assignment operator.
4704 if (Op == OO_Equal) {
4705 // Would have returned earlier otherwise.
4706 assert(isa<CXXMethodDecl>(FnDecl) &&
4707 "Overloaded = not member, but not filtered.");
4708 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4709 Method->getParent()->addedAssignmentOperator(Context, Method);
4710 }
4711
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004712 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004713}
Chris Lattner5a003a42008-12-17 07:09:26 +00004714
Sean Hunta6c058d2010-01-13 09:01:02 +00004715/// CheckLiteralOperatorDeclaration - Check whether the declaration
4716/// of this literal operator function is well-formed. If so, returns
4717/// false; otherwise, emits appropriate diagnostics and returns true.
4718bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4719 DeclContext *DC = FnDecl->getDeclContext();
4720 Decl::Kind Kind = DC->getDeclKind();
4721 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4722 Kind != Decl::LinkageSpec) {
4723 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4724 << FnDecl->getDeclName();
4725 return true;
4726 }
4727
4728 bool Valid = false;
4729
Sean Hunt216c2782010-04-07 23:11:06 +00004730 // template <char...> type operator "" name() is the only valid template
4731 // signature, and the only valid signature with no parameters.
4732 if (FnDecl->param_size() == 0) {
4733 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
4734 // Must have only one template parameter
4735 TemplateParameterList *Params = TpDecl->getTemplateParameters();
4736 if (Params->size() == 1) {
4737 NonTypeTemplateParmDecl *PmDecl =
4738 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00004739
Sean Hunt216c2782010-04-07 23:11:06 +00004740 // The template parameter must be a char parameter pack.
4741 // FIXME: This test will always fail because non-type parameter packs
4742 // have not been implemented.
4743 if (PmDecl && PmDecl->isTemplateParameterPack() &&
4744 Context.hasSameType(PmDecl->getType(), Context.CharTy))
4745 Valid = true;
4746 }
4747 }
4748 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00004749 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00004750 FunctionDecl::param_iterator Param = FnDecl->param_begin();
4751
Sean Hunta6c058d2010-01-13 09:01:02 +00004752 QualType T = (*Param)->getType();
4753
Sean Hunt30019c02010-04-07 22:57:35 +00004754 // unsigned long long int, long double, and any character type are allowed
4755 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00004756 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
4757 Context.hasSameType(T, Context.LongDoubleTy) ||
4758 Context.hasSameType(T, Context.CharTy) ||
4759 Context.hasSameType(T, Context.WCharTy) ||
4760 Context.hasSameType(T, Context.Char16Ty) ||
4761 Context.hasSameType(T, Context.Char32Ty)) {
4762 if (++Param == FnDecl->param_end())
4763 Valid = true;
4764 goto FinishedParams;
4765 }
4766
Sean Hunt30019c02010-04-07 22:57:35 +00004767 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00004768 const PointerType *PT = T->getAs<PointerType>();
4769 if (!PT)
4770 goto FinishedParams;
4771 T = PT->getPointeeType();
4772 if (!T.isConstQualified())
4773 goto FinishedParams;
4774 T = T.getUnqualifiedType();
4775
4776 // Move on to the second parameter;
4777 ++Param;
4778
4779 // If there is no second parameter, the first must be a const char *
4780 if (Param == FnDecl->param_end()) {
4781 if (Context.hasSameType(T, Context.CharTy))
4782 Valid = true;
4783 goto FinishedParams;
4784 }
4785
4786 // const char *, const wchar_t*, const char16_t*, and const char32_t*
4787 // are allowed as the first parameter to a two-parameter function
4788 if (!(Context.hasSameType(T, Context.CharTy) ||
4789 Context.hasSameType(T, Context.WCharTy) ||
4790 Context.hasSameType(T, Context.Char16Ty) ||
4791 Context.hasSameType(T, Context.Char32Ty)))
4792 goto FinishedParams;
4793
4794 // The second and final parameter must be an std::size_t
4795 T = (*Param)->getType().getUnqualifiedType();
4796 if (Context.hasSameType(T, Context.getSizeType()) &&
4797 ++Param == FnDecl->param_end())
4798 Valid = true;
4799 }
4800
4801 // FIXME: This diagnostic is absolutely terrible.
4802FinishedParams:
4803 if (!Valid) {
4804 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
4805 << FnDecl->getDeclName();
4806 return true;
4807 }
4808
4809 return false;
4810}
4811
Douglas Gregor074149e2009-01-05 19:45:36 +00004812/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4813/// linkage specification, including the language and (if present)
4814/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4815/// the location of the language string literal, which is provided
4816/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4817/// the '{' brace. Otherwise, this linkage specification does not
4818/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004819Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4820 SourceLocation ExternLoc,
4821 SourceLocation LangLoc,
4822 const char *Lang,
4823 unsigned StrSize,
4824 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00004825 LinkageSpecDecl::LanguageIDs Language;
4826 if (strncmp(Lang, "\"C\"", StrSize) == 0)
4827 Language = LinkageSpecDecl::lang_c;
4828 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4829 Language = LinkageSpecDecl::lang_cxx;
4830 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00004831 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004832 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00004833 }
Mike Stump1eb44332009-09-09 15:08:12 +00004834
Chris Lattnercc98eac2008-12-17 07:13:27 +00004835 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Douglas Gregor074149e2009-01-05 19:45:36 +00004837 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00004838 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00004839 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004840 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00004841 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004842 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00004843}
4844
Douglas Gregor074149e2009-01-05 19:45:36 +00004845/// ActOnFinishLinkageSpecification - Completely the definition of
4846/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4847/// valid, it's the position of the closing '}' brace in a linkage
4848/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004849Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4850 DeclPtrTy LinkageSpec,
4851 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00004852 if (LinkageSpec)
4853 PopDeclContext();
4854 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00004855}
4856
Douglas Gregord308e622009-05-18 20:51:54 +00004857/// \brief Perform semantic analysis for the variable declaration that
4858/// occurs within a C++ catch clause, returning the newly-created
4859/// variable.
4860VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00004861 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004862 IdentifierInfo *Name,
4863 SourceLocation Loc,
4864 SourceRange Range) {
4865 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004866
4867 // Arrays and functions decay.
4868 if (ExDeclType->isArrayType())
4869 ExDeclType = Context.getArrayDecayedType(ExDeclType);
4870 else if (ExDeclType->isFunctionType())
4871 ExDeclType = Context.getPointerType(ExDeclType);
4872
4873 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4874 // The exception-declaration shall not denote a pointer or reference to an
4875 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004876 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00004877 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00004878 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004879 Invalid = true;
4880 }
Douglas Gregord308e622009-05-18 20:51:54 +00004881
Douglas Gregora2762912010-03-08 01:47:36 +00004882 // GCC allows catching pointers and references to incomplete types
4883 // as an extension; so do we, but we warn by default.
4884
Sebastian Redl4b07b292008-12-22 19:15:10 +00004885 QualType BaseType = ExDeclType;
4886 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004887 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00004888 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00004889 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004890 BaseType = Ptr->getPointeeType();
4891 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00004892 DK = diag::ext_catch_incomplete_ptr;
4893 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004894 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004895 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004896 BaseType = Ref->getPointeeType();
4897 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00004898 DK = diag::ext_catch_incomplete_ref;
4899 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004900 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00004901 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00004902 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
4903 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00004904 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004905
Mike Stump1eb44332009-09-09 15:08:12 +00004906 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00004907 RequireNonAbstractType(Loc, ExDeclType,
4908 diag::err_abstract_type_in_decl,
4909 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00004910 Invalid = true;
4911
Mike Stump1eb44332009-09-09 15:08:12 +00004912 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004913 Name, ExDeclType, TInfo, VarDecl::None,
4914 VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00004915
Douglas Gregor6d182892010-03-05 23:38:39 +00004916 if (!Invalid) {
4917 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
4918 // C++ [except.handle]p16:
4919 // The object declared in an exception-declaration or, if the
4920 // exception-declaration does not specify a name, a temporary (12.2) is
4921 // copy-initialized (8.5) from the exception object. [...]
4922 // The object is destroyed when the handler exits, after the destruction
4923 // of any automatic objects initialized within the handler.
4924 //
4925 // We just pretend to initialize the object with itself, then make sure
4926 // it can be destroyed later.
4927 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
4928 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
4929 Loc, ExDeclType, 0);
4930 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
4931 SourceLocation());
4932 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
4933 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4934 MultiExprArg(*this, (void**)&ExDeclRef, 1));
4935 if (Result.isInvalid())
4936 Invalid = true;
4937 else
4938 FinalizeVarWithDestructor(ExDecl, RecordTy);
4939 }
4940 }
4941
Douglas Gregord308e622009-05-18 20:51:54 +00004942 if (Invalid)
4943 ExDecl->setInvalidDecl();
4944
4945 return ExDecl;
4946}
4947
4948/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4949/// handler.
4950Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00004951 TypeSourceInfo *TInfo = 0;
4952 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00004953
4954 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00004955 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00004956 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00004957 LookupOrdinaryName,
4958 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004959 // The scope should be freshly made just for us. There is just no way
4960 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004961 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00004962 if (PrevDecl->isTemplateParameter()) {
4963 // Maybe we will complain about the shadowed template parameter.
4964 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004965 }
4966 }
4967
Chris Lattnereaaebc72009-04-25 08:06:05 +00004968 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00004969 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4970 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00004971 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00004972 }
4973
John McCalla93c9342009-12-07 02:54:59 +00004974 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00004975 D.getIdentifier(),
4976 D.getIdentifierLoc(),
4977 D.getDeclSpec().getSourceRange());
4978
Chris Lattnereaaebc72009-04-25 08:06:05 +00004979 if (Invalid)
4980 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004981
Sebastian Redl4b07b292008-12-22 19:15:10 +00004982 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00004983 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00004984 PushOnScopeChains(ExDecl, S);
4985 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004986 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004987
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004988 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004989 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00004990}
Anders Carlssonfb311762009-03-14 00:25:26 +00004991
Mike Stump1eb44332009-09-09 15:08:12 +00004992Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004993 ExprArg assertexpr,
4994 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00004995 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004996 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00004997 cast<StringLiteral>((Expr *)assertmessageexpr.get());
4998
Anders Carlssonc3082412009-03-14 00:33:21 +00004999 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5000 llvm::APSInt Value(32);
5001 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5002 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5003 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005004 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005005 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005006
Anders Carlssonc3082412009-03-14 00:33:21 +00005007 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005008 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005009 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005010 }
5011 }
Mike Stump1eb44332009-09-09 15:08:12 +00005012
Anders Carlsson77d81422009-03-15 17:35:16 +00005013 assertexpr.release();
5014 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005015 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005016 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005017
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005018 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005019 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005020}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005021
Douglas Gregor1d869352010-04-07 16:53:43 +00005022/// \brief Perform semantic analysis of the given friend type declaration.
5023///
5024/// \returns A friend declaration that.
5025FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5026 TypeSourceInfo *TSInfo) {
5027 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5028
5029 QualType T = TSInfo->getType();
5030 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5031
Douglas Gregor06245bf2010-04-07 17:57:12 +00005032 if (!getLangOptions().CPlusPlus0x) {
5033 // C++03 [class.friend]p2:
5034 // An elaborated-type-specifier shall be used in a friend declaration
5035 // for a class.*
5036 //
5037 // * The class-key of the elaborated-type-specifier is required.
5038 if (!ActiveTemplateInstantiations.empty()) {
5039 // Do not complain about the form of friend template types during
5040 // template instantiation; we will already have complained when the
5041 // template was declared.
5042 } else if (!T->isElaboratedTypeSpecifier()) {
5043 // If we evaluated the type to a record type, suggest putting
5044 // a tag in front.
5045 if (const RecordType *RT = T->getAs<RecordType>()) {
5046 RecordDecl *RD = RT->getDecl();
5047
5048 std::string InsertionText = std::string(" ") + RD->getKindName();
5049
5050 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5051 << (unsigned) RD->getTagKind()
5052 << T
5053 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5054 InsertionText);
5055 } else {
5056 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5057 << T
5058 << SourceRange(FriendLoc, TypeRange.getEnd());
5059 }
5060 } else if (T->getAs<EnumType>()) {
5061 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00005062 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00005063 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00005064 }
5065 }
5066
Douglas Gregor06245bf2010-04-07 17:57:12 +00005067 // C++0x [class.friend]p3:
5068 // If the type specifier in a friend declaration designates a (possibly
5069 // cv-qualified) class type, that class is declared as a friend; otherwise,
5070 // the friend declaration is ignored.
5071
5072 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5073 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00005074
5075 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5076}
5077
John McCalldd4a3b02009-09-16 22:47:08 +00005078/// Handle a friend type declaration. This works in tandem with
5079/// ActOnTag.
5080///
5081/// Notes on friend class templates:
5082///
5083/// We generally treat friend class declarations as if they were
5084/// declaring a class. So, for example, the elaborated type specifier
5085/// in a friend declaration is required to obey the restrictions of a
5086/// class-head (i.e. no typedefs in the scope chain), template
5087/// parameters are required to match up with simple template-ids, &c.
5088/// However, unlike when declaring a template specialization, it's
5089/// okay to refer to a template specialization without an empty
5090/// template parameter declaration, e.g.
5091/// friend class A<T>::B<unsigned>;
5092/// We permit this as a special case; if there are any template
5093/// parameters present at all, require proper matching, i.e.
5094/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005095Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005096 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005097 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005098
5099 assert(DS.isFriendSpecified());
5100 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5101
John McCalldd4a3b02009-09-16 22:47:08 +00005102 // Try to convert the decl specifier to a type. This works for
5103 // friend templates because ActOnTag never produces a ClassTemplateDecl
5104 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005105 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall32f2fb52010-03-25 18:04:51 +00005106 TypeSourceInfo *TSI;
5107 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005108 if (TheDeclarator.isInvalidType())
5109 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005110
Douglas Gregor1d869352010-04-07 16:53:43 +00005111 if (!TSI)
5112 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5113
John McCalldd4a3b02009-09-16 22:47:08 +00005114 // This is definitely an error in C++98. It's probably meant to
5115 // be forbidden in C++0x, too, but the specification is just
5116 // poorly written.
5117 //
5118 // The problem is with declarations like the following:
5119 // template <T> friend A<T>::foo;
5120 // where deciding whether a class C is a friend or not now hinges
5121 // on whether there exists an instantiation of A that causes
5122 // 'foo' to equal C. There are restrictions on class-heads
5123 // (which we declare (by fiat) elaborated friend declarations to
5124 // be) that makes this tractable.
5125 //
5126 // FIXME: handle "template <> friend class A<T>;", which
5127 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00005128 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00005129 Diag(Loc, diag::err_tagless_friend_type_template)
5130 << DS.getSourceRange();
5131 return DeclPtrTy();
5132 }
Douglas Gregor1d869352010-04-07 16:53:43 +00005133
John McCall02cace72009-08-28 07:59:38 +00005134 // C++98 [class.friend]p1: A friend of a class is a function
5135 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005136 // This is fixed in DR77, which just barely didn't make the C++03
5137 // deadline. It's also a very silly restriction that seriously
5138 // affects inner classes and which nobody else seems to implement;
5139 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00005140 //
5141 // But note that we could warn about it: it's always useless to
5142 // friend one of your own members (it's not, however, worthless to
5143 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00005144
John McCalldd4a3b02009-09-16 22:47:08 +00005145 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00005146 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00005147 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00005148 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00005149 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00005150 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00005151 DS.getFriendSpecLoc());
5152 else
Douglas Gregor1d869352010-04-07 16:53:43 +00005153 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5154
5155 if (!D)
5156 return DeclPtrTy();
5157
John McCalldd4a3b02009-09-16 22:47:08 +00005158 D->setAccess(AS_public);
5159 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005160
John McCalldd4a3b02009-09-16 22:47:08 +00005161 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005162}
5163
John McCallbbbcdd92009-09-11 21:02:39 +00005164Sema::DeclPtrTy
5165Sema::ActOnFriendFunctionDecl(Scope *S,
5166 Declarator &D,
5167 bool IsDefinition,
5168 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005169 const DeclSpec &DS = D.getDeclSpec();
5170
5171 assert(DS.isFriendSpecified());
5172 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5173
5174 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005175 TypeSourceInfo *TInfo = 0;
5176 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005177
5178 // C++ [class.friend]p1
5179 // A friend of a class is a function or class....
5180 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005181 // It *doesn't* see through dependent types, which is correct
5182 // according to [temp.arg.type]p3:
5183 // If a declaration acquires a function type through a
5184 // type dependent on a template-parameter and this causes
5185 // a declaration that does not use the syntactic form of a
5186 // function declarator to have a function type, the program
5187 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005188 if (!T->isFunctionType()) {
5189 Diag(Loc, diag::err_unexpected_friend);
5190
5191 // It might be worthwhile to try to recover by creating an
5192 // appropriate declaration.
5193 return DeclPtrTy();
5194 }
5195
5196 // C++ [namespace.memdef]p3
5197 // - If a friend declaration in a non-local class first declares a
5198 // class or function, the friend class or function is a member
5199 // of the innermost enclosing namespace.
5200 // - The name of the friend is not found by simple name lookup
5201 // until a matching declaration is provided in that namespace
5202 // scope (either before or after the class declaration granting
5203 // friendship).
5204 // - If a friend function is called, its name may be found by the
5205 // name lookup that considers functions from namespaces and
5206 // classes associated with the types of the function arguments.
5207 // - When looking for a prior declaration of a class or a function
5208 // declared as a friend, scopes outside the innermost enclosing
5209 // namespace scope are not considered.
5210
John McCall02cace72009-08-28 07:59:38 +00005211 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5212 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005213 assert(Name);
5214
John McCall67d1a672009-08-06 02:15:43 +00005215 // The context we found the declaration in, or in which we should
5216 // create the declaration.
5217 DeclContext *DC;
5218
5219 // FIXME: handle local classes
5220
5221 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005222 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5223 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005224 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
Douglas Gregora735b202009-10-13 14:39:41 +00005225 // FIXME: RequireCompleteDeclContext
John McCall67d1a672009-08-06 02:15:43 +00005226 DC = computeDeclContext(ScopeQual);
5227
5228 // FIXME: handle dependent contexts
5229 if (!DC) return DeclPtrTy();
5230
John McCall68263142009-11-18 22:49:29 +00005231 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005232
5233 // If searching in that context implicitly found a declaration in
5234 // a different context, treat it like it wasn't found at all.
5235 // TODO: better diagnostics for this case. Suggesting the right
5236 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005237 // FIXME: getRepresentativeDecl() is not right here at all
5238 if (Previous.empty() ||
5239 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005240 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005241 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5242 return DeclPtrTy();
5243 }
5244
5245 // C++ [class.friend]p1: A friend of a class is a function or
5246 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005247 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005248 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5249
John McCall67d1a672009-08-06 02:15:43 +00005250 // Otherwise walk out to the nearest namespace scope looking for matches.
5251 } else {
5252 // TODO: handle local class contexts.
5253
5254 DC = CurContext;
5255 while (true) {
5256 // Skip class contexts. If someone can cite chapter and verse
5257 // for this behavior, that would be nice --- it's what GCC and
5258 // EDG do, and it seems like a reasonable intent, but the spec
5259 // really only says that checks for unqualified existing
5260 // declarations should stop at the nearest enclosing namespace,
5261 // not that they should only consider the nearest enclosing
5262 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005263 while (DC->isRecord())
5264 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005265
John McCall68263142009-11-18 22:49:29 +00005266 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005267
5268 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005269 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005270 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005271
John McCall67d1a672009-08-06 02:15:43 +00005272 if (DC->isFileContext()) break;
5273 DC = DC->getParent();
5274 }
5275
5276 // C++ [class.friend]p1: A friend of a class is a function or
5277 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005278 // C++0x changes this for both friend types and functions.
5279 // Most C++ 98 compilers do seem to give an error here, so
5280 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005281 if (!Previous.empty() && DC->Equals(CurContext)
5282 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005283 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5284 }
5285
Douglas Gregor182ddf02009-09-28 00:08:27 +00005286 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005287 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005288 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5289 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5290 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005291 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005292 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5293 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005294 return DeclPtrTy();
5295 }
John McCall67d1a672009-08-06 02:15:43 +00005296 }
5297
Douglas Gregor182ddf02009-09-28 00:08:27 +00005298 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005299 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005300 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005301 IsDefinition,
5302 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005303 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005304
Douglas Gregor182ddf02009-09-28 00:08:27 +00005305 assert(ND->getDeclContext() == DC);
5306 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005307
John McCallab88d972009-08-31 22:39:49 +00005308 // Add the function declaration to the appropriate lookup tables,
5309 // adjusting the redeclarations list as necessary. We don't
5310 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005311 //
John McCallab88d972009-08-31 22:39:49 +00005312 // Also update the scope-based lookup if the target context's
5313 // lookup context is in lexical scope.
5314 if (!CurContext->isDependentContext()) {
5315 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005316 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005317 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005318 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005319 }
John McCall02cace72009-08-28 07:59:38 +00005320
5321 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005322 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005323 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005324 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005325 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005326
Douglas Gregor182ddf02009-09-28 00:08:27 +00005327 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005328}
5329
Chris Lattnerb28317a2009-03-28 19:18:32 +00005330void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005331 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Chris Lattnerb28317a2009-03-28 19:18:32 +00005333 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005334 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5335 if (!Fn) {
5336 Diag(DelLoc, diag::err_deleted_non_function);
5337 return;
5338 }
5339 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5340 Diag(DelLoc, diag::err_deleted_decl_not_first);
5341 Diag(Prev->getLocation(), diag::note_previous_declaration);
5342 // If the declaration wasn't the first, we delete the function anyway for
5343 // recovery.
5344 }
5345 Fn->setDeleted();
5346}
Sebastian Redl13e88542009-04-27 21:33:24 +00005347
5348static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5349 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5350 ++CI) {
5351 Stmt *SubStmt = *CI;
5352 if (!SubStmt)
5353 continue;
5354 if (isa<ReturnStmt>(SubStmt))
5355 Self.Diag(SubStmt->getSourceRange().getBegin(),
5356 diag::err_return_in_constructor_handler);
5357 if (!isa<Expr>(SubStmt))
5358 SearchForReturnInStmt(Self, SubStmt);
5359 }
5360}
5361
5362void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5363 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5364 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5365 SearchForReturnInStmt(*this, Handler);
5366 }
5367}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005368
Mike Stump1eb44332009-09-09 15:08:12 +00005369bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005370 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005371 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5372 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005373
Chandler Carruth73857792010-02-15 11:53:20 +00005374 if (Context.hasSameType(NewTy, OldTy) ||
5375 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005376 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005378 // Check if the return types are covariant
5379 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005381 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005382 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5383 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005384 NewClassTy = NewPT->getPointeeType();
5385 OldClassTy = OldPT->getPointeeType();
5386 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005387 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5388 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5389 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5390 NewClassTy = NewRT->getPointeeType();
5391 OldClassTy = OldRT->getPointeeType();
5392 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005393 }
5394 }
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005396 // The return types aren't either both pointers or references to a class type.
5397 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005398 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005399 diag::err_different_return_type_for_overriding_virtual_function)
5400 << New->getDeclName() << NewTy << OldTy;
5401 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005403 return true;
5404 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005405
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005406 // C++ [class.virtual]p6:
5407 // If the return type of D::f differs from the return type of B::f, the
5408 // class type in the return type of D::f shall be complete at the point of
5409 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005410 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5411 if (!RT->isBeingDefined() &&
5412 RequireCompleteType(New->getLocation(), NewClassTy,
5413 PDiag(diag::err_covariant_return_incomplete)
5414 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005415 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005416 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005417
Douglas Gregora4923eb2009-11-16 21:35:15 +00005418 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005419 // Check if the new class derives from the old class.
5420 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5421 Diag(New->getLocation(),
5422 diag::err_covariant_return_not_derived)
5423 << New->getDeclName() << NewTy << OldTy;
5424 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5425 return true;
5426 }
Mike Stump1eb44332009-09-09 15:08:12 +00005427
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005428 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00005429 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00005430 diag::err_covariant_return_inaccessible_base,
5431 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5432 // FIXME: Should this point to the return type?
5433 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005434 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5435 return true;
5436 }
5437 }
Mike Stump1eb44332009-09-09 15:08:12 +00005438
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005439 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005440 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005441 Diag(New->getLocation(),
5442 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005443 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005444 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5445 return true;
5446 };
Mike Stump1eb44332009-09-09 15:08:12 +00005447
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005448
5449 // The new class type must have the same or less qualifiers as the old type.
5450 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5451 Diag(New->getLocation(),
5452 diag::err_covariant_return_type_class_type_more_qualified)
5453 << New->getDeclName() << NewTy << OldTy;
5454 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5455 return true;
5456 };
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005458 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005459}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005460
Sean Huntbbd37c62009-11-21 08:43:09 +00005461bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5462 const CXXMethodDecl *Old)
5463{
5464 if (Old->hasAttr<FinalAttr>()) {
5465 Diag(New->getLocation(), diag::err_final_function_overridden)
5466 << New->getDeclName();
5467 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5468 return true;
5469 }
5470
5471 return false;
5472}
5473
Douglas Gregor4ba31362009-12-01 17:24:26 +00005474/// \brief Mark the given method pure.
5475///
5476/// \param Method the method to be marked pure.
5477///
5478/// \param InitRange the source range that covers the "0" initializer.
5479bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5480 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5481 Method->setPure();
5482
5483 // A class is abstract if at least one function is pure virtual.
5484 Method->getParent()->setAbstract(true);
5485 return false;
5486 }
5487
5488 if (!Method->isInvalidDecl())
5489 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5490 << Method->getDeclName() << InitRange;
5491 return true;
5492}
5493
John McCall731ad842009-12-19 09:28:58 +00005494/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5495/// an initializer for the out-of-line declaration 'Dcl'. The scope
5496/// is a fresh scope pushed for just this purpose.
5497///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005498/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5499/// static data member of class X, names should be looked up in the scope of
5500/// class X.
5501void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005502 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005503 Decl *D = Dcl.getAs<Decl>();
5504 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005505
John McCall731ad842009-12-19 09:28:58 +00005506 // We should only get called for declarations with scope specifiers, like:
5507 // int foo::bar;
5508 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005509 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005510}
5511
5512/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005513/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005514void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005515 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005516 Decl *D = Dcl.getAs<Decl>();
5517 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005518
John McCall731ad842009-12-19 09:28:58 +00005519 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005520 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005521}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005522
5523/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5524/// C++ if/switch/while/for statement.
5525/// e.g: "if (int x = f()) {...}"
5526Action::DeclResult
5527Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5528 // C++ 6.4p2:
5529 // The declarator shall not specify a function or an array.
5530 // The type-specifier-seq shall not contain typedef and shall not declare a
5531 // new class or enumeration.
5532 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5533 "Parser allowed 'typedef' as storage class of condition decl.");
5534
John McCalla93c9342009-12-07 02:54:59 +00005535 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005536 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005537 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005538
5539 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5540 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5541 // would be created and CXXConditionDeclExpr wants a VarDecl.
5542 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5543 << D.getSourceRange();
5544 return DeclResult();
5545 } else if (OwnedTag && OwnedTag->isDefinition()) {
5546 // The type-specifier-seq shall not declare a new class or enumeration.
5547 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5548 }
5549
5550 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5551 if (!Dcl)
5552 return DeclResult();
5553
5554 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5555 VD->setDeclaredInCondition(true);
5556 return Dcl;
5557}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005558
Anders Carlsson046c2942010-04-17 20:15:18 +00005559static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005560 // Ignore dependent types.
5561 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005562 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005563
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005564 // Ignore declarations that are not definitions.
5565 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005566 return false;
5567
5568 CXXRecordDecl *RD = MD->getParent();
5569
5570 // Ignore classes without a vtable.
5571 if (!RD->isDynamicClass())
5572 return false;
5573
5574 switch (MD->getParent()->getTemplateSpecializationKind()) {
5575 case TSK_Undeclared:
5576 case TSK_ExplicitSpecialization:
5577 // Classes that aren't instantiations of templates don't need their
5578 // virtual methods marked until we see the definition of the key
5579 // function.
5580 break;
5581
5582 case TSK_ImplicitInstantiation:
5583 // This is a constructor of a class template; mark all of the virtual
5584 // members as referenced to ensure that they get instantiatied.
5585 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5586 return true;
5587 break;
5588
5589 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005590 return false;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005591
5592 case TSK_ExplicitInstantiationDefinition:
5593 // This is method of a explicit instantiation; mark all of the virtual
5594 // members as referenced to ensure that they get instantiatied.
5595 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005596 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005597
5598 // Consider only out-of-line definitions of member functions. When we see
5599 // an inline definition, it's too early to compute the key function.
5600 if (!MD->isOutOfLine())
5601 return false;
5602
5603 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5604
5605 // If there is no key function, we will need a copy of the vtable.
5606 if (!KeyFunction)
5607 return true;
5608
5609 // If this is the key function, we need to mark virtual members.
5610 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5611 return true;
5612
5613 return false;
5614}
5615
5616void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5617 CXXMethodDecl *MD) {
5618 CXXRecordDecl *RD = MD->getParent();
5619
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005620 // We will need to mark all of the virtual members as referenced to build the
5621 // vtable.
Anders Carlsson046c2942010-04-17 20:15:18 +00005622 if (!needsVTable(MD, Context))
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005623 return;
5624
5625 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5626 if (kind == TSK_ImplicitInstantiation)
5627 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5628 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005629 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005630}
5631
5632bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5633 if (ClassesWithUnmarkedVirtualMembers.empty())
5634 return false;
5635
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005636 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5637 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5638 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5639 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00005640 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005641 }
5642
Anders Carlssond6a637f2009-12-07 08:24:59 +00005643 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005644}
Anders Carlssond6a637f2009-12-07 08:24:59 +00005645
Rafael Espindola3e1ae932010-03-26 00:36:59 +00005646void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
5647 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00005648 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5649 e = RD->method_end(); i != e; ++i) {
5650 CXXMethodDecl *MD = *i;
5651
5652 // C++ [basic.def.odr]p2:
5653 // [...] A virtual member function is used if it is not pure. [...]
5654 if (MD->isVirtual() && !MD->isPure())
5655 MarkDeclarationReferenced(Loc, MD);
5656 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00005657
5658 // Only classes that have virtual bases need a VTT.
5659 if (RD->getNumVBases() == 0)
5660 return;
5661
5662 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
5663 e = RD->bases_end(); i != e; ++i) {
5664 const CXXRecordDecl *Base =
5665 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
5666 if (i->isVirtual())
5667 continue;
5668 if (Base->getNumVBases() == 0)
5669 continue;
5670 MarkVirtualMembersReferenced(Loc, Base);
5671 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00005672}