blob: 1ca7a728f0a3d951b4190fce1cb80c8fde6eff54 [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"
Douglas Gregor06a9f362010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.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 Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000026#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000031#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000032#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner8123a952008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattner9e979552008-04-12 23:52:44 +000040namespace {
41 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42 /// the default argument of a parameter to determine whether it
43 /// contains any ill-formed subexpressions. For example, this will
44 /// diagnose the use of local variables or parameters within the
45 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 public:
Mike Stump1eb44332009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000058 };
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 /// VisitExpr - Visit all of the children of this expression.
61 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000067 }
68
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitDeclRefExpr - Visit a reference to a declaration, to
70 /// determine whether this declaration can be used in the default
71 /// argument expression.
72 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000074 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75 // C++ [dcl.fct.default]p9
76 // Default arguments are evaluated each time the function is
77 // called. The order of evaluation of function arguments is
78 // unspecified. Consequently, parameters of a function shall not
79 // be used in default argument expressions, even if they are not
80 // evaluated. Parameters of a function declared before a default
81 // argument expression are in scope and can hide namespace and
82 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000094 }
Chris Lattner8123a952008-04-10 02:22:51 +000095
Douglas Gregor3996f232008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattner9e979552008-04-12 23:52:44 +000098
Douglas Gregor796da182008-11-04 14:32:21 +000099 /// VisitCXXThisExpr - Visit a C++ "this" expression.
100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101 // C++ [dcl.fct.default]p8:
102 // The keyword this shall not be used in a default argument of a
103 // member function.
104 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000107 }
Chris Lattner8123a952008-04-10 02:22:51 +0000108}
109
Anders Carlssoned961f92009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
132 MultiExprArg(*this, (void**)&Arg, 1));
133 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000134 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000136
Anders Carlsson0ece4912009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlssoned961f92009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson9351c172009-08-25 03:18:48 +0000144 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000145}
146
Chris Lattner8123a952008-04-10 02:22:51 +0000147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000150void
Mike Stump1eb44332009-09-09 15:08:12 +0000151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Chris Lattnerb28317a2009-03-28 19:18:32 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlsson66e30672009-08-25 01:02:06 +0000169 // Check that the default argument is well-formed
170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171 if (DefaultArgChecker.Visit(DefaultArg.get())) {
172 Param->setInvalidDecl();
173 return;
174 }
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlssoned961f92009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177}
178
Douglas Gregor61366e92008-12-24 00:01:03 +0000179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Chris Lattnerb28317a2009-03-28 19:18:32 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Anders Carlsson5e300d12009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000194}
195
Douglas Gregor72b505b2008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlsson5e300d12009-06-12 16:51:40 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Anders Carlsson5e300d12009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000207}
208
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215 // C++ [dcl.fct.default]p3
216 // A default argument expression shall be specified only in the
217 // parameter-declaration-clause of a function declaration or in a
218 // template-parameter (14.1). It shall not be specified for a
219 // parameter pack. If it is specified in a
220 // parameter-declaration-clause, it shall not occur within a
221 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226 ParmVarDecl *Param =
227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232 delete Toks;
233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000234 } else if (Param->getDefaultArg()) {
235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236 << Param->getDefaultArg()->getSourceRange();
237 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249 bool Invalid = false;
250
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000252 // For non-template functions, default arguments can be added in
253 // later declarations of a function in the same
254 // scope. Declarations in different scopes have completely
255 // distinct sets of default arguments. That is, declarations in
256 // inner scopes do not acquire default arguments from
257 // declarations in outer scopes, and vice versa. In a given
258 // function declaration, all parameters subsequent to a
259 // parameter with a default argument shall have default
260 // arguments supplied in this or previous declarations. A
261 // default argument shall not be redefined by a later
262 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000263 //
264 // C++ [dcl.fct.default]p6:
265 // Except for member functions of class templates, the default arguments
266 // in a member function definition that appears outside of the class
267 // definition are added to the set of default arguments provided by the
268 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270 ParmVarDecl *OldParam = Old->getParamDecl(p);
271 ParmVarDecl *NewParam = New->getParamDecl(p);
272
Douglas Gregor6cc15182009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275 // hint here. Alternatively, we could walk the type-source information
276 // for NewParam to find the last source location in the type... but it
277 // isn't worth the effort right now. This is the kind of test case that
278 // is hard to get right:
279
280 // int f(int);
281 // void g(int (*fp)(int) = f);
282 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000286
287 // Look for the function declaration where the default argument was
288 // actually written, which may be a declaration prior to Old.
289 for (FunctionDecl *Older = Old->getPreviousDeclaration();
290 Older; Older = Older->getPreviousDeclaration()) {
291 if (!Older->getParamDecl(p)->hasDefaultArg())
292 break;
293
294 OldParam = Older->getParamDecl(p);
295 }
296
297 Diag(OldParam->getLocation(), diag::note_previous_definition)
298 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000301 // Merge the old default argument into the new parameter
John McCallbf73b352010-03-12 18:31:32 +0000302 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000303 if (OldParam->hasUninstantiatedDefaultArg())
304 NewParam->setUninstantiatedDefaultArg(
305 OldParam->getUninstantiatedDefaultArg());
306 else
307 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000308 } else if (NewParam->hasDefaultArg()) {
309 if (New->getDescribedFunctionTemplate()) {
310 // Paragraph 4, quoted above, only applies to non-template functions.
311 Diag(NewParam->getLocation(),
312 diag::err_param_default_argument_template_redecl)
313 << NewParam->getDefaultArgRange();
314 Diag(Old->getLocation(), diag::note_template_prev_declaration)
315 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000316 } else if (New->getTemplateSpecializationKind()
317 != TSK_ImplicitInstantiation &&
318 New->getTemplateSpecializationKind() != TSK_Undeclared) {
319 // C++ [temp.expr.spec]p21:
320 // Default function arguments shall not be specified in a declaration
321 // or a definition for one of the following explicit specializations:
322 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000323 // - the explicit specialization of a member function template;
324 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000325 // template where the class template specialization to which the
326 // member function specialization belongs is implicitly
327 // instantiated.
328 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
329 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
330 << New->getDeclName()
331 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000332 } else if (New->getDeclContext()->isDependentContext()) {
333 // C++ [dcl.fct.default]p6 (DR217):
334 // Default arguments for a member function of a class template shall
335 // be specified on the initial declaration of the member function
336 // within the class template.
337 //
338 // Reading the tea leaves a bit in DR217 and its reference to DR205
339 // leads me to the conclusion that one cannot add default function
340 // arguments for an out-of-line definition of a member function of a
341 // dependent type.
342 int WhichKind = 2;
343 if (CXXRecordDecl *Record
344 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
345 if (Record->getDescribedClassTemplate())
346 WhichKind = 0;
347 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
348 WhichKind = 1;
349 else
350 WhichKind = 2;
351 }
352
353 Diag(NewParam->getLocation(),
354 diag::err_param_default_argument_member_template_redecl)
355 << WhichKind
356 << NewParam->getDefaultArgRange();
357 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000358 }
359 }
360
Douglas Gregore13ad832010-02-12 07:32:17 +0000361 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000363
Douglas Gregorcda9c672009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000397 else
Mike Stump1eb44332009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000436 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump1eb44332009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000450 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451 SourceLocation BaseLoc) {
452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000462 Class->getTagKind() == RecordDecl::TK_class,
463 Access, BaseType);
464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000484 return 0;
485
Eli Friedman1d954f62009-08-15 21:55:26 +0000486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000489 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000493
Sean Huntbbd37c62009-11-21 08:43:09 +0000494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000499 return 0;
500 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000501
Eli Friedmand0137332009-12-05 23:03:49 +0000502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlsson51f94042009-12-03 17:49:57 +0000503
504 // Create the base specifier.
505 // FIXME: Allocate via ASTContext?
506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 Class->getTagKind() == RecordDecl::TK_class,
508 Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 const CXXRecordDecl *BaseClass,
513 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000514 // A class with a non-empty base class is not empty.
515 // FIXME: Standard ref?
516 if (!BaseClass->isEmpty())
517 Class->setEmpty(false);
518
519 // C++ [class.virtual]p1:
520 // A class that [...] inherits a virtual function is called a polymorphic
521 // class.
522 if (BaseClass->isPolymorphic())
523 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000524
Douglas Gregor2943aed2009-03-03 04:44:36 +0000525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is [...] a class with [...] no base classes [...].
527 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531 Class->setPOD(false);
532
Anders Carlsson51f94042009-12-03 17:49:57 +0000533 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000534 // C++ [class.ctor]p5:
535 // A constructor is trivial if its class has no virtual base classes.
536 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000537
538 // C++ [class.copy]p6:
539 // A copy constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialCopyConstructor(false);
541
542 // C++ [class.copy]p11:
543 // A copy assignment operator is trivial if its class has no virtual
544 // base classes.
545 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000546
547 // C++0x [meta.unary.prop] is_empty:
548 // T is a class type, but not a union type, with ... no virtual base
549 // classes
550 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000551 } else {
552 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000554 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000556 Class->setHasTrivialConstructor(false);
557
558 // C++ [class.copy]p6:
559 // A copy constructor is trivial if all the direct base classes of its
560 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000562 Class->setHasTrivialCopyConstructor(false);
563
564 // C++ [class.copy]p11:
565 // A copy assignment operator is trivial if all the direct base classes
566 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000567 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000568 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000569 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000570
571 // C++ [class.ctor]p3:
572 // A destructor is trivial if all the direct base classes of its class
573 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000575 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000576}
577
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000580/// example:
581/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000582/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000583Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000587 if (!classdecl)
588 return true;
589
Douglas Gregor40808ce2009-03-09 23:48:35 +0000590 AdjustDeclIfTemplate(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000591 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
592 if (!Class)
593 return true;
594
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000595 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000596 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
597 Virtual, Access,
598 BaseType, BaseLoc))
599 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000602}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000603
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604/// \brief Performs the actual work of attaching the given base class
605/// specifiers to a C++ class.
606bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
607 unsigned NumBases) {
608 if (NumBases == 0)
609 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000610
611 // Used to keep track of which base types we have already seen, so
612 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000613 // that the key is always the unqualified canonical type of the base
614 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000615 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
616
617 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000618 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000619 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000620 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000621 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000622 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000623 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000624
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000625 if (KnownBaseTypes[NewBaseType]) {
626 // C++ [class.mi]p3:
627 // A class shall not be specified as a direct base class of a
628 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000630 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000631 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000632 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000633
634 // Delete the duplicate base class specifier; we're going to
635 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000636 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000637
638 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000639 } else {
640 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000641 KnownBaseTypes[NewBaseType] = Bases[idx];
642 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000643 }
644 }
645
646 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000647 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000648
649 // Delete the remaining (good) base class specifiers, since their
650 // data has been copied into the CXXRecordDecl.
651 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000652 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000653
654 return Invalid;
655}
656
657/// ActOnBaseSpecifiers - Attach the given base specifiers to the
658/// class, after checking whether there are any duplicate base
659/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000660void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000661 unsigned NumBases) {
662 if (!ClassDecl || !Bases || !NumBases)
663 return;
664
665 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000666 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000667 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000668}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000669
John McCall3cb0ebd2010-03-10 03:28:59 +0000670static CXXRecordDecl *GetClassForType(QualType T) {
671 if (const RecordType *RT = T->getAs<RecordType>())
672 return cast<CXXRecordDecl>(RT->getDecl());
673 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
674 return ICT->getDecl();
675 else
676 return 0;
677}
678
Douglas Gregora8f32e02009-10-06 17:59:45 +0000679/// \brief Determine whether the type \p Derived is a C++ class that is
680/// derived from the type \p Base.
681bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
682 if (!getLangOptions().CPlusPlus)
683 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000684
685 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
686 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000687 return false;
688
John McCall3cb0ebd2010-03-10 03:28:59 +0000689 CXXRecordDecl *BaseRD = GetClassForType(Base);
690 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000691 return false;
692
John McCall86ff3082010-02-04 22:26:26 +0000693 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
694 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000695}
696
697/// \brief Determine whether the type \p Derived is a C++ class that is
698/// derived from the type \p Base.
699bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
700 if (!getLangOptions().CPlusPlus)
701 return false;
702
John McCall3cb0ebd2010-03-10 03:28:59 +0000703 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
704 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000705 return false;
706
John McCall3cb0ebd2010-03-10 03:28:59 +0000707 CXXRecordDecl *BaseRD = GetClassForType(Base);
708 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709 return false;
710
Douglas Gregora8f32e02009-10-06 17:59:45 +0000711 return DerivedRD->isDerivedFrom(BaseRD, Paths);
712}
713
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000714void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
715 CXXBaseSpecifierArray &BasePathArray) {
716 assert(BasePathArray.empty() && "Base path array must be empty!");
717 assert(Paths.isRecordingPaths() && "Must record paths!");
718
719 const CXXBasePath &Path = Paths.front();
720
721 // We first go backward and check if we have a virtual base.
722 // FIXME: It would be better if CXXBasePath had the base specifier for
723 // the nearest virtual base.
724 unsigned Start = 0;
725 for (unsigned I = Path.size(); I != 0; --I) {
726 if (Path[I - 1].Base->isVirtual()) {
727 Start = I - 1;
728 break;
729 }
730 }
731
732 // Now add all bases.
733 for (unsigned I = Start, E = Path.size(); I != E; ++I)
734 BasePathArray.push_back(Path[I].Base);
735}
736
Douglas Gregora8f32e02009-10-06 17:59:45 +0000737/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
738/// conversion (where Derived and Base are class types) is
739/// well-formed, meaning that the conversion is unambiguous (and
740/// that all of the base classes are accessible). Returns true
741/// and emits a diagnostic if the code is ill-formed, returns false
742/// otherwise. Loc is the location where this routine should point to
743/// if there is an error, and Range is the source range to highlight
744/// if there is an error.
745bool
746Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000747 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000748 unsigned AmbigiousBaseConvID,
749 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000750 DeclarationName Name,
751 CXXBaseSpecifierArray *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000752 // First, determine whether the path from Derived to Base is
753 // ambiguous. This is slightly more expensive than checking whether
754 // the Derived to Base conversion exists, because here we need to
755 // explore multiple paths to determine if there is an ambiguity.
756 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
757 /*DetectVirtual=*/false);
758 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
759 assert(DerivationOkay &&
760 "Can only be used with a derived-to-base conversion");
761 (void)DerivationOkay;
762
763 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000764 if (InaccessibleBaseID) {
765 // Check that the base class can be accessed.
766 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
767 InaccessibleBaseID)) {
768 case AR_inaccessible:
769 return true;
770 case AR_accessible:
771 case AR_dependent:
772 case AR_delayed:
773 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000774 }
John McCall6b2accb2010-02-10 09:31:12 +0000775 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000776
777 // Build a base path if necessary.
778 if (BasePath)
779 BuildBasePathArray(Paths, *BasePath);
780 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000781 }
782
783 // We know that the derived-to-base conversion is ambiguous, and
784 // we're going to produce a diagnostic. Perform the derived-to-base
785 // search just one more time to compute all of the possible paths so
786 // that we can print them out. This is more expensive than any of
787 // the previous derived-to-base checks we've done, but at this point
788 // performance isn't as much of an issue.
789 Paths.clear();
790 Paths.setRecordingPaths(true);
791 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
792 assert(StillOkay && "Can only be used with a derived-to-base conversion");
793 (void)StillOkay;
794
795 // Build up a textual representation of the ambiguous paths, e.g.,
796 // D -> B -> A, that will be used to illustrate the ambiguous
797 // conversions in the diagnostic. We only print one of the paths
798 // to each base class subobject.
799 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
800
801 Diag(Loc, AmbigiousBaseConvID)
802 << Derived << Base << PathDisplayStr << Range << Name;
803 return true;
804}
805
806bool
807Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000808 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000809 CXXBaseSpecifierArray *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000810 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000811 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000812 IgnoreAccess ? 0
813 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000814 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000815 Loc, Range, DeclarationName(),
816 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000817}
818
819
820/// @brief Builds a string representing ambiguous paths from a
821/// specific derived class to different subobjects of the same base
822/// class.
823///
824/// This function builds a string that can be used in error messages
825/// to show the different paths that one can take through the
826/// inheritance hierarchy to go from the derived class to different
827/// subobjects of a base class. The result looks something like this:
828/// @code
829/// struct D -> struct B -> struct A
830/// struct D -> struct C -> struct A
831/// @endcode
832std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
833 std::string PathDisplayStr;
834 std::set<unsigned> DisplayedPaths;
835 for (CXXBasePaths::paths_iterator Path = Paths.begin();
836 Path != Paths.end(); ++Path) {
837 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
838 // We haven't displayed a path to this particular base
839 // class subobject yet.
840 PathDisplayStr += "\n ";
841 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
842 for (CXXBasePath::const_iterator Element = Path->begin();
843 Element != Path->end(); ++Element)
844 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
845 }
846 }
847
848 return PathDisplayStr;
849}
850
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000851//===----------------------------------------------------------------------===//
852// C++ class member Handling
853//===----------------------------------------------------------------------===//
854
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000855/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
856/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
857/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000858/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000859Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000865 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000866 Expr *BitWidth = static_cast<Expr*>(BW);
867 Expr *Init = static_cast<Expr*>(InitExpr);
868 SourceLocation Loc = D.getIdentifierLoc();
869
Sebastian Redl669d5d72008-11-14 23:42:31 +0000870 bool isFunc = D.isFunctionDeclarator();
871
John McCall67d1a672009-08-06 02:15:43 +0000872 assert(!DS.isFriendSpecified());
873
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000874 // C++ 9.2p6: A member shall not be declared to have automatic storage
875 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000876 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
877 // data members and cannot be applied to names declared const or static,
878 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000879 switch (DS.getStorageClassSpec()) {
880 case DeclSpec::SCS_unspecified:
881 case DeclSpec::SCS_typedef:
882 case DeclSpec::SCS_static:
883 // FALL THROUGH.
884 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000885 case DeclSpec::SCS_mutable:
886 if (isFunc) {
887 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000888 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000889 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000890 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Sebastian Redla11f42f2008-11-17 23:24:37 +0000892 // FIXME: It would be nicer if the keyword was ignored only for this
893 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000894 D.getMutableDeclSpec().ClearStorageClassSpecs();
895 } else {
896 QualType T = GetTypeForDeclarator(D, S);
897 diag::kind err = static_cast<diag::kind>(0);
898 if (T->isReferenceType())
899 err = diag::err_mutable_reference;
900 else if (T.isConstQualified())
901 err = diag::err_mutable_const;
902 if (err != 0) {
903 if (DS.getStorageClassSpecLoc().isValid())
904 Diag(DS.getStorageClassSpecLoc(), err);
905 else
906 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000907 // FIXME: It would be nicer if the keyword was ignored only for this
908 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000909 D.getMutableDeclSpec().ClearStorageClassSpecs();
910 }
911 }
912 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000913 default:
914 if (DS.getStorageClassSpecLoc().isValid())
915 Diag(DS.getStorageClassSpecLoc(),
916 diag::err_storageclass_invalid_for_member);
917 else
918 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
919 D.getMutableDeclSpec().ClearStorageClassSpecs();
920 }
921
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000922 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000923 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000924 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000925 // Check also for this case:
926 //
927 // typedef int f();
928 // f a;
929 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000930 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000931 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000932 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000933
Sebastian Redl669d5d72008-11-14 23:42:31 +0000934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000936 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000937
938 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000939 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000940 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000941 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
942 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000943 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000944 } else {
Sebastian Redld1a78462009-11-24 23:38:44 +0000945 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor37b372b2009-08-20 22:52:58 +0000946 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000947 if (!Member) {
948 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000949 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000950 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000951
952 // Non-instance-fields can't have a bitfield.
953 if (BitWidth) {
954 if (Member->isInvalidDecl()) {
955 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000956 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000957 // C++ 9.6p3: A bit-field shall not be a static member.
958 // "static member 'A' cannot be a bit-field"
959 Diag(Loc, diag::err_static_not_bitfield)
960 << Name << BitWidth->getSourceRange();
961 } else if (isa<TypedefDecl>(Member)) {
962 // "typedef member 'x' cannot be a bit-field"
963 Diag(Loc, diag::err_typedef_not_bitfield)
964 << Name << BitWidth->getSourceRange();
965 } else {
966 // A function typedef ("typedef int f(); f a;").
967 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
968 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000969 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000970 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000971 }
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Chris Lattner8b963ef2009-03-05 23:01:03 +0000973 DeleteExpr(BitWidth);
974 BitWidth = 0;
975 Member->setInvalidDecl();
976 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000977
978 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor37b372b2009-08-20 22:52:58 +0000980 // If we have declared a member function template, set the access of the
981 // templated declaration as well.
982 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
983 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000984 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000985
Douglas Gregor10bd3682008-11-17 22:58:34 +0000986 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000987
Douglas Gregor021c3b32009-03-11 23:00:04 +0000988 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000989 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000990 if (Deleted) // FIXME: Source location is not very good.
991 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000993 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000994 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000995 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000996 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000997 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998}
999
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001000/// \brief Find the direct and/or virtual base specifiers that
1001/// correspond to the given base type, for use in base initialization
1002/// within a constructor.
1003static bool FindBaseInitializer(Sema &SemaRef,
1004 CXXRecordDecl *ClassDecl,
1005 QualType BaseType,
1006 const CXXBaseSpecifier *&DirectBaseSpec,
1007 const CXXBaseSpecifier *&VirtualBaseSpec) {
1008 // First, check for a direct base class.
1009 DirectBaseSpec = 0;
1010 for (CXXRecordDecl::base_class_const_iterator Base
1011 = ClassDecl->bases_begin();
1012 Base != ClassDecl->bases_end(); ++Base) {
1013 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1014 // We found a direct base of this type. That's what we're
1015 // initializing.
1016 DirectBaseSpec = &*Base;
1017 break;
1018 }
1019 }
1020
1021 // Check for a virtual base class.
1022 // FIXME: We might be able to short-circuit this if we know in advance that
1023 // there are no virtual bases.
1024 VirtualBaseSpec = 0;
1025 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1026 // We haven't found a base yet; search the class hierarchy for a
1027 // virtual base class.
1028 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1029 /*DetectVirtual=*/false);
1030 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1031 BaseType, Paths)) {
1032 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1033 Path != Paths.end(); ++Path) {
1034 if (Path->back().Base->isVirtual()) {
1035 VirtualBaseSpec = Path->back().Base;
1036 break;
1037 }
1038 }
1039 }
1040 }
1041
1042 return DirectBaseSpec || VirtualBaseSpec;
1043}
1044
Douglas Gregor7ad83902008-11-05 04:29:56 +00001045/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001046Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +00001047Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001048 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001049 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001050 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001051 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001052 SourceLocation IdLoc,
1053 SourceLocation LParenLoc,
1054 ExprTy **Args, unsigned NumArgs,
1055 SourceLocation *CommaLocs,
1056 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001057 if (!ConstructorD)
1058 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001060 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
1062 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +00001063 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +00001064 if (!Constructor) {
1065 // The user wrote a constructor initializer on a function that is
1066 // not a C++ constructor. Ignore the error for now, because we may
1067 // have more member initializers coming; we'll diagnose it just
1068 // once in ActOnMemInitializers.
1069 return true;
1070 }
1071
1072 CXXRecordDecl *ClassDecl = Constructor->getParent();
1073
1074 // C++ [class.base.init]p2:
1075 // Names in a mem-initializer-id are looked up in the scope of the
1076 // constructor’s class and, if not found in that scope, are looked
1077 // up in the scope containing the constructor’s
1078 // definition. [Note: if the constructor’s class contains a member
1079 // with the same name as a direct or virtual base class of the
1080 // class, a mem-initializer-id naming the member or base class and
1081 // composed of a single identifier refers to the class member. A
1082 // mem-initializer-id for the hidden base class may be specified
1083 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001084 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001085 // Look for a member, first.
1086 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001087 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001088 = ClassDecl->lookup(MemberOrBase);
1089 if (Result.first != Result.second)
1090 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001091
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001092 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001093
Eli Friedman59c04372009-07-29 19:44:27 +00001094 if (Member)
1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001096 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001097 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001098 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001099 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001100 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001101
1102 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001103 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001104 } else {
1105 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1106 LookupParsedName(R, S, &SS);
1107
1108 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1109 if (!TyD) {
1110 if (R.isAmbiguous()) return true;
1111
John McCallfd225442010-04-09 19:01:14 +00001112 // We don't want access-control diagnostics here.
1113 R.suppressDiagnostics();
1114
Douglas Gregor7a886e12010-01-19 06:46:48 +00001115 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1116 bool NotUnknownSpecialization = false;
1117 DeclContext *DC = computeDeclContext(SS, false);
1118 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1119 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1120
1121 if (!NotUnknownSpecialization) {
1122 // When the scope specifier can refer to a member of an unknown
1123 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001124 BaseType = CheckTypenameType(ETK_None,
1125 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregor7a886e12010-01-19 06:46:48 +00001126 *MemberOrBase, SS.getRange());
Douglas Gregora50ce322010-03-07 23:26:22 +00001127 if (BaseType.isNull())
1128 return true;
1129
Douglas Gregor7a886e12010-01-19 06:46:48 +00001130 R.clear();
1131 }
1132 }
1133
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001134 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001135 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001136 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1137 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001138 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1139 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1140 // We have found a non-static data member with a similar
1141 // name to what was typed; complain and initialize that
1142 // member.
1143 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1144 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001145 << FixItHint::CreateReplacement(R.getNameLoc(),
1146 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001147 Diag(Member->getLocation(), diag::note_previous_decl)
1148 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001149
1150 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1151 LParenLoc, RParenLoc);
1152 }
1153 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1154 const CXXBaseSpecifier *DirectBaseSpec;
1155 const CXXBaseSpecifier *VirtualBaseSpec;
1156 if (FindBaseInitializer(*this, ClassDecl,
1157 Context.getTypeDeclType(Type),
1158 DirectBaseSpec, VirtualBaseSpec)) {
1159 // We have found a direct or virtual base class with a
1160 // similar name to what was typed; complain and initialize
1161 // that base class.
1162 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1163 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001164 << FixItHint::CreateReplacement(R.getNameLoc(),
1165 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001166
1167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1168 : VirtualBaseSpec;
1169 Diag(BaseSpec->getSourceRange().getBegin(),
1170 diag::note_base_class_specified_here)
1171 << BaseSpec->getType()
1172 << BaseSpec->getSourceRange();
1173
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001174 TyD = Type;
1175 }
1176 }
1177 }
1178
Douglas Gregor7a886e12010-01-19 06:46:48 +00001179 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001180 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1181 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1182 return true;
1183 }
John McCall2b194412009-12-21 10:41:20 +00001184 }
1185
Douglas Gregor7a886e12010-01-19 06:46:48 +00001186 if (BaseType.isNull()) {
1187 BaseType = Context.getTypeDeclType(TyD);
1188 if (SS.isSet()) {
1189 NestedNameSpecifier *Qualifier =
1190 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001191
Douglas Gregor7a886e12010-01-19 06:46:48 +00001192 // FIXME: preserve source range information
1193 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1194 }
John McCall2b194412009-12-21 10:41:20 +00001195 }
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
John McCalla93c9342009-12-07 02:54:59 +00001198 if (!TInfo)
1199 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001200
John McCalla93c9342009-12-07 02:54:59 +00001201 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001202 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001203}
1204
John McCallb4190042009-11-04 23:02:40 +00001205/// Checks an initializer expression for use of uninitialized fields, such as
1206/// containing the field that is being initialized. Returns true if there is an
1207/// uninitialized field was used an updates the SourceLocation parameter; false
1208/// otherwise.
1209static bool InitExprContainsUninitializedFields(const Stmt* S,
1210 const FieldDecl* LhsField,
1211 SourceLocation* L) {
1212 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1213 if (ME) {
1214 const NamedDecl* RhsField = ME->getMemberDecl();
1215 if (RhsField == LhsField) {
1216 // Initializing a field with itself. Throw a warning.
1217 // But wait; there are exceptions!
1218 // Exception #1: The field may not belong to this record.
1219 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1220 const Expr* base = ME->getBase();
1221 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1222 // Even though the field matches, it does not belong to this record.
1223 return false;
1224 }
1225 // None of the exceptions triggered; return true to indicate an
1226 // uninitialized field was used.
1227 *L = ME->getMemberLoc();
1228 return true;
1229 }
1230 }
1231 bool found = false;
1232 for (Stmt::const_child_iterator it = S->child_begin();
1233 it != S->child_end() && found == false;
1234 ++it) {
1235 if (isa<CallExpr>(S)) {
1236 // Do not descend into function calls or constructors, as the use
1237 // of an uninitialized field may be valid. One would have to inspect
1238 // the contents of the function/ctor to determine if it is safe or not.
1239 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1240 // may be safe, depending on what the function/ctor does.
1241 continue;
1242 }
1243 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1244 }
1245 return found;
1246}
1247
Eli Friedman59c04372009-07-29 19:44:27 +00001248Sema::MemInitResult
1249Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1250 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001251 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001252 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001253 // Diagnose value-uses of fields to initialize themselves, e.g.
1254 // foo(foo)
1255 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001256 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001257 for (unsigned i = 0; i < NumArgs; ++i) {
1258 SourceLocation L;
1259 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1260 // FIXME: Return true in the case when other fields are used before being
1261 // uninitialized. For example, let this field be the i'th field. When
1262 // initializing the i'th field, throw a warning if any of the >= i'th
1263 // fields are used, as they are not yet initialized.
1264 // Right now we are only handling the case where the i'th field uses
1265 // itself in its initializer.
1266 Diag(L, diag::warn_field_is_uninit);
1267 }
1268 }
1269
Eli Friedman59c04372009-07-29 19:44:27 +00001270 bool HasDependentArg = false;
1271 for (unsigned i = 0; i < NumArgs; i++)
1272 HasDependentArg |= Args[i]->isTypeDependent();
1273
Eli Friedman59c04372009-07-29 19:44:27 +00001274 QualType FieldType = Member->getType();
1275 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1276 FieldType = Array->getElementType();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001277 if (FieldType->isDependentType() || HasDependentArg) {
1278 // Can't check initialization for a member of dependent type or when
1279 // any of the arguments are type-dependent expressions.
1280 OwningExprResult Init
1281 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1282 RParenLoc));
1283
1284 // Erase any temporaries within this evaluation context; we're not
1285 // going to track them in the AST, since we'll be rebuilding the
1286 // ASTs during template instantiation.
1287 ExprTemporaries.erase(
1288 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1289 ExprTemporaries.end());
1290
1291 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1292 LParenLoc,
1293 Init.takeAs<Expr>(),
1294 RParenLoc);
1295
Douglas Gregor7ad83902008-11-05 04:29:56 +00001296 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001297
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001298 if (Member->isInvalidDecl())
1299 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001300
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001301 // Initialize the member.
1302 InitializedEntity MemberEntity =
1303 InitializedEntity::InitializeMember(Member, 0);
1304 InitializationKind Kind =
1305 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1306
1307 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1308
1309 OwningExprResult MemberInit =
1310 InitSeq.Perform(*this, MemberEntity, Kind,
1311 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1312 if (MemberInit.isInvalid())
1313 return true;
1314
1315 // C++0x [class.base.init]p7:
1316 // The initialization of each base and member constitutes a
1317 // full-expression.
1318 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1319 if (MemberInit.isInvalid())
1320 return true;
1321
1322 // If we are in a dependent context, template instantiation will
1323 // perform this type-checking again. Just save the arguments that we
1324 // received in a ParenListExpr.
1325 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1326 // of the information that we have about the member
1327 // initializer. However, deconstructing the ASTs is a dicey process,
1328 // and this approach is far more likely to get the corner cases right.
1329 if (CurContext->isDependentContext()) {
1330 // Bump the reference count of all of the arguments.
1331 for (unsigned I = 0; I != NumArgs; ++I)
1332 Args[I]->Retain();
1333
1334 OwningExprResult Init
1335 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1336 RParenLoc));
1337 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1338 LParenLoc,
1339 Init.takeAs<Expr>(),
1340 RParenLoc);
1341 }
1342
Douglas Gregor802ab452009-12-02 22:36:29 +00001343 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001344 LParenLoc,
1345 MemberInit.takeAs<Expr>(),
1346 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001347}
1348
1349Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001350Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001351 Expr **Args, unsigned NumArgs,
1352 SourceLocation LParenLoc, SourceLocation RParenLoc,
1353 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001354 bool HasDependentArg = false;
1355 for (unsigned i = 0; i < NumArgs; i++)
1356 HasDependentArg |= Args[i]->isTypeDependent();
1357
John McCalla93c9342009-12-07 02:54:59 +00001358 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001359 if (BaseType->isDependentType() || HasDependentArg) {
1360 // Can't check initialization for a base of dependent type or when
1361 // any of the arguments are type-dependent expressions.
1362 OwningExprResult BaseInit
1363 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1364 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001365
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001366 // Erase any temporaries within this evaluation context; we're not
1367 // going to track them in the AST, since we'll be rebuilding the
1368 // ASTs during template instantiation.
1369 ExprTemporaries.erase(
1370 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1371 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001373 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001374 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001375 LParenLoc,
1376 BaseInit.takeAs<Expr>(),
1377 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001378 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001379
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001380 if (!BaseType->isRecordType())
1381 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1382 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1383
1384 // C++ [class.base.init]p2:
1385 // [...] Unless the mem-initializer-id names a nonstatic data
1386 // member of the constructor’s class or a direct or virtual base
1387 // of that class, the mem-initializer is ill-formed. A
1388 // mem-initializer-list can initialize a base class using any
1389 // name that denotes that base class type.
1390
1391 // Check for direct and virtual base classes.
1392 const CXXBaseSpecifier *DirectBaseSpec = 0;
1393 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1394 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1395 VirtualBaseSpec);
1396
1397 // C++ [base.class.init]p2:
1398 // If a mem-initializer-id is ambiguous because it designates both
1399 // a direct non-virtual base class and an inherited virtual base
1400 // class, the mem-initializer is ill-formed.
1401 if (DirectBaseSpec && VirtualBaseSpec)
1402 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1403 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1404 // C++ [base.class.init]p2:
1405 // Unless the mem-initializer-id names a nonstatic data membeer of the
1406 // constructor's class ot a direst or virtual base of that class, the
1407 // mem-initializer is ill-formed.
1408 if (!DirectBaseSpec && !VirtualBaseSpec)
1409 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall110acc12010-04-27 01:43:38 +00001410 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001411 << BaseTInfo->getTypeLoc().getSourceRange();
1412
1413 CXXBaseSpecifier *BaseSpec
1414 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1415 if (!BaseSpec)
1416 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1417
1418 // Initialize the base.
1419 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001420 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001421 InitializationKind Kind =
1422 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1423
1424 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1425
1426 OwningExprResult BaseInit =
1427 InitSeq.Perform(*this, BaseEntity, Kind,
1428 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1429 if (BaseInit.isInvalid())
1430 return true;
1431
1432 // C++0x [class.base.init]p7:
1433 // The initialization of each base and member constitutes a
1434 // full-expression.
1435 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1436 if (BaseInit.isInvalid())
1437 return true;
1438
1439 // If we are in a dependent context, template instantiation will
1440 // perform this type-checking again. Just save the arguments that we
1441 // received in a ParenListExpr.
1442 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1443 // of the information that we have about the base
1444 // initializer. However, deconstructing the ASTs is a dicey process,
1445 // and this approach is far more likely to get the corner cases right.
1446 if (CurContext->isDependentContext()) {
1447 // Bump the reference count of all of the arguments.
1448 for (unsigned I = 0; I != NumArgs; ++I)
1449 Args[I]->Retain();
1450
1451 OwningExprResult Init
1452 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1453 RParenLoc));
1454 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001455 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001456 LParenLoc,
1457 Init.takeAs<Expr>(),
1458 RParenLoc);
1459 }
1460
1461 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001462 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001463 LParenLoc,
1464 BaseInit.takeAs<Expr>(),
1465 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001466}
1467
Anders Carlssone5ef7402010-04-23 03:10:23 +00001468/// ImplicitInitializerKind - How an implicit base or member initializer should
1469/// initialize its base or member.
1470enum ImplicitInitializerKind {
1471 IIK_Default,
1472 IIK_Copy,
1473 IIK_Move
1474};
1475
Anders Carlssondefefd22010-04-23 02:00:02 +00001476static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001477BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001478 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001479 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001480 bool IsInheritedVirtualBase,
1481 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001482 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001483 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1484 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001485
Anders Carlssone5ef7402010-04-23 03:10:23 +00001486 Sema::OwningExprResult BaseInit(SemaRef);
1487
1488 switch (ImplicitInitKind) {
1489 case IIK_Default: {
1490 InitializationKind InitKind
1491 = InitializationKind::CreateDefault(Constructor->getLocation());
1492 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1493 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1494 Sema::MultiExprArg(SemaRef, 0, 0));
1495 break;
1496 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001497
Anders Carlssone5ef7402010-04-23 03:10:23 +00001498 case IIK_Copy: {
1499 ParmVarDecl *Param = Constructor->getParamDecl(0);
1500 QualType ParamType = Param->getType().getNonReferenceType();
1501
1502 Expr *CopyCtorArg =
1503 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1504 SourceLocation(), ParamType, 0);
1505
Anders Carlssonc7957502010-04-24 22:02:54 +00001506 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001507 QualType ArgTy =
1508 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1509 ParamType.getQualifiers());
1510 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonc7957502010-04-24 22:02:54 +00001511 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson8f2abbc2010-04-24 22:54:32 +00001512 /*isLvalue=*/true,
1513 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonc7957502010-04-24 22:02:54 +00001514
Anders Carlssone5ef7402010-04-23 03:10:23 +00001515 InitializationKind InitKind
1516 = InitializationKind::CreateDirect(Constructor->getLocation(),
1517 SourceLocation(), SourceLocation());
1518 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1519 &CopyCtorArg, 1);
1520 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1521 Sema::MultiExprArg(SemaRef,
1522 (void**)&CopyCtorArg, 1));
1523 break;
1524 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001525
Anders Carlssone5ef7402010-04-23 03:10:23 +00001526 case IIK_Move:
1527 assert(false && "Unhandled initializer kind!");
1528 }
1529
Anders Carlsson84688f22010-04-20 23:11:20 +00001530 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1531 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001532 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001533
Anders Carlssondefefd22010-04-23 02:00:02 +00001534 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001535 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1536 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1537 SourceLocation()),
1538 BaseSpec->isVirtual(),
1539 SourceLocation(),
1540 BaseInit.takeAs<Expr>(),
1541 SourceLocation());
1542
Anders Carlssondefefd22010-04-23 02:00:02 +00001543 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001544}
1545
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001546static bool
1547BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001548 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001549 FieldDecl *Field,
1550 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001551 if (ImplicitInitKind == IIK_Copy) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00001552 // FIXME: We should not return early here, but will do so until
1553 // we know how to handle copy initialization of arrays.
1554 CXXMemberInit = 0;
1555 return false;
1556
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001557 ParmVarDecl *Param = Constructor->getParamDecl(0);
1558 QualType ParamType = Param->getType().getNonReferenceType();
1559
1560 Expr *MemberExprBase =
1561 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1562 SourceLocation(), ParamType, 0);
1563
1564
1565 Expr *CopyCtorArg =
1566 MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1567 0, SourceRange(), Field,
1568 DeclAccessPair::make(Field, Field->getAccess()),
1569 SourceLocation(), 0,
1570 Field->getType().getNonReferenceType());
1571
1572 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1573 InitializationKind InitKind =
1574 InitializationKind::CreateDirect(Constructor->getLocation(),
1575 SourceLocation(), SourceLocation());
1576
1577 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1578 &CopyCtorArg, 1);
1579
1580 Sema::OwningExprResult MemberInit =
1581 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1582 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1583 if (MemberInit.isInvalid())
1584 return true;
1585
Anders Carlssone5ef7402010-04-23 03:10:23 +00001586 CXXMemberInit = 0;
1587 return false;
1588 }
1589
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001590 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1591
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001592 QualType FieldBaseElementType =
1593 SemaRef.Context.getBaseElementType(Field->getType());
1594
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001595 if (FieldBaseElementType->isRecordType()) {
1596 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001597 InitializationKind InitKind =
1598 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001599
1600 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1601 Sema::OwningExprResult MemberInit =
1602 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1603 Sema::MultiExprArg(SemaRef, 0, 0));
1604 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1605 if (MemberInit.isInvalid())
1606 return true;
1607
1608 CXXMemberInit =
1609 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1610 Field, SourceLocation(),
1611 SourceLocation(),
1612 MemberInit.takeAs<Expr>(),
1613 SourceLocation());
1614 return false;
1615 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001616
1617 if (FieldBaseElementType->isReferenceType()) {
1618 SemaRef.Diag(Constructor->getLocation(),
1619 diag::err_uninitialized_member_in_ctor)
1620 << (int)Constructor->isImplicit()
1621 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1622 << 0 << Field->getDeclName();
1623 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1624 return true;
1625 }
1626
1627 if (FieldBaseElementType.isConstQualified()) {
1628 SemaRef.Diag(Constructor->getLocation(),
1629 diag::err_uninitialized_member_in_ctor)
1630 << (int)Constructor->isImplicit()
1631 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1632 << 1 << Field->getDeclName();
1633 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1634 return true;
1635 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001636
1637 // Nothing to initialize.
1638 CXXMemberInit = 0;
1639 return false;
1640}
1641
Eli Friedman80c30da2009-11-09 19:20:36 +00001642bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001643Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001644 CXXBaseOrMemberInitializer **Initializers,
1645 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001646 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001647 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001648 // Just store the initializers as written, they will be checked during
1649 // instantiation.
1650 if (NumInitializers > 0) {
1651 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1652 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1653 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1654 memcpy(baseOrMemberInitializers, Initializers,
1655 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1656 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1657 }
1658
1659 return false;
1660 }
1661
Anders Carlssone5ef7402010-04-23 03:10:23 +00001662 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1663
1664 // FIXME: Handle implicit move constructors.
1665 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1666 ImplicitInitKind = IIK_Copy;
1667
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001668 // We need to build the initializer AST according to order of construction
1669 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001670 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001671 if (!ClassDecl)
1672 return true;
1673
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001674 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1675 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman80c30da2009-11-09 19:20:36 +00001676 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001678 for (unsigned i = 0; i < NumInitializers; i++) {
1679 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001680
1681 if (Member->isBaseInitializer())
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001682 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001683 else
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001684 AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001685 }
1686
Anders Carlsson711f34a2010-04-21 19:52:01 +00001687 // Keep track of the direct virtual bases.
1688 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1689 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1690 E = ClassDecl->bases_end(); I != E; ++I) {
1691 if (I->isVirtual())
1692 DirectVBases.insert(I);
1693 }
1694
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001695 // Push virtual bases before others.
1696 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1697 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1698
1699 if (CXXBaseOrMemberInitializer *Value
1700 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1701 AllToInit.push_back(Value);
1702 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001703 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001704 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001705 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1706 VBase, IsInheritedVirtualBase,
1707 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001708 HadError = true;
1709 continue;
1710 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001711
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001712 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001713 }
1714 }
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001716 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1717 E = ClassDecl->bases_end(); Base != E; ++Base) {
1718 // Virtuals are in the virtual base list and already constructed.
1719 if (Base->isVirtual())
1720 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001722 if (CXXBaseOrMemberInitializer *Value
1723 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1724 AllToInit.push_back(Value);
1725 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001726 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001727 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1728 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001729 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001730 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001731 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001732 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001733
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001734 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001735 }
1736 }
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001738 // non-static data members.
1739 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1740 E = ClassDecl->field_end(); Field != E; ++Field) {
1741 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001742 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001743 Field->getType()->getAs<RecordType>()) {
1744 CXXRecordDecl *FieldClassDecl
Douglas Gregorafe7ec22009-11-13 18:34:26 +00001745 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001746 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001747 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1748 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1749 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1750 // set to the anonymous union data member used in the initializer
1751 // list.
1752 Value->setMember(*Field);
1753 Value->setAnonUnionMember(*FA);
1754 AllToInit.push_back(Value);
1755 break;
1756 }
1757 }
1758 }
1759 continue;
1760 }
1761 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1762 AllToInit.push_back(Value);
1763 continue;
1764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Anders Carlssondefefd22010-04-23 02:00:02 +00001766 if (AnyErrors)
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001767 continue;
Douglas Gregor1fe6b912009-11-04 17:16:11 +00001768
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001769 CXXBaseOrMemberInitializer *Member;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001770 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1771 *Field, Member)) {
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001772 HadError = true;
1773 continue;
1774 }
1775
1776 // If the member doesn't need to be initialized, it will be null.
1777 if (Member)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001778 AllToInit.push_back(Member);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001779 }
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001781 NumInitializers = AllToInit.size();
1782 if (NumInitializers > 0) {
1783 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1784 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1785 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallef027fe2010-03-16 21:39:52 +00001786 memcpy(baseOrMemberInitializers, AllToInit.data(),
1787 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001788 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001789
John McCallef027fe2010-03-16 21:39:52 +00001790 // Constructors implicitly reference the base and member
1791 // destructors.
1792 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1793 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001794 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001795
1796 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001797}
1798
Eli Friedman6347f422009-07-21 19:28:10 +00001799static void *GetKeyForTopLevelField(FieldDecl *Field) {
1800 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001801 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001802 if (RT->getDecl()->isAnonymousStructOrUnion())
1803 return static_cast<void *>(RT->getDecl());
1804 }
1805 return static_cast<void *>(Field);
1806}
1807
Anders Carlssonea356fb2010-04-02 05:42:15 +00001808static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1809 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001810}
1811
Anders Carlssonea356fb2010-04-02 05:42:15 +00001812static void *GetKeyForMember(ASTContext &Context,
1813 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001814 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001815 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001816 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001817
Eli Friedman6347f422009-07-21 19:28:10 +00001818 // For fields injected into the class via declaration of an anonymous union,
1819 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001820 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001822 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1823 // data member of the class. Data member used in the initializer list is
1824 // in AnonUnionMember field.
1825 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1826 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001827
John McCall3c3ccdb2010-04-10 09:28:51 +00001828 // If the field is a member of an anonymous struct or union, our key
1829 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001830 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001831 if (RD->isAnonymousStructOrUnion()) {
1832 while (true) {
1833 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1834 if (Parent->isAnonymousStructOrUnion())
1835 RD = Parent;
1836 else
1837 break;
1838 }
1839
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001840 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00001841 }
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001843 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00001844}
1845
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001846static void
1847DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00001848 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00001849 CXXBaseOrMemberInitializer **Inits,
1850 unsigned NumInits) {
1851 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001852 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
John McCalld6ca8da2010-04-10 07:37:23 +00001854 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1855 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001856 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001857
John McCalld6ca8da2010-04-10 07:37:23 +00001858 // Build the list of bases and members in the order that they'll
1859 // actually be initialized. The explicit initializers should be in
1860 // this same order but may be missing things.
1861 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Anders Carlsson071d6102010-04-02 03:38:04 +00001863 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1864
John McCalld6ca8da2010-04-10 07:37:23 +00001865 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001866 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001867 ClassDecl->vbases_begin(),
1868 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00001869 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001870
John McCalld6ca8da2010-04-10 07:37:23 +00001871 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00001872 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001873 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001874 if (Base->isVirtual())
1875 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00001876 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
John McCalld6ca8da2010-04-10 07:37:23 +00001879 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1881 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00001882 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001883
John McCalld6ca8da2010-04-10 07:37:23 +00001884 unsigned NumIdealInits = IdealInitKeys.size();
1885 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00001886
John McCalld6ca8da2010-04-10 07:37:23 +00001887 CXXBaseOrMemberInitializer *PrevInit = 0;
1888 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1889 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1890 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1891
1892 // Scan forward to try to find this initializer in the idealized
1893 // initializers list.
1894 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1895 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001896 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001897
1898 // If we didn't find this initializer, it must be because we
1899 // scanned past it on a previous iteration. That can only
1900 // happen if we're out of order; emit a warning.
1901 if (IdealIndex == NumIdealInits) {
1902 assert(PrevInit && "initializer not found in initializer list");
1903
1904 Sema::SemaDiagnosticBuilder D =
1905 SemaRef.Diag(PrevInit->getSourceLocation(),
1906 diag::warn_initializer_out_of_order);
1907
1908 if (PrevInit->isMemberInitializer())
1909 D << 0 << PrevInit->getMember()->getDeclName();
1910 else
1911 D << 1 << PrevInit->getBaseClassInfo()->getType();
1912
1913 if (Init->isMemberInitializer())
1914 D << 0 << Init->getMember()->getDeclName();
1915 else
1916 D << 1 << Init->getBaseClassInfo()->getType();
1917
1918 // Move back to the initializer's location in the ideal list.
1919 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1920 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001921 break;
John McCalld6ca8da2010-04-10 07:37:23 +00001922
1923 assert(IdealIndex != NumIdealInits &&
1924 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001925 }
John McCalld6ca8da2010-04-10 07:37:23 +00001926
1927 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001928 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001929}
1930
John McCall3c3ccdb2010-04-10 09:28:51 +00001931namespace {
1932bool CheckRedundantInit(Sema &S,
1933 CXXBaseOrMemberInitializer *Init,
1934 CXXBaseOrMemberInitializer *&PrevInit) {
1935 if (!PrevInit) {
1936 PrevInit = Init;
1937 return false;
1938 }
1939
1940 if (FieldDecl *Field = Init->getMember())
1941 S.Diag(Init->getSourceLocation(),
1942 diag::err_multiple_mem_initialization)
1943 << Field->getDeclName()
1944 << Init->getSourceRange();
1945 else {
1946 Type *BaseClass = Init->getBaseClass();
1947 assert(BaseClass && "neither field nor base");
1948 S.Diag(Init->getSourceLocation(),
1949 diag::err_multiple_base_initialization)
1950 << QualType(BaseClass, 0)
1951 << Init->getSourceRange();
1952 }
1953 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1954 << 0 << PrevInit->getSourceRange();
1955
1956 return true;
1957}
1958
1959typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1960typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1961
1962bool CheckRedundantUnionInit(Sema &S,
1963 CXXBaseOrMemberInitializer *Init,
1964 RedundantUnionMap &Unions) {
1965 FieldDecl *Field = Init->getMember();
1966 RecordDecl *Parent = Field->getParent();
1967 if (!Parent->isAnonymousStructOrUnion())
1968 return false;
1969
1970 NamedDecl *Child = Field;
1971 do {
1972 if (Parent->isUnion()) {
1973 UnionEntry &En = Unions[Parent];
1974 if (En.first && En.first != Child) {
1975 S.Diag(Init->getSourceLocation(),
1976 diag::err_multiple_mem_union_initialization)
1977 << Field->getDeclName()
1978 << Init->getSourceRange();
1979 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1980 << 0 << En.second->getSourceRange();
1981 return true;
1982 } else if (!En.first) {
1983 En.first = Child;
1984 En.second = Init;
1985 }
1986 }
1987
1988 Child = Parent;
1989 Parent = cast<RecordDecl>(Parent->getDeclContext());
1990 } while (Parent->isAnonymousStructOrUnion());
1991
1992 return false;
1993}
1994}
1995
Anders Carlsson58cfbde2010-04-02 03:37:03 +00001996/// ActOnMemInitializers - Handle the member initializers for a constructor.
1997void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1998 SourceLocation ColonLoc,
1999 MemInitTy **meminits, unsigned NumMemInits,
2000 bool AnyErrors) {
2001 if (!ConstructorDecl)
2002 return;
2003
2004 AdjustDeclIfTemplate(ConstructorDecl);
2005
2006 CXXConstructorDecl *Constructor
2007 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2008
2009 if (!Constructor) {
2010 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2011 return;
2012 }
2013
2014 CXXBaseOrMemberInitializer **MemInits =
2015 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002016
2017 // Mapping for the duplicate initializers check.
2018 // For member initializers, this is keyed with a FieldDecl*.
2019 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002020 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002021
2022 // Mapping for the inconsistent anonymous-union initializers check.
2023 RedundantUnionMap MemberUnions;
2024
Anders Carlssonea356fb2010-04-02 05:42:15 +00002025 bool HadError = false;
2026 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002027 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002028
John McCall3c3ccdb2010-04-10 09:28:51 +00002029 if (Init->isMemberInitializer()) {
2030 FieldDecl *Field = Init->getMember();
2031 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2032 CheckRedundantUnionInit(*this, Init, MemberUnions))
2033 HadError = true;
2034 } else {
2035 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2036 if (CheckRedundantInit(*this, Init, Members[Key]))
2037 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002038 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002039 }
2040
Anders Carlssonea356fb2010-04-02 05:42:15 +00002041 if (HadError)
2042 return;
2043
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002044 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002045
2046 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002047}
2048
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002049void
John McCallef027fe2010-03-16 21:39:52 +00002050Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2051 CXXRecordDecl *ClassDecl) {
2052 // Ignore dependent contexts.
2053 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002054 return;
John McCall58e6f342010-03-16 05:22:47 +00002055
2056 // FIXME: all the access-control diagnostics are positioned on the
2057 // field/base declaration. That's probably good; that said, the
2058 // user might reasonably want to know why the destructor is being
2059 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002060
Anders Carlsson9f853df2009-11-17 04:44:12 +00002061 // Non-static data members.
2062 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2063 E = ClassDecl->field_end(); I != E; ++I) {
2064 FieldDecl *Field = *I;
2065
2066 QualType FieldType = Context.getBaseElementType(Field->getType());
2067
2068 const RecordType* RT = FieldType->getAs<RecordType>();
2069 if (!RT)
2070 continue;
2071
2072 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2073 if (FieldClassDecl->hasTrivialDestructor())
2074 continue;
2075
John McCall58e6f342010-03-16 05:22:47 +00002076 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2077 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002078 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002079 << Field->getDeclName()
2080 << FieldType);
2081
John McCallef027fe2010-03-16 21:39:52 +00002082 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002083 }
2084
John McCall58e6f342010-03-16 05:22:47 +00002085 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2086
Anders Carlsson9f853df2009-11-17 04:44:12 +00002087 // Bases.
2088 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2089 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002090 // Bases are always records in a well-formed non-dependent class.
2091 const RecordType *RT = Base->getType()->getAs<RecordType>();
2092
2093 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002094 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002095 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002096
2097 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002098 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002099 if (BaseClassDecl->hasTrivialDestructor())
2100 continue;
John McCall58e6f342010-03-16 05:22:47 +00002101
2102 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2103
2104 // FIXME: caret should be on the start of the class name
2105 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002106 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002107 << Base->getType()
2108 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002109
John McCallef027fe2010-03-16 21:39:52 +00002110 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002111 }
2112
2113 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002114 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2115 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002116
2117 // Bases are always records in a well-formed non-dependent class.
2118 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2119
2120 // Ignore direct virtual bases.
2121 if (DirectVirtualBases.count(RT))
2122 continue;
2123
Anders Carlsson9f853df2009-11-17 04:44:12 +00002124 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002125 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002126 if (BaseClassDecl->hasTrivialDestructor())
2127 continue;
John McCall58e6f342010-03-16 05:22:47 +00002128
2129 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2130 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002131 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002132 << VBase->getType());
2133
John McCallef027fe2010-03-16 21:39:52 +00002134 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002135 }
2136}
2137
Fariborz Jahanian393612e2009-07-21 22:36:06 +00002138void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002139 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002140 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Mike Stump1eb44332009-09-09 15:08:12 +00002142 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00002143 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002144 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002145}
2146
Mike Stump1eb44332009-09-09 15:08:12 +00002147bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002148 unsigned DiagID, AbstractDiagSelID SelID,
2149 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002150 if (SelID == -1)
2151 return RequireNonAbstractType(Loc, T,
2152 PDiag(DiagID), CurrentRD);
2153 else
2154 return RequireNonAbstractType(Loc, T,
2155 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002156}
2157
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002158bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2159 const PartialDiagnostic &PD,
2160 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002161 if (!getLangOptions().CPlusPlus)
2162 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Anders Carlsson11f21a02009-03-23 19:10:31 +00002164 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002165 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002166 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenek6217b802009-07-29 21:53:49 +00002168 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002169 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002170 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002171 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002173 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002174 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002175 }
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Ted Kremenek6217b802009-07-29 21:53:49 +00002177 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002178 if (!RT)
2179 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002180
John McCall86ff3082010-02-04 22:26:26 +00002181 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002182
Anders Carlssone65a3c82009-03-24 17:23:42 +00002183 if (CurrentRD && CurrentRD != RD)
2184 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
John McCall86ff3082010-02-04 22:26:26 +00002186 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor952b0172010-02-11 01:04:33 +00002187 if (!RD->getDefinition())
John McCall86ff3082010-02-04 22:26:26 +00002188 return false;
2189
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002190 if (!RD->isAbstract())
2191 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002193 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002195 // Check if we've already emitted the list of pure virtual functions for this
2196 // class.
2197 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2198 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002200 CXXFinalOverriderMap FinalOverriders;
2201 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002203 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2204 MEnd = FinalOverriders.end();
2205 M != MEnd;
2206 ++M) {
2207 for (OverridingMethods::iterator SO = M->second.begin(),
2208 SOEnd = M->second.end();
2209 SO != SOEnd; ++SO) {
2210 // C++ [class.abstract]p4:
2211 // A class is abstract if it contains or inherits at least one
2212 // pure virtual function for which the final overrider is pure
2213 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002215 //
2216 if (SO->second.size() != 1)
2217 continue;
2218
2219 if (!SO->second.front().Method->isPure())
2220 continue;
2221
2222 Diag(SO->second.front().Method->getLocation(),
2223 diag::note_pure_virtual_function)
2224 << SO->second.front().Method->getDeclName();
2225 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002226 }
2227
2228 if (!PureVirtualClassDiagSet)
2229 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2230 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002232 return true;
2233}
2234
Anders Carlsson8211eff2009-03-24 01:19:16 +00002235namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +00002236 class AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00002237 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2238 Sema &SemaRef;
2239 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Anders Carlssone65a3c82009-03-24 17:23:42 +00002241 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002242 bool Invalid = false;
2243
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002244 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2245 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00002246 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002247
Anders Carlsson8211eff2009-03-24 01:19:16 +00002248 return Invalid;
2249 }
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Anders Carlssone65a3c82009-03-24 17:23:42 +00002251 public:
2252 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2253 : SemaRef(SemaRef), AbstractClass(ac) {
2254 Visit(SemaRef.Context.getTranslationUnitDecl());
2255 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002256
Anders Carlssone65a3c82009-03-24 17:23:42 +00002257 bool VisitFunctionDecl(const FunctionDecl *FD) {
2258 if (FD->isThisDeclarationADefinition()) {
2259 // No need to do the check if we're in a definition, because it requires
2260 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00002261 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00002262 return VisitDeclContext(FD);
2263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Anders Carlssone65a3c82009-03-24 17:23:42 +00002265 // Check the return type.
John McCall183700f2009-09-21 23:43:11 +00002266 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00002267 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00002268 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2269 diag::err_abstract_type_in_decl,
2270 Sema::AbstractReturnType,
2271 AbstractClass);
2272
Mike Stump1eb44332009-09-09 15:08:12 +00002273 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00002274 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00002275 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00002276 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00002277 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002278 VD->getOriginalType(),
2279 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00002280 Sema::AbstractParamType,
2281 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00002282 }
2283
2284 return Invalid;
2285 }
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Anders Carlssone65a3c82009-03-24 17:23:42 +00002287 bool VisitDecl(const Decl* D) {
2288 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2289 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Anders Carlssone65a3c82009-03-24 17:23:42 +00002291 return false;
2292 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002293 };
2294}
2295
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002296/// \brief Perform semantic checks on a class definition that has been
2297/// completing, introducing implicitly-declared members, checking for
2298/// abstract types, etc.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002299void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002300 if (!Record || Record->isInvalidDecl())
2301 return;
2302
Eli Friedmanff2d8782009-12-16 20:00:27 +00002303 if (!Record->isDependentType())
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002304 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002305
Eli Friedmanff2d8782009-12-16 20:00:27 +00002306 if (Record->isInvalidDecl())
2307 return;
2308
John McCall233a6412010-01-28 07:38:46 +00002309 // Set access bits correctly on the directly-declared conversions.
2310 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2311 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2312 Convs->setAccess(I, (*I)->getAccess());
2313
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002314 // Determine whether we need to check for final overriders. We do
2315 // this either when there are virtual base classes (in which case we
2316 // may end up finding multiple final overriders for a given virtual
2317 // function) or any of the base classes is abstract (in which case
2318 // we might detect that this class is abstract).
2319 bool CheckFinalOverriders = false;
2320 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2321 !Record->isDependentType()) {
2322 if (Record->getNumVBases())
2323 CheckFinalOverriders = true;
2324 else if (!Record->isAbstract()) {
2325 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2326 BEnd = Record->bases_end();
2327 B != BEnd; ++B) {
2328 CXXRecordDecl *BaseDecl
2329 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2330 if (BaseDecl->isAbstract()) {
2331 CheckFinalOverriders = true;
2332 break;
2333 }
2334 }
2335 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002336 }
2337
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002338 if (CheckFinalOverriders) {
2339 CXXFinalOverriderMap FinalOverriders;
2340 Record->getFinalOverriders(FinalOverriders);
2341
2342 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2343 MEnd = FinalOverriders.end();
2344 M != MEnd; ++M) {
2345 for (OverridingMethods::iterator SO = M->second.begin(),
2346 SOEnd = M->second.end();
2347 SO != SOEnd; ++SO) {
2348 assert(SO->second.size() > 0 &&
2349 "All virtual functions have overridding virtual functions");
2350 if (SO->second.size() == 1) {
2351 // C++ [class.abstract]p4:
2352 // A class is abstract if it contains or inherits at least one
2353 // pure virtual function for which the final overrider is pure
2354 // virtual.
2355 if (SO->second.front().Method->isPure())
2356 Record->setAbstract(true);
2357 continue;
2358 }
2359
2360 // C++ [class.virtual]p2:
2361 // In a derived class, if a virtual member function of a base
2362 // class subobject has more than one final overrider the
2363 // program is ill-formed.
2364 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2365 << (NamedDecl *)M->first << Record;
2366 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2367 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2368 OMEnd = SO->second.end();
2369 OM != OMEnd; ++OM)
2370 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2371 << (NamedDecl *)M->first << OM->Method->getParent();
2372
2373 Record->setInvalidDecl();
2374 }
2375 }
2376 }
2377
2378 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002379 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor325e5932010-04-15 00:00:53 +00002380
2381 // If this is not an aggregate type and has no user-declared constructor,
2382 // complain about any non-static data members of reference or const scalar
2383 // type, since they will never get initializers.
2384 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2385 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2386 bool Complained = false;
2387 for (RecordDecl::field_iterator F = Record->field_begin(),
2388 FEnd = Record->field_end();
2389 F != FEnd; ++F) {
2390 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002391 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002392 if (!Complained) {
2393 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2394 << Record->getTagKind() << Record;
2395 Complained = true;
2396 }
2397
2398 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2399 << F->getType()->isReferenceType()
2400 << F->getDeclName();
2401 }
2402 }
2403 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002404}
2405
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002406void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002407 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002408 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002409 SourceLocation RBrac,
2410 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002411 if (!TagDecl)
2412 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Douglas Gregor42af25f2009-05-11 19:58:34 +00002414 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002415
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002416 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002417 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002418 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002419
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002420 CheckCompletedCXXClass(S,
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002421 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002422}
2423
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002424/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2425/// special functions, such as the default constructor, copy
2426/// constructor, or destructor, to the given C++ class (C++
2427/// [special]p1). This routine can only be executed just before the
2428/// definition of the class is complete.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002429///
2430/// The scope, if provided, is the class scope.
2431void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2432 CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002433 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00002434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002435
Sebastian Redl465226e2009-05-27 22:11:52 +00002436 // FIXME: Implicit declarations have exception specifications, which are
2437 // the union of the specifications of the implicitly called functions.
2438
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002439 if (!ClassDecl->hasUserDeclaredConstructor()) {
2440 // C++ [class.ctor]p5:
2441 // A default constructor for a class X is a constructor of class X
2442 // that can be called without an argument. If there is no
2443 // user-declared constructor for class X, a default constructor is
2444 // implicitly declared. An implicitly-declared default constructor
2445 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002446 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002447 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002448 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002449 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002450 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002451 Context.getFunctionType(Context.VoidTy,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002452 0, 0, false, 0,
2453 /*FIXME*/false, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002454 0, 0,
2455 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002456 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002457 /*isExplicit=*/false,
2458 /*isInline=*/true,
2459 /*isImplicitlyDeclared=*/true);
2460 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002461 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002462 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002463 if (S)
2464 PushOnScopeChains(DefaultCon, S, true);
2465 else
2466 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002467 }
2468
2469 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2470 // C++ [class.copy]p4:
2471 // If the class definition does not explicitly declare a copy
2472 // constructor, one is declared implicitly.
2473
2474 // C++ [class.copy]p5:
2475 // The implicitly-declared copy constructor for a class X will
2476 // have the form
2477 //
2478 // X::X(const X&)
2479 //
2480 // if
2481 bool HasConstCopyConstructor = true;
2482
2483 // -- each direct or virtual base class B of X has a copy
2484 // constructor whose first parameter is of type const B& or
2485 // const volatile B&, and
2486 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2487 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2488 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002489 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002490 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002491 = BaseClassDecl->hasConstCopyConstructor(Context);
2492 }
2493
2494 // -- for all the nonstatic data members of X that are of a
2495 // class type M (or array thereof), each such class type
2496 // has a copy constructor whose first parameter is of type
2497 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002498 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2499 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002500 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002501 QualType FieldType = (*Field)->getType();
2502 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2503 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002504 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002505 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002506 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002507 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002508 = FieldClassDecl->hasConstCopyConstructor(Context);
2509 }
2510 }
2511
Sebastian Redl64b45f72009-01-05 20:52:13 +00002512 // Otherwise, the implicitly declared copy constructor will have
2513 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002514 //
2515 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00002516 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002517 if (HasConstCopyConstructor)
2518 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002519 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002520
Sebastian Redl64b45f72009-01-05 20:52:13 +00002521 // An implicitly-declared copy constructor is an inline public
2522 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00002523 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002524 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002525 CXXConstructorDecl *CopyConstructor
2526 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002527 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002528 Context.getFunctionType(Context.VoidTy,
2529 &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002530 false, 0,
2531 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002532 false, 0, 0,
2533 FunctionType::ExtInfo()),
John McCalla93c9342009-12-07 02:54:59 +00002534 /*TInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002535 /*isExplicit=*/false,
2536 /*isInline=*/true,
2537 /*isImplicitlyDeclared=*/true);
2538 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002539 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002540 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002541
2542 // Add the parameter to the constructor.
2543 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2544 ClassDecl->getLocation(),
2545 /*IdentifierInfo=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002546 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002547 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002548 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002549 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002550 if (S)
2551 PushOnScopeChains(CopyConstructor, S, true);
2552 else
2553 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002554 }
2555
Sebastian Redl64b45f72009-01-05 20:52:13 +00002556 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2557 // Note: The following rules are largely analoguous to the copy
2558 // constructor rules. Note that virtual bases are not taken into account
2559 // for determining the argument type of the operator. Note also that
2560 // operators taking an object instead of a reference are allowed.
2561 //
2562 // C++ [class.copy]p10:
2563 // If the class definition does not explicitly declare a copy
2564 // assignment operator, one is declared implicitly.
2565 // The implicitly-defined copy assignment operator for a class X
2566 // will have the form
2567 //
2568 // X& X::operator=(const X&)
2569 //
2570 // if
2571 bool HasConstCopyAssignment = true;
2572
2573 // -- each direct base class B of X has a copy assignment operator
2574 // whose parameter is of type const B&, const volatile B& or B,
2575 // and
2576 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2577 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl9994a342009-10-25 17:03:50 +00002578 assert(!Base->getType()->isDependentType() &&
2579 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002580 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002581 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002582 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002583 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002584 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002585 }
2586
2587 // -- for all the nonstatic data members of X that are of a class
2588 // type M (or array thereof), each such class type has a copy
2589 // assignment operator whose parameter is of type const M&,
2590 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2592 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002593 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002594 QualType FieldType = (*Field)->getType();
2595 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2596 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002597 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002598 const CXXRecordDecl *FieldClassDecl
2599 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002600 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002601 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00002602 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002603 }
2604 }
2605
2606 // Otherwise, the implicitly declared copy assignment operator will
2607 // have the form
2608 //
2609 // X& X::operator=(X&)
2610 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002611 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002612 if (HasConstCopyAssignment)
2613 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002614 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002615
2616 // An implicitly-declared copy assignment operator is an inline public
2617 // member of its class.
2618 DeclarationName Name =
2619 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2620 CXXMethodDecl *CopyAssignment =
2621 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2622 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregorce056bc2010-02-21 22:15:06 +00002623 false, 0,
2624 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002625 false, 0, 0,
2626 FunctionType::ExtInfo()),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002627 /*TInfo=*/0, /*isStatic=*/false,
2628 /*StorageClassAsWritten=*/FunctionDecl::None,
2629 /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002630 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002631 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002632 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00002633 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002634
2635 // Add the parameter to the operator.
2636 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2637 ClassDecl->getLocation(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00002638 /*Id=*/0,
John McCalla93c9342009-12-07 02:54:59 +00002639 ArgType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002640 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002641 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00002642 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002643
2644 // Don't call addedAssignmentOperator. There is no way to distinguish an
2645 // implicit from an explicit assignment operator.
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002646 if (S)
2647 PushOnScopeChains(CopyAssignment, S, true);
2648 else
2649 ClassDecl->addDecl(CopyAssignment);
Eli Friedmanca6affd2009-12-02 06:59:20 +00002650 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002651 }
2652
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002653 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002654 // C++ [class.dtor]p2:
2655 // If a class has no user-declared destructor, a destructor is
2656 // declared implicitly. An implicitly-declared destructor is an
2657 // inline public member of its class.
John McCall21ef0fa2010-03-11 09:03:00 +00002658 QualType Ty = Context.getFunctionType(Context.VoidTy,
2659 0, 0, false, 0,
2660 /*FIXME:*/false,
Rafael Espindola264ba482010-03-30 20:24:48 +00002661 false, 0, 0, FunctionType::ExtInfo());
John McCall21ef0fa2010-03-11 09:03:00 +00002662
Mike Stump1eb44332009-09-09 15:08:12 +00002663 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002664 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00002665 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00002666 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall21ef0fa2010-03-11 09:03:00 +00002667 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor42a552f2008-11-05 20:51:48 +00002668 /*isInline=*/true,
2669 /*isImplicitlyDeclared=*/true);
2670 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002671 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00002672 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor6275e0c2010-04-12 17:09:20 +00002673 if (S)
2674 PushOnScopeChains(Destructor, S, true);
2675 else
2676 ClassDecl->addDecl(Destructor);
John McCall21ef0fa2010-03-11 09:03:00 +00002677
2678 // This could be uniqued if it ever proves significant.
2679 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlssond5a942b2009-11-26 21:25:09 +00002680
2681 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002682 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002683}
2684
Douglas Gregor6569d682009-05-27 23:11:45 +00002685void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002686 Decl *D = TemplateD.getAs<Decl>();
2687 if (!D)
2688 return;
2689
2690 TemplateParameterList *Params = 0;
2691 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2692 Params = Template->getTemplateParameters();
2693 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2694 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2695 Params = PartialSpec->getTemplateParameters();
2696 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002697 return;
2698
Douglas Gregor6569d682009-05-27 23:11:45 +00002699 for (TemplateParameterList::iterator Param = Params->begin(),
2700 ParamEnd = Params->end();
2701 Param != ParamEnd; ++Param) {
2702 NamedDecl *Named = cast<NamedDecl>(*Param);
2703 if (Named->getDeclName()) {
2704 S->AddDecl(DeclPtrTy::make(Named));
2705 IdResolver.AddDecl(Named);
2706 }
2707 }
2708}
2709
John McCall7a1dc562009-12-19 10:49:29 +00002710void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2711 if (!RecordD) return;
2712 AdjustDeclIfTemplate(RecordD);
2713 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2714 PushDeclContext(S, Record);
2715}
2716
2717void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2718 if (!RecordD) return;
2719 PopDeclContext();
2720}
2721
Douglas Gregor72b505b2008-12-16 21:30:33 +00002722/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2723/// parsing a top-level (non-nested) C++ class, and we are now
2724/// parsing those parts of the given Method declaration that could
2725/// not be parsed earlier (C++ [class.mem]p2), such as default
2726/// arguments. This action should enter the scope of the given
2727/// Method declaration as if we had just parsed the qualified method
2728/// name. However, it should not bring the parameters into scope;
2729/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002730void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002731}
2732
2733/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2734/// C++ method declaration. We're (re-)introducing the given
2735/// function parameter into scope for use in parsing later parts of
2736/// the method declaration. For example, we could see an
2737/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002738void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002739 if (!ParamD)
2740 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Chris Lattnerb28317a2009-03-28 19:18:32 +00002742 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00002743
2744 // If this parameter has an unparsed default argument, clear it out
2745 // to make way for the parsed default argument.
2746 if (Param->hasUnparsedDefaultArg())
2747 Param->setDefaultArg(0);
2748
Chris Lattnerb28317a2009-03-28 19:18:32 +00002749 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00002750 if (Param->getDeclName())
2751 IdResolver.AddDecl(Param);
2752}
2753
2754/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2755/// processing the delayed method declaration for Method. The method
2756/// declaration is now considered finished. There may be a separate
2757/// ActOnStartOfFunctionDef action later (not necessarily
2758/// immediately!) for this method, if it was also defined inside the
2759/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002760void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002761 if (!MethodD)
2762 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002764 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002765
Chris Lattnerb28317a2009-03-28 19:18:32 +00002766 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00002767
2768 // Now that we have our default arguments, check the constructor
2769 // again. It could produce additional diagnostics or affect whether
2770 // the class has implicitly-declared destructors, among other
2771 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2773 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002774
2775 // Check the default arguments, which we may have added.
2776 if (!Method->isInvalidDecl())
2777 CheckCXXDefaultArguments(Method);
2778}
2779
Douglas Gregor42a552f2008-11-05 20:51:48 +00002780/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002781/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002782/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002783/// emit diagnostics and set the invalid bit to true. In any case, the type
2784/// will be updated to reflect a well-formed type for the constructor and
2785/// returned.
2786QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2787 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002788 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002789
2790 // C++ [class.ctor]p3:
2791 // A constructor shall not be virtual (10.3) or static (9.4). A
2792 // constructor can be invoked for a const, volatile or const
2793 // volatile object. A constructor shall not be declared const,
2794 // volatile, or const volatile (9.3.2).
2795 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002796 if (!D.isInvalidType())
2797 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2798 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2799 << SourceRange(D.getIdentifierLoc());
2800 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002801 }
2802 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002803 if (!D.isInvalidType())
2804 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2805 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2806 << SourceRange(D.getIdentifierLoc());
2807 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002808 SC = FunctionDecl::None;
2809 }
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Chris Lattner65401802009-04-25 08:28:21 +00002811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2812 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002813 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002814 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2815 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002816 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002817 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2818 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002819 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2821 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002822 }
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Douglas Gregor42a552f2008-11-05 20:51:48 +00002824 // Rebuild the function type "R" without any type qualifiers (in
2825 // case any of the errors above fired) and with "void" as the
2826 // return type, since constructors don't have return types. We
2827 // *always* have to do this, because GetTypeForDeclarator will
2828 // put in a result type of "int" when none was specified.
John McCall183700f2009-09-21 23:43:11 +00002829 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002830 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2831 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002832 Proto->isVariadic(), 0,
2833 Proto->hasExceptionSpec(),
2834 Proto->hasAnyExceptionSpec(),
2835 Proto->getNumExceptions(),
2836 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002837 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002838}
2839
Douglas Gregor72b505b2008-12-16 21:30:33 +00002840/// CheckConstructor - Checks a fully-formed constructor for
2841/// well-formedness, issuing any diagnostics required. Returns true if
2842/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002843void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002844 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002845 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2846 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002847 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002848
2849 // C++ [class.copy]p3:
2850 // A declaration of a constructor for a class X is ill-formed if
2851 // its first parameter is of type (optionally cv-qualified) X and
2852 // either there are no other parameters or else all other
2853 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002854 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002855 ((Constructor->getNumParams() == 1) ||
2856 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002857 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2858 Constructor->getTemplateSpecializationKind()
2859 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002860 QualType ParamType = Constructor->getParamDecl(0)->getType();
2861 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2862 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002863 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2864 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor849b2432010-03-31 17:46:05 +00002865 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregor66724ea2009-11-14 01:20:54 +00002866
2867 // FIXME: Rather that making the constructor invalid, we should endeavor
2868 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002869 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002870 }
2871 }
Mike Stump1eb44332009-09-09 15:08:12 +00002872
John McCall3d043362010-04-13 07:45:41 +00002873 // Notify the class that we've added a constructor. In principle we
2874 // don't need to do this for out-of-line declarations; in practice
2875 // we only instantiate the most recent declaration of a method, so
2876 // we have to call this for everything but friends.
2877 if (!Constructor->getFriendObjectKind())
2878 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002879}
2880
Anders Carlsson37909802009-11-30 21:24:50 +00002881/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2882/// issuing any diagnostics required. Returns true on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002883bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002884 CXXRecordDecl *RD = Destructor->getParent();
2885
2886 if (Destructor->isVirtual()) {
2887 SourceLocation Loc;
2888
2889 if (!Destructor->isImplicit())
2890 Loc = Destructor->getLocation();
2891 else
2892 Loc = RD->getLocation();
2893
2894 // If we have a virtual destructor, look up the deallocation function
2895 FunctionDecl *OperatorDelete = 0;
2896 DeclarationName Name =
2897 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002898 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00002899 return true;
2900
2901 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00002902 }
Anders Carlsson37909802009-11-30 21:24:50 +00002903
2904 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00002905}
2906
Mike Stump1eb44332009-09-09 15:08:12 +00002907static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002908FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2909 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2910 FTI.ArgInfo[0].Param &&
2911 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2912}
2913
Douglas Gregor42a552f2008-11-05 20:51:48 +00002914/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2915/// the well-formednes of the destructor declarator @p D with type @p
2916/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002917/// emit diagnostics and set the declarator to invalid. Even if this happens,
2918/// will be updated to reflect a well-formed type for the destructor and
2919/// returned.
2920QualType Sema::CheckDestructorDeclarator(Declarator &D,
2921 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002922 // C++ [class.dtor]p1:
2923 // [...] A typedef-name that names a class is a class-name
2924 // (7.1.3); however, a typedef-name that names a class shall not
2925 // be used as the identifier in the declarator for a destructor
2926 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002927 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner65401802009-04-25 08:28:21 +00002928 if (isa<TypedefType>(DeclaratorType)) {
2929 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002930 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002931 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002932 }
2933
2934 // C++ [class.dtor]p2:
2935 // A destructor is used to destroy objects of its class type. A
2936 // destructor takes no parameters, and no return type can be
2937 // specified for it (not even void). The address of a destructor
2938 // shall not be taken. A destructor shall not be static. A
2939 // destructor can be invoked for a const, volatile or const
2940 // volatile object. A destructor shall not be declared const,
2941 // volatile or const volatile (9.3.2).
2942 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002943 if (!D.isInvalidType())
2944 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2945 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2946 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002947 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002948 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002949 }
Chris Lattner65401802009-04-25 08:28:21 +00002950 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002951 // Destructors don't have return types, but the parser will
2952 // happily parse something like:
2953 //
2954 // class X {
2955 // float ~X();
2956 // };
2957 //
2958 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002959 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2960 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2961 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002962 }
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Chris Lattner65401802009-04-25 08:28:21 +00002964 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2965 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00002966 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002967 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2968 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002969 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002970 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2971 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002972 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002973 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2974 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002975 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002976 }
2977
2978 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002979 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002980 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2981
2982 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002983 FTI.freeArgs();
2984 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002985 }
2986
Mike Stump1eb44332009-09-09 15:08:12 +00002987 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002988 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002989 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002990 D.setInvalidType();
2991 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002992
2993 // Rebuild the function type "R" without any type qualifiers or
2994 // parameters (in case any of the errors above fired) and with
2995 // "void" as the return type, since destructors don't have return
2996 // types. We *always* have to do this, because GetTypeForDeclarator
2997 // will put in a result type of "int" when none was specified.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002998 // FIXME: Exceptions!
2999 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003000 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003001}
3002
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003003/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3004/// well-formednes of the conversion function declarator @p D with
3005/// type @p R. If there are any errors in the declarator, this routine
3006/// will emit diagnostics and return true. Otherwise, it will return
3007/// false. Either way, the type @p R will be updated to reflect a
3008/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003009void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003010 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003011 // C++ [class.conv.fct]p1:
3012 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003013 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003014 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003015 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003016 if (!D.isInvalidType())
3017 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3018 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3019 << SourceRange(D.getIdentifierLoc());
3020 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003021 SC = FunctionDecl::None;
3022 }
John McCalla3f81372010-04-13 00:04:31 +00003023
3024 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3025
Chris Lattner6e475012009-04-25 08:35:12 +00003026 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003027 // Conversion functions don't have return types, but the parser will
3028 // happily parse something like:
3029 //
3030 // class X {
3031 // float operator bool();
3032 // };
3033 //
3034 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003035 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3036 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3037 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003038 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003039 }
3040
John McCalla3f81372010-04-13 00:04:31 +00003041 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3042
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003043 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003044 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003045 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3046
3047 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003048 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003049 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003050 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003051 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003052 D.setInvalidType();
3053 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003054
John McCalla3f81372010-04-13 00:04:31 +00003055 // Diagnose "&operator bool()" and other such nonsense. This
3056 // is actually a gcc extension which we don't support.
3057 if (Proto->getResultType() != ConvType) {
3058 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3059 << Proto->getResultType();
3060 D.setInvalidType();
3061 ConvType = Proto->getResultType();
3062 }
3063
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003064 // C++ [class.conv.fct]p4:
3065 // The conversion-type-id shall not represent a function type nor
3066 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003067 if (ConvType->isArrayType()) {
3068 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3069 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003070 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003071 } else if (ConvType->isFunctionType()) {
3072 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3073 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003074 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003075 }
3076
3077 // Rebuild the function type "R" without any parameters (in case any
3078 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003079 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003080 if (D.isInvalidType()) {
3081 R = Context.getFunctionType(ConvType, 0, 0, false,
3082 Proto->getTypeQuals(),
3083 Proto->hasExceptionSpec(),
3084 Proto->hasAnyExceptionSpec(),
3085 Proto->getNumExceptions(),
3086 Proto->exception_begin(),
3087 Proto->getExtInfo());
3088 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003089
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003090 // C++0x explicit conversion operators.
3091 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003092 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003093 diag::warn_explicit_conversion_functions)
3094 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003095}
3096
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003097/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3098/// the declaration of the given C++ conversion function. This routine
3099/// is responsible for recording the conversion function in the C++
3100/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003101Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003102 assert(Conversion && "Expected to receive a conversion function declaration");
3103
Douglas Gregor9d350972008-12-12 08:25:50 +00003104 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003105
3106 // Make sure we aren't redeclaring the conversion function.
3107 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003108
3109 // C++ [class.conv.fct]p1:
3110 // [...] A conversion function is never used to convert a
3111 // (possibly cv-qualified) object to the (possibly cv-qualified)
3112 // same object type (or a reference to it), to a (possibly
3113 // cv-qualified) base class of that type (or a reference to it),
3114 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003115 // FIXME: Suppress this warning if the conversion function ends up being a
3116 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003117 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003118 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003119 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003120 ConvType = ConvTypeRef->getPointeeType();
3121 if (ConvType->isRecordType()) {
3122 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3123 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003124 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003125 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003126 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003127 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003128 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003129 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003130 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003131 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003132 }
3133
Douglas Gregor48026d22010-01-11 18:40:55 +00003134 if (Conversion->getPrimaryTemplate()) {
3135 // ignore specializations
3136 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003137 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003138 = Conversion->getDescribedFunctionTemplate()) {
3139 if (ClassDecl->replaceConversion(
3140 ConversionTemplate->getPreviousDeclaration(),
3141 ConversionTemplate))
3142 return DeclPtrTy::make(ConversionTemplate);
3143 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3144 Conversion))
John McCallba135432009-11-21 08:51:07 +00003145 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00003146 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003147 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003148 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003149 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003150 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003151 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003152
Chris Lattnerb28317a2009-03-28 19:18:32 +00003153 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003154}
3155
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003156//===----------------------------------------------------------------------===//
3157// Namespace Handling
3158//===----------------------------------------------------------------------===//
3159
3160/// ActOnStartNamespaceDef - This is called at the start of a namespace
3161/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003162Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3163 SourceLocation IdentLoc,
3164 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003165 SourceLocation LBrace,
3166 AttributeList *AttrList) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003167 NamespaceDecl *Namespc =
3168 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3169 Namespc->setLBracLoc(LBrace);
3170
3171 Scope *DeclRegionScope = NamespcScope->getParent();
3172
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003173 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3174
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003175 if (II) {
3176 // C++ [namespace.def]p2:
3177 // The identifier in an original-namespace-definition shall not have been
3178 // previously defined in the declarative region in which the
3179 // original-namespace-definition appears. The identifier in an
3180 // original-namespace-definition is the name of the namespace. Subsequently
3181 // in that declarative region, it is treated as an original-namespace-name.
3182
John McCallf36e02d2009-10-09 21:13:30 +00003183 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003184 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003185 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Douglas Gregor44b43212008-12-11 16:49:14 +00003187 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3188 // This is an extended namespace definition.
3189 // Attach this namespace decl to the chain of extended namespace
3190 // definitions.
3191 OrigNS->setNextNamespace(Namespc);
3192 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003193
Mike Stump1eb44332009-09-09 15:08:12 +00003194 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003195 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003196 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003197 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003198 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003199 } else if (PrevDecl) {
3200 // This is an invalid name redefinition.
3201 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3202 << Namespc->getDeclName();
3203 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3204 Namespc->setInvalidDecl();
3205 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003206 } else if (II->isStr("std") &&
3207 CurContext->getLookupContext()->isTranslationUnit()) {
3208 // This is the first "real" definition of the namespace "std", so update
3209 // our cache of the "std" namespace to point at this definition.
3210 if (StdNamespace) {
3211 // We had already defined a dummy namespace "std". Link this new
3212 // namespace definition to the dummy namespace "std".
3213 StdNamespace->setNextNamespace(Namespc);
3214 StdNamespace->setLocation(IdentLoc);
3215 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3216 }
3217
3218 // Make our StdNamespace cache point at the first real definition of the
3219 // "std" namespace.
3220 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003221 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003222
3223 PushOnScopeChains(Namespc, DeclRegionScope);
3224 } else {
John McCall9aeed322009-10-01 00:25:31 +00003225 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003226 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003227
3228 // Link the anonymous namespace into its parent.
3229 NamespaceDecl *PrevDecl;
3230 DeclContext *Parent = CurContext->getLookupContext();
3231 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3232 PrevDecl = TU->getAnonymousNamespace();
3233 TU->setAnonymousNamespace(Namespc);
3234 } else {
3235 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3236 PrevDecl = ND->getAnonymousNamespace();
3237 ND->setAnonymousNamespace(Namespc);
3238 }
3239
3240 // Link the anonymous namespace with its previous declaration.
3241 if (PrevDecl) {
3242 assert(PrevDecl->isAnonymousNamespace());
3243 assert(!PrevDecl->getNextNamespace());
3244 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3245 PrevDecl->setNextNamespace(Namespc);
3246 }
John McCall9aeed322009-10-01 00:25:31 +00003247
Douglas Gregora4181472010-03-24 00:46:35 +00003248 CurContext->addDecl(Namespc);
3249
John McCall9aeed322009-10-01 00:25:31 +00003250 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3251 // behaves as if it were replaced by
3252 // namespace unique { /* empty body */ }
3253 // using namespace unique;
3254 // namespace unique { namespace-body }
3255 // where all occurrences of 'unique' in a translation unit are
3256 // replaced by the same identifier and this identifier differs
3257 // from all other identifiers in the entire program.
3258
3259 // We just create the namespace with an empty name and then add an
3260 // implicit using declaration, just like the standard suggests.
3261 //
3262 // CodeGen enforces the "universally unique" aspect by giving all
3263 // declarations semantically contained within an anonymous
3264 // namespace internal linkage.
3265
John McCall5fdd7642009-12-16 02:06:49 +00003266 if (!PrevDecl) {
3267 UsingDirectiveDecl* UD
3268 = UsingDirectiveDecl::Create(Context, CurContext,
3269 /* 'using' */ LBrace,
3270 /* 'namespace' */ SourceLocation(),
3271 /* qualifier */ SourceRange(),
3272 /* NNS */ NULL,
3273 /* identifier */ SourceLocation(),
3274 Namespc,
3275 /* Ancestor */ CurContext);
3276 UD->setImplicit();
3277 CurContext->addDecl(UD);
3278 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003279 }
3280
3281 // Although we could have an invalid decl (i.e. the namespace name is a
3282 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003283 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3284 // for the namespace has the declarations that showed up in that particular
3285 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003286 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003287 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003288}
3289
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003290/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3291/// is a namespace alias, returns the namespace it points to.
3292static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3293 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3294 return AD->getNamespace();
3295 return dyn_cast_or_null<NamespaceDecl>(D);
3296}
3297
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003298/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3299/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003300void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3301 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003302 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3303 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3304 Namespc->setRBracLoc(RBrace);
3305 PopDeclContext();
3306}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003307
Chris Lattnerb28317a2009-03-28 19:18:32 +00003308Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3309 SourceLocation UsingLoc,
3310 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003311 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003312 SourceLocation IdentLoc,
3313 IdentifierInfo *NamespcName,
3314 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003315 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3316 assert(NamespcName && "Invalid NamespcName.");
3317 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003318 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003319
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003320 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00003321
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003322 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003323 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3324 LookupParsedName(R, S, &SS);
3325 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00003326 return DeclPtrTy();
John McCalla24dc2e2009-11-17 02:14:36 +00003327
John McCallf36e02d2009-10-09 21:13:30 +00003328 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003329 NamedDecl *Named = R.getFoundDecl();
3330 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3331 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003332 // C++ [namespace.udir]p1:
3333 // A using-directive specifies that the names in the nominated
3334 // namespace can be used in the scope in which the
3335 // using-directive appears after the using-directive. During
3336 // unqualified name lookup (3.4.1), the names appear as if they
3337 // were declared in the nearest enclosing namespace which
3338 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003339 // namespace. [Note: in this context, "contains" means "contains
3340 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003341
3342 // Find enclosing context containing both using-directive and
3343 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003344 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003345 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3346 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3347 CommonAncestor = CommonAncestor->getParent();
3348
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003349 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003350 SS.getRange(),
3351 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003352 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003353 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003354 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003355 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003356 }
3357
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003358 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003359 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00003360 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003361}
3362
3363void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3364 // If scope has associated entity, then using directive is at namespace
3365 // or translation unit scope. We add UsingDirectiveDecls, into
3366 // it's lookup structure.
3367 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003368 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003369 else
3370 // Otherwise it is block-sope. using-directives will affect lookup
3371 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003372 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00003373}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003374
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003375
3376Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003377 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003378 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003379 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003380 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003381 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003382 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003383 bool IsTypeName,
3384 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003385 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Douglas Gregor12c118a2009-11-04 16:30:06 +00003387 switch (Name.getKind()) {
3388 case UnqualifiedId::IK_Identifier:
3389 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003390 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003391 case UnqualifiedId::IK_ConversionFunctionId:
3392 break;
3393
3394 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003395 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003396 // C++0x inherited constructors.
3397 if (getLangOptions().CPlusPlus0x) break;
3398
Douglas Gregor12c118a2009-11-04 16:30:06 +00003399 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3400 << SS.getRange();
3401 return DeclPtrTy();
3402
3403 case UnqualifiedId::IK_DestructorName:
3404 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3405 << SS.getRange();
3406 return DeclPtrTy();
3407
3408 case UnqualifiedId::IK_TemplateId:
3409 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3410 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3411 return DeclPtrTy();
3412 }
3413
3414 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall604e7f12009-12-08 07:46:18 +00003415 if (!TargetName)
3416 return DeclPtrTy();
3417
John McCall60fa3cf2009-12-11 02:10:03 +00003418 // Warn about using declarations.
3419 // TODO: store that the declaration was written without 'using' and
3420 // talk about access decls instead of using decls in the
3421 // diagnostics.
3422 if (!HasUsingKeyword) {
3423 UsingLoc = Name.getSourceRange().getBegin();
3424
3425 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003426 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003427 }
3428
John McCall9488ea12009-11-17 05:59:44 +00003429 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003430 Name.getSourceRange().getBegin(),
John McCall7ba107a2009-11-18 02:36:19 +00003431 TargetName, AttrList,
3432 /* IsInstantiation */ false,
3433 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003434 if (UD)
3435 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Anders Carlssonc72160b2009-08-28 05:40:36 +00003437 return DeclPtrTy::make(UD);
3438}
3439
John McCall9f54ad42009-12-10 09:41:52 +00003440/// Determines whether to create a using shadow decl for a particular
3441/// decl, given the set of decls existing prior to this using lookup.
3442bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3443 const LookupResult &Previous) {
3444 // Diagnose finding a decl which is not from a base class of the
3445 // current class. We do this now because there are cases where this
3446 // function will silently decide not to build a shadow decl, which
3447 // will pre-empt further diagnostics.
3448 //
3449 // We don't need to do this in C++0x because we do the check once on
3450 // the qualifier.
3451 //
3452 // FIXME: diagnose the following if we care enough:
3453 // struct A { int foo; };
3454 // struct B : A { using A::foo; };
3455 // template <class T> struct C : A {};
3456 // template <class T> struct D : C<T> { using B::foo; } // <---
3457 // This is invalid (during instantiation) in C++03 because B::foo
3458 // resolves to the using decl in B, which is not a base class of D<T>.
3459 // We can't diagnose it immediately because C<T> is an unknown
3460 // specialization. The UsingShadowDecl in D<T> then points directly
3461 // to A::foo, which will look well-formed when we instantiate.
3462 // The right solution is to not collapse the shadow-decl chain.
3463 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3464 DeclContext *OrigDC = Orig->getDeclContext();
3465
3466 // Handle enums and anonymous structs.
3467 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3468 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3469 while (OrigRec->isAnonymousStructOrUnion())
3470 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3471
3472 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3473 if (OrigDC == CurContext) {
3474 Diag(Using->getLocation(),
3475 diag::err_using_decl_nested_name_specifier_is_current_class)
3476 << Using->getNestedNameRange();
3477 Diag(Orig->getLocation(), diag::note_using_decl_target);
3478 return true;
3479 }
3480
3481 Diag(Using->getNestedNameRange().getBegin(),
3482 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3483 << Using->getTargetNestedNameDecl()
3484 << cast<CXXRecordDecl>(CurContext)
3485 << Using->getNestedNameRange();
3486 Diag(Orig->getLocation(), diag::note_using_decl_target);
3487 return true;
3488 }
3489 }
3490
3491 if (Previous.empty()) return false;
3492
3493 NamedDecl *Target = Orig;
3494 if (isa<UsingShadowDecl>(Target))
3495 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3496
John McCalld7533ec2009-12-11 02:33:26 +00003497 // If the target happens to be one of the previous declarations, we
3498 // don't have a conflict.
3499 //
3500 // FIXME: but we might be increasing its access, in which case we
3501 // should redeclare it.
3502 NamedDecl *NonTag = 0, *Tag = 0;
3503 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3504 I != E; ++I) {
3505 NamedDecl *D = (*I)->getUnderlyingDecl();
3506 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3507 return false;
3508
3509 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3510 }
3511
John McCall9f54ad42009-12-10 09:41:52 +00003512 if (Target->isFunctionOrFunctionTemplate()) {
3513 FunctionDecl *FD;
3514 if (isa<FunctionTemplateDecl>(Target))
3515 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3516 else
3517 FD = cast<FunctionDecl>(Target);
3518
3519 NamedDecl *OldDecl = 0;
3520 switch (CheckOverload(FD, Previous, OldDecl)) {
3521 case Ovl_Overload:
3522 return false;
3523
3524 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003525 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003526 break;
3527
3528 // We found a decl with the exact signature.
3529 case Ovl_Match:
3530 if (isa<UsingShadowDecl>(OldDecl)) {
3531 // Silently ignore the possible conflict.
3532 return false;
3533 }
3534
3535 // If we're in a record, we want to hide the target, so we
3536 // return true (without a diagnostic) to tell the caller not to
3537 // build a shadow decl.
3538 if (CurContext->isRecord())
3539 return true;
3540
3541 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003542 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003543 break;
3544 }
3545
3546 Diag(Target->getLocation(), diag::note_using_decl_target);
3547 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3548 return true;
3549 }
3550
3551 // Target is not a function.
3552
John McCall9f54ad42009-12-10 09:41:52 +00003553 if (isa<TagDecl>(Target)) {
3554 // No conflict between a tag and a non-tag.
3555 if (!Tag) return false;
3556
John McCall41ce66f2009-12-10 19:51:03 +00003557 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003558 Diag(Target->getLocation(), diag::note_using_decl_target);
3559 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3560 return true;
3561 }
3562
3563 // No conflict between a tag and a non-tag.
3564 if (!NonTag) return false;
3565
John McCall41ce66f2009-12-10 19:51:03 +00003566 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003567 Diag(Target->getLocation(), diag::note_using_decl_target);
3568 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3569 return true;
3570}
3571
John McCall9488ea12009-11-17 05:59:44 +00003572/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003573UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003574 UsingDecl *UD,
3575 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003576
3577 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003578 NamedDecl *Target = Orig;
3579 if (isa<UsingShadowDecl>(Target)) {
3580 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3581 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003582 }
3583
3584 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003585 = UsingShadowDecl::Create(Context, CurContext,
3586 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003587 UD->addShadowDecl(Shadow);
3588
3589 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003590 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003591 else
John McCall604e7f12009-12-08 07:46:18 +00003592 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003593 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003594
John McCall32daa422010-03-31 01:36:47 +00003595 // Register it as a conversion if appropriate.
3596 if (Shadow->getDeclName().getNameKind()
3597 == DeclarationName::CXXConversionFunctionName)
3598 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3599
John McCall604e7f12009-12-08 07:46:18 +00003600 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3601 Shadow->setInvalidDecl();
3602
John McCall9f54ad42009-12-10 09:41:52 +00003603 return Shadow;
3604}
John McCall604e7f12009-12-08 07:46:18 +00003605
John McCall9f54ad42009-12-10 09:41:52 +00003606/// Hides a using shadow declaration. This is required by the current
3607/// using-decl implementation when a resolvable using declaration in a
3608/// class is followed by a declaration which would hide or override
3609/// one or more of the using decl's targets; for example:
3610///
3611/// struct Base { void foo(int); };
3612/// struct Derived : Base {
3613/// using Base::foo;
3614/// void foo(int);
3615/// };
3616///
3617/// The governing language is C++03 [namespace.udecl]p12:
3618///
3619/// When a using-declaration brings names from a base class into a
3620/// derived class scope, member functions in the derived class
3621/// override and/or hide member functions with the same name and
3622/// parameter types in a base class (rather than conflicting).
3623///
3624/// There are two ways to implement this:
3625/// (1) optimistically create shadow decls when they're not hidden
3626/// by existing declarations, or
3627/// (2) don't create any shadow decls (or at least don't make them
3628/// visible) until we've fully parsed/instantiated the class.
3629/// The problem with (1) is that we might have to retroactively remove
3630/// a shadow decl, which requires several O(n) operations because the
3631/// decl structures are (very reasonably) not designed for removal.
3632/// (2) avoids this but is very fiddly and phase-dependent.
3633void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003634 if (Shadow->getDeclName().getNameKind() ==
3635 DeclarationName::CXXConversionFunctionName)
3636 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3637
John McCall9f54ad42009-12-10 09:41:52 +00003638 // Remove it from the DeclContext...
3639 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003640
John McCall9f54ad42009-12-10 09:41:52 +00003641 // ...and the scope, if applicable...
3642 if (S) {
3643 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3644 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003645 }
3646
John McCall9f54ad42009-12-10 09:41:52 +00003647 // ...and the using decl.
3648 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3649
3650 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003651 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003652}
3653
John McCall7ba107a2009-11-18 02:36:19 +00003654/// Builds a using declaration.
3655///
3656/// \param IsInstantiation - Whether this call arises from an
3657/// instantiation of an unresolved using declaration. We treat
3658/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003659NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3660 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003661 CXXScopeSpec &SS,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003662 SourceLocation IdentLoc,
3663 DeclarationName Name,
3664 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003665 bool IsInstantiation,
3666 bool IsTypeName,
3667 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003668 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3669 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003670
Anders Carlsson550b14b2009-08-28 05:49:21 +00003671 // FIXME: We ignore attributes for now.
3672 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003674 if (SS.isEmpty()) {
3675 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003676 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003677 }
Mike Stump1eb44332009-09-09 15:08:12 +00003678
John McCall9f54ad42009-12-10 09:41:52 +00003679 // Do the redeclaration lookup in the current scope.
3680 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3681 ForRedeclaration);
3682 Previous.setHideTags(false);
3683 if (S) {
3684 LookupName(Previous, S);
3685
3686 // It is really dumb that we have to do this.
3687 LookupResult::Filter F = Previous.makeFilter();
3688 while (F.hasNext()) {
3689 NamedDecl *D = F.next();
3690 if (!isDeclInScope(D, CurContext, S))
3691 F.erase();
3692 }
3693 F.done();
3694 } else {
3695 assert(IsInstantiation && "no scope in non-instantiation");
3696 assert(CurContext->isRecord() && "scope not record in instantiation");
3697 LookupQualifiedName(Previous, CurContext);
3698 }
3699
Mike Stump1eb44332009-09-09 15:08:12 +00003700 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003701 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3702
John McCall9f54ad42009-12-10 09:41:52 +00003703 // Check for invalid redeclarations.
3704 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3705 return 0;
3706
3707 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003708 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3709 return 0;
3710
John McCallaf8e6ed2009-11-12 03:15:40 +00003711 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003712 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003713 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003714 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003715 // FIXME: not all declaration name kinds are legal here
3716 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3717 UsingLoc, TypenameLoc,
3718 SS.getRange(), NNS,
John McCall7ba107a2009-11-18 02:36:19 +00003719 IdentLoc, Name);
John McCalled976492009-12-04 22:46:56 +00003720 } else {
3721 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3722 UsingLoc, SS.getRange(), NNS,
3723 IdentLoc, Name);
John McCall7ba107a2009-11-18 02:36:19 +00003724 }
John McCalled976492009-12-04 22:46:56 +00003725 } else {
3726 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3727 SS.getRange(), UsingLoc, NNS, Name,
3728 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003729 }
John McCalled976492009-12-04 22:46:56 +00003730 D->setAccess(AS);
3731 CurContext->addDecl(D);
3732
3733 if (!LookupContext) return D;
3734 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003735
John McCall77bb1aa2010-05-01 00:40:08 +00003736 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003737 UD->setInvalidDecl();
3738 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003739 }
3740
John McCall604e7f12009-12-08 07:46:18 +00003741 // Look up the target name.
3742
John McCalla24dc2e2009-11-17 02:14:36 +00003743 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003744
John McCall604e7f12009-12-08 07:46:18 +00003745 // Unlike most lookups, we don't always want to hide tag
3746 // declarations: tag names are visible through the using declaration
3747 // even if hidden by ordinary names, *except* in a dependent context
3748 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003749 if (!IsInstantiation)
3750 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003751
John McCalla24dc2e2009-11-17 02:14:36 +00003752 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003753
John McCallf36e02d2009-10-09 21:13:30 +00003754 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003755 Diag(IdentLoc, diag::err_no_member)
3756 << Name << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003757 UD->setInvalidDecl();
3758 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003759 }
3760
John McCalled976492009-12-04 22:46:56 +00003761 if (R.isAmbiguous()) {
3762 UD->setInvalidDecl();
3763 return UD;
3764 }
Mike Stump1eb44332009-09-09 15:08:12 +00003765
John McCall7ba107a2009-11-18 02:36:19 +00003766 if (IsTypeName) {
3767 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003768 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003769 Diag(IdentLoc, diag::err_using_typename_non_type);
3770 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3771 Diag((*I)->getUnderlyingDecl()->getLocation(),
3772 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003773 UD->setInvalidDecl();
3774 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003775 }
3776 } else {
3777 // If we asked for a non-typename and we got a type, error out,
3778 // but only if this is an instantiation of an unresolved using
3779 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003780 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003781 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3782 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003783 UD->setInvalidDecl();
3784 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003785 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003786 }
3787
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003788 // C++0x N2914 [namespace.udecl]p6:
3789 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003790 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003791 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3792 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003793 UD->setInvalidDecl();
3794 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003795 }
Mike Stump1eb44332009-09-09 15:08:12 +00003796
John McCall9f54ad42009-12-10 09:41:52 +00003797 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3798 if (!CheckUsingShadowDecl(UD, *I, Previous))
3799 BuildUsingShadowDecl(S, UD, *I);
3800 }
John McCall9488ea12009-11-17 05:59:44 +00003801
3802 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003803}
3804
John McCall9f54ad42009-12-10 09:41:52 +00003805/// Checks that the given using declaration is not an invalid
3806/// redeclaration. Note that this is checking only for the using decl
3807/// itself, not for any ill-formedness among the UsingShadowDecls.
3808bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3809 bool isTypeName,
3810 const CXXScopeSpec &SS,
3811 SourceLocation NameLoc,
3812 const LookupResult &Prev) {
3813 // C++03 [namespace.udecl]p8:
3814 // C++0x [namespace.udecl]p10:
3815 // A using-declaration is a declaration and can therefore be used
3816 // repeatedly where (and only where) multiple declarations are
3817 // allowed.
3818 // That's only in file contexts.
3819 if (CurContext->getLookupContext()->isFileContext())
3820 return false;
3821
3822 NestedNameSpecifier *Qual
3823 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3824
3825 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3826 NamedDecl *D = *I;
3827
3828 bool DTypename;
3829 NestedNameSpecifier *DQual;
3830 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3831 DTypename = UD->isTypeName();
3832 DQual = UD->getTargetNestedNameDecl();
3833 } else if (UnresolvedUsingValueDecl *UD
3834 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3835 DTypename = false;
3836 DQual = UD->getTargetNestedNameSpecifier();
3837 } else if (UnresolvedUsingTypenameDecl *UD
3838 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3839 DTypename = true;
3840 DQual = UD->getTargetNestedNameSpecifier();
3841 } else continue;
3842
3843 // using decls differ if one says 'typename' and the other doesn't.
3844 // FIXME: non-dependent using decls?
3845 if (isTypeName != DTypename) continue;
3846
3847 // using decls differ if they name different scopes (but note that
3848 // template instantiation can cause this check to trigger when it
3849 // didn't before instantiation).
3850 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3851 Context.getCanonicalNestedNameSpecifier(DQual))
3852 continue;
3853
3854 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00003855 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00003856 return true;
3857 }
3858
3859 return false;
3860}
3861
John McCall604e7f12009-12-08 07:46:18 +00003862
John McCalled976492009-12-04 22:46:56 +00003863/// Checks that the given nested-name qualifier used in a using decl
3864/// in the current context is appropriately related to the current
3865/// scope. If an error is found, diagnoses it and returns true.
3866bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3867 const CXXScopeSpec &SS,
3868 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00003869 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003870
John McCall604e7f12009-12-08 07:46:18 +00003871 if (!CurContext->isRecord()) {
3872 // C++03 [namespace.udecl]p3:
3873 // C++0x [namespace.udecl]p8:
3874 // A using-declaration for a class member shall be a member-declaration.
3875
3876 // If we weren't able to compute a valid scope, it must be a
3877 // dependent class scope.
3878 if (!NamedContext || NamedContext->isRecord()) {
3879 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3880 << SS.getRange();
3881 return true;
3882 }
3883
3884 // Otherwise, everything is known to be fine.
3885 return false;
3886 }
3887
3888 // The current scope is a record.
3889
3890 // If the named context is dependent, we can't decide much.
3891 if (!NamedContext) {
3892 // FIXME: in C++0x, we can diagnose if we can prove that the
3893 // nested-name-specifier does not refer to a base class, which is
3894 // still possible in some cases.
3895
3896 // Otherwise we have to conservatively report that things might be
3897 // okay.
3898 return false;
3899 }
3900
3901 if (!NamedContext->isRecord()) {
3902 // Ideally this would point at the last name in the specifier,
3903 // but we don't have that level of source info.
3904 Diag(SS.getRange().getBegin(),
3905 diag::err_using_decl_nested_name_specifier_is_not_class)
3906 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3907 return true;
3908 }
3909
3910 if (getLangOptions().CPlusPlus0x) {
3911 // C++0x [namespace.udecl]p3:
3912 // In a using-declaration used as a member-declaration, the
3913 // nested-name-specifier shall name a base class of the class
3914 // being defined.
3915
3916 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3917 cast<CXXRecordDecl>(NamedContext))) {
3918 if (CurContext == NamedContext) {
3919 Diag(NameLoc,
3920 diag::err_using_decl_nested_name_specifier_is_current_class)
3921 << SS.getRange();
3922 return true;
3923 }
3924
3925 Diag(SS.getRange().getBegin(),
3926 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3927 << (NestedNameSpecifier*) SS.getScopeRep()
3928 << cast<CXXRecordDecl>(CurContext)
3929 << SS.getRange();
3930 return true;
3931 }
3932
3933 return false;
3934 }
3935
3936 // C++03 [namespace.udecl]p4:
3937 // A using-declaration used as a member-declaration shall refer
3938 // to a member of a base class of the class being defined [etc.].
3939
3940 // Salient point: SS doesn't have to name a base class as long as
3941 // lookup only finds members from base classes. Therefore we can
3942 // diagnose here only if we can prove that that can't happen,
3943 // i.e. if the class hierarchies provably don't intersect.
3944
3945 // TODO: it would be nice if "definitely valid" results were cached
3946 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3947 // need to be repeated.
3948
3949 struct UserData {
3950 llvm::DenseSet<const CXXRecordDecl*> Bases;
3951
3952 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3953 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3954 Data->Bases.insert(Base);
3955 return true;
3956 }
3957
3958 bool hasDependentBases(const CXXRecordDecl *Class) {
3959 return !Class->forallBases(collect, this);
3960 }
3961
3962 /// Returns true if the base is dependent or is one of the
3963 /// accumulated base classes.
3964 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3965 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3966 return !Data->Bases.count(Base);
3967 }
3968
3969 bool mightShareBases(const CXXRecordDecl *Class) {
3970 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3971 }
3972 };
3973
3974 UserData Data;
3975
3976 // Returns false if we find a dependent base.
3977 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3978 return false;
3979
3980 // Returns false if the class has a dependent base or if it or one
3981 // of its bases is present in the base set of the current context.
3982 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3983 return false;
3984
3985 Diag(SS.getRange().getBegin(),
3986 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3987 << (NestedNameSpecifier*) SS.getScopeRep()
3988 << cast<CXXRecordDecl>(CurContext)
3989 << SS.getRange();
3990
3991 return true;
John McCalled976492009-12-04 22:46:56 +00003992}
3993
Mike Stump1eb44332009-09-09 15:08:12 +00003994Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003995 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003996 SourceLocation AliasLoc,
3997 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003998 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00003999 SourceLocation IdentLoc,
4000 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Anders Carlsson81c85c42009-03-28 23:53:49 +00004002 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004003 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4004 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004005
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004006 // Check if we have a previous declaration with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00004007 if (NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00004008 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4009 ForRedeclaration)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004010 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004011 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004012 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004013 // FIXME: At some point, we'll want to create the (redundant)
4014 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004015 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004016 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlsson81c85c42009-03-28 23:53:49 +00004017 return DeclPtrTy();
4018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004020 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4021 diag::err_redefinition_different_kind;
4022 Diag(AliasLoc, DiagID) << Alias;
4023 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004024 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004025 }
4026
John McCalla24dc2e2009-11-17 02:14:36 +00004027 if (R.isAmbiguous())
Chris Lattnerb28317a2009-03-28 19:18:32 +00004028 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00004029
John McCallf36e02d2009-10-09 21:13:30 +00004030 if (R.empty()) {
Anders Carlsson5721c682009-03-28 06:42:02 +00004031 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004032 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00004033 }
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004035 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004036 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4037 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004038 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004039 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004040
John McCall3dbd3d52010-02-16 06:53:13 +00004041 PushOnScopeChains(AliasDecl, S);
Anders Carlsson68771c72009-03-28 22:58:02 +00004042 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00004043}
4044
Douglas Gregor39957dc2010-05-01 15:04:51 +00004045namespace {
4046 /// \brief Scoped object used to handle the state changes required in Sema
4047 /// to implicitly define the body of a C++ member function;
4048 class ImplicitlyDefinedFunctionScope {
4049 Sema &S;
4050 DeclContext *PreviousContext;
4051
4052 public:
4053 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4054 : S(S), PreviousContext(S.CurContext)
4055 {
4056 S.CurContext = Method;
4057 S.PushFunctionScope();
4058 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4059 }
4060
4061 ~ImplicitlyDefinedFunctionScope() {
4062 S.PopExpressionEvaluationContext();
4063 S.PopFunctionOrBlockScope();
4064 S.CurContext = PreviousContext;
4065 }
4066 };
4067}
4068
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004069void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4070 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004071 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4072 !Constructor->isUsed()) &&
4073 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004075 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004076 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004077
Douglas Gregor39957dc2010-05-01 15:04:51 +00004078 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Anders Carlssonec3332b2010-04-02 03:43:34 +00004079 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson37909802009-11-30 21:24:50 +00004080 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004081 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004082 Constructor->setInvalidDecl();
4083 } else {
4084 Constructor->setUsed();
4085 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004086}
4087
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004088void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004089 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004090 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4091 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004092 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004093 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004094
Douglas Gregor39957dc2010-05-01 15:04:51 +00004095 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004096
John McCallef027fe2010-03-16 21:39:52 +00004097 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4098 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Anders Carlsson37909802009-11-30 21:24:50 +00004100 // FIXME: If CheckDestructor fails, we should emit a note about where the
4101 // implicit destructor was needed.
4102 if (CheckDestructor(Destructor)) {
4103 Diag(CurrentLocation, diag::note_member_synthesized_at)
4104 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4105
4106 Destructor->setInvalidDecl();
4107 return;
4108 }
4109
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004110 Destructor->setUsed();
4111}
4112
Douglas Gregor06a9f362010-05-01 20:49:11 +00004113/// \brief Builds a statement that copies the given entity from \p From to
4114/// \c To.
4115///
4116/// This routine is used to copy the members of a class with an
4117/// implicitly-declared copy assignment operator. When the entities being
4118/// copied are arrays, this routine builds for loops to copy them.
4119///
4120/// \param S The Sema object used for type-checking.
4121///
4122/// \param Loc The location where the implicit copy is being generated.
4123///
4124/// \param T The type of the expressions being copied. Both expressions must
4125/// have this type.
4126///
4127/// \param To The expression we are copying to.
4128///
4129/// \param From The expression we are copying from.
4130///
4131/// \param Depth Internal parameter recording the depth of the recursion.
4132///
4133/// \returns A statement or a loop that copies the expressions.
4134static Sema::OwningStmtResult
4135BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4136 Sema::OwningExprResult To, Sema::OwningExprResult From,
4137 unsigned Depth = 0) {
4138 typedef Sema::OwningStmtResult OwningStmtResult;
4139 typedef Sema::OwningExprResult OwningExprResult;
4140
4141 // C++0x [class.copy]p30:
4142 // Each subobject is assigned in the manner appropriate to its type:
4143 //
4144 // - if the subobject is of class type, the copy assignment operator
4145 // for the class is used (as if by explicit qualification; that is,
4146 // ignoring any possible virtual overriding functions in more derived
4147 // classes);
4148 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4149 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4150
4151 // Look for operator=.
4152 DeclarationName Name
4153 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4154 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4155 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4156
4157 // Filter out any result that isn't a copy-assignment operator.
4158 LookupResult::Filter F = OpLookup.makeFilter();
4159 while (F.hasNext()) {
4160 NamedDecl *D = F.next();
4161 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4162 if (Method->isCopyAssignmentOperator())
4163 continue;
4164
4165 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004166 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004167 F.done();
4168
4169 // Create the nested-name-specifier that will be used to qualify the
4170 // reference to operator=; this is required to suppress the virtual
4171 // call mechanism.
4172 CXXScopeSpec SS;
4173 SS.setRange(Loc);
4174 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4175 T.getTypePtr()));
4176
4177 // Create the reference to operator=.
4178 OwningExprResult OpEqualRef
4179 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4180 /*FirstQualifierInScope=*/0, OpLookup,
4181 /*TemplateArgs=*/0,
4182 /*SuppressQualifierCheck=*/true);
4183 if (OpEqualRef.isInvalid())
4184 return S.StmtError();
4185
4186 // Build the call to the assignment operator.
4187 Expr *FromE = From.takeAs<Expr>();
4188 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4189 OpEqualRef.takeAs<Expr>(),
4190 Loc, &FromE, 1, 0, Loc);
4191 if (Call.isInvalid())
4192 return S.StmtError();
4193
4194 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004195 }
John McCallb0207482010-03-16 06:11:48 +00004196
Douglas Gregor06a9f362010-05-01 20:49:11 +00004197 // - if the subobject is of scalar type, the built-in assignment
4198 // operator is used.
4199 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4200 if (!ArrayTy) {
4201 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4202 BinaryOperator::Assign,
4203 To.takeAs<Expr>(),
4204 From.takeAs<Expr>());
4205 if (Assignment.isInvalid())
4206 return S.StmtError();
4207
4208 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004209 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004210
4211 // - if the subobject is an array, each element is assigned, in the
4212 // manner appropriate to the element type;
4213
4214 // Construct a loop over the array bounds, e.g.,
4215 //
4216 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4217 //
4218 // that will copy each of the array elements.
4219 QualType SizeType = S.Context.getSizeType();
4220
4221 // Create the iteration variable.
4222 IdentifierInfo *IterationVarName = 0;
4223 {
4224 llvm::SmallString<8> Str;
4225 llvm::raw_svector_ostream OS(Str);
4226 OS << "__i" << Depth;
4227 IterationVarName = &S.Context.Idents.get(OS.str());
4228 }
4229 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4230 IterationVarName, SizeType,
4231 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4232 VarDecl::None, VarDecl::None);
4233
4234 // Initialize the iteration variable to zero.
4235 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4236 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4237
4238 // Create a reference to the iteration variable; we'll use this several
4239 // times throughout.
4240 Expr *IterationVarRef
4241 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4242 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4243
4244 // Create the DeclStmt that holds the iteration variable.
4245 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4246
4247 // Create the comparison against the array bound.
4248 llvm::APInt Upper = ArrayTy->getSize();
4249 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4250 OwningExprResult Comparison
4251 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4252 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4253 BinaryOperator::NE, S.Context.BoolTy, Loc));
4254
4255 // Create the pre-increment of the iteration variable.
4256 OwningExprResult Increment
4257 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4258 UnaryOperator::PreInc,
4259 SizeType, Loc));
4260
4261 // Subscript the "from" and "to" expressions with the iteration variable.
4262 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4263 S.Owned(IterationVarRef->Retain()),
4264 Loc);
4265 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4266 S.Owned(IterationVarRef->Retain()),
4267 Loc);
4268 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4269 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4270
4271 // Build the copy for an individual element of the array.
4272 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4273 ArrayTy->getElementType(),
4274 move(To), move(From), Depth+1);
4275 if (Copy.isInvalid()) {
4276 InitStmt->Destroy(S.Context);
4277 return S.StmtError();
4278 }
4279
4280 // Construct the loop that copies all elements of this array.
4281 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4282 S.MakeFullExpr(Comparison),
4283 Sema::DeclPtrTy(),
4284 S.MakeFullExpr(Increment),
4285 Loc, move(Copy));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004286}
4287
Douglas Gregor06a9f362010-05-01 20:49:11 +00004288void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4289 CXXMethodDecl *CopyAssignOperator) {
4290 assert((CopyAssignOperator->isImplicit() &&
4291 CopyAssignOperator->isOverloadedOperator() &&
4292 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4293 !CopyAssignOperator->isUsed()) &&
4294 "DefineImplicitCopyAssignment called for wrong function");
4295
4296 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4297
4298 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4299 CopyAssignOperator->setInvalidDecl();
4300 return;
4301 }
4302
4303 CopyAssignOperator->setUsed();
4304
4305 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4306
4307 // C++0x [class.copy]p30:
4308 // The implicitly-defined or explicitly-defaulted copy assignment operator
4309 // for a non-union class X performs memberwise copy assignment of its
4310 // subobjects. The direct base classes of X are assigned first, in the
4311 // order of their declaration in the base-specifier-list, and then the
4312 // immediate non-static data members of X are assigned, in the order in
4313 // which they were declared in the class definition.
4314
4315 // The statements that form the synthesized function body.
4316 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4317
4318 // The parameter for the "other" object, which we are copying from.
4319 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4320 Qualifiers OtherQuals = Other->getType().getQualifiers();
4321 QualType OtherRefType = Other->getType();
4322 if (const LValueReferenceType *OtherRef
4323 = OtherRefType->getAs<LValueReferenceType>()) {
4324 OtherRefType = OtherRef->getPointeeType();
4325 OtherQuals = OtherRefType.getQualifiers();
4326 }
4327
4328 // Our location for everything implicitly-generated.
4329 SourceLocation Loc = CopyAssignOperator->getLocation();
4330
4331 // Construct a reference to the "other" object. We'll be using this
4332 // throughout the generated ASTs.
4333 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4334 assert(OtherRef && "Reference to parameter cannot fail!");
4335
4336 // Construct the "this" pointer. We'll be using this throughout the generated
4337 // ASTs.
4338 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4339 assert(This && "Reference to this cannot fail!");
4340
4341 // Assign base classes.
4342 bool Invalid = false;
4343 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4344 E = ClassDecl->bases_end(); Base != E; ++Base) {
4345 // Form the assignment:
4346 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4347 QualType BaseType = Base->getType().getUnqualifiedType();
4348 CXXRecordDecl *BaseClassDecl = 0;
4349 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4350 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4351 else {
4352 Invalid = true;
4353 continue;
4354 }
4355
4356 // Construct the "from" expression, which is an implicit cast to the
4357 // appropriately-qualified base type.
4358 Expr *From = OtherRef->Retain();
4359 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4360 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4361 CXXBaseSpecifierArray(Base));
4362
4363 // Dereference "this".
4364 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4365 Owned(This->Retain()));
4366
4367 // Implicitly cast "this" to the appropriately-qualified base type.
4368 Expr *ToE = To.takeAs<Expr>();
4369 ImpCastExprToType(ToE,
4370 Context.getCVRQualifiedType(BaseType,
4371 CopyAssignOperator->getTypeQualifiers()),
4372 CastExpr::CK_UncheckedDerivedToBase,
4373 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4374 To = Owned(ToE);
4375
4376 // Build the copy.
4377 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
4378 move(To), Owned(From));
4379 if (Copy.isInvalid()) {
4380 Invalid = true;
4381 continue;
4382 }
4383
4384 // Success! Record the copy.
4385 Statements.push_back(Copy.takeAs<Expr>());
4386 }
4387
4388 // \brief Reference to the __builtin_memcpy function.
4389 Expr *BuiltinMemCpyRef = 0;
4390
4391 // Assign non-static members.
4392 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4393 FieldEnd = ClassDecl->field_end();
4394 Field != FieldEnd; ++Field) {
4395 // Check for members of reference type; we can't copy those.
4396 if (Field->getType()->isReferenceType()) {
4397 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4398 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4399 Diag(Field->getLocation(), diag::note_declared_at);
4400 Diag(Loc, diag::note_first_required_here);
4401 Invalid = true;
4402 continue;
4403 }
4404
4405 // Check for members of const-qualified, non-class type.
4406 QualType BaseType = Context.getBaseElementType(Field->getType());
4407 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4408 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4409 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4410 Diag(Field->getLocation(), diag::note_declared_at);
4411 Diag(Loc, diag::note_first_required_here);
4412 Invalid = true;
4413 continue;
4414 }
4415
4416 QualType FieldType = Field->getType().getNonReferenceType();
4417
4418 // Build references to the field in the object we're copying from and to.
4419 CXXScopeSpec SS; // Intentionally empty
4420 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4421 LookupMemberName);
4422 MemberLookup.addDecl(*Field);
4423 MemberLookup.resolveKind();
4424 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4425 OtherRefType,
4426 Loc, /*IsArrow=*/false,
4427 SS, 0, MemberLookup, 0);
4428 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4429 This->getType(),
4430 Loc, /*IsArrow=*/true,
4431 SS, 0, MemberLookup, 0);
4432 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4433 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4434
4435 // If the field should be copied with __builtin_memcpy rather than via
4436 // explicit assignments, do so. This optimization only applies for arrays
4437 // of scalars and arrays of class type with trivial copy-assignment
4438 // operators.
4439 if (FieldType->isArrayType() &&
4440 (!BaseType->isRecordType() ||
4441 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4442 ->hasTrivialCopyAssignment())) {
4443 // Compute the size of the memory buffer to be copied.
4444 QualType SizeType = Context.getSizeType();
4445 llvm::APInt Size(Context.getTypeSize(SizeType),
4446 Context.getTypeSizeInChars(BaseType).getQuantity());
4447 for (const ConstantArrayType *Array
4448 = Context.getAsConstantArrayType(FieldType);
4449 Array;
4450 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4451 llvm::APInt ArraySize = Array->getSize();
4452 ArraySize.zextOrTrunc(Size.getBitWidth());
4453 Size *= ArraySize;
4454 }
4455
4456 // Take the address of the field references for "from" and "to".
4457 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4458 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4459
4460 // Create a reference to the __builtin_memcpy builtin function.
4461 if (!BuiltinMemCpyRef) {
4462 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4463 LookupOrdinaryName);
4464 LookupName(R, TUScope, true);
4465
4466 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4467 if (!BuiltinMemCpy) {
4468 // Something went horribly wrong earlier, and we will have complained
4469 // about it.
4470 Invalid = true;
4471 continue;
4472 }
4473
4474 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4475 BuiltinMemCpy->getType(),
4476 Loc, 0).takeAs<Expr>();
4477 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4478 }
4479
4480 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4481 CallArgs.push_back(To.takeAs<Expr>());
4482 CallArgs.push_back(From.takeAs<Expr>());
4483 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4484 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4485 Commas.push_back(Loc);
4486 Commas.push_back(Loc);
4487 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4488 Owned(BuiltinMemCpyRef->Retain()),
4489 Loc, move_arg(CallArgs),
4490 Commas.data(), Loc);
4491 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4492 Statements.push_back(Call.takeAs<Expr>());
4493 continue;
4494 }
4495
4496 // Build the copy of this field.
4497 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
4498 move(To), move(From));
4499 if (Copy.isInvalid()) {
4500 Invalid = true;
4501 continue;
4502 }
4503
4504 // Success! Record the copy.
4505 Statements.push_back(Copy.takeAs<Stmt>());
4506 }
4507
4508 if (!Invalid) {
4509 // Add a "return *this;"
4510 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4511 Owned(This->Retain()));
4512
4513 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4514 if (Return.isInvalid())
4515 Invalid = true;
4516 else {
4517 Statements.push_back(Return.takeAs<Stmt>());
4518 }
4519 }
4520
4521 if (Invalid) {
4522 CopyAssignOperator->setInvalidDecl();
4523 return;
4524 }
4525
4526 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4527 /*isStmtExpr=*/false);
4528 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4529 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004530}
4531
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004532void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4533 CXXConstructorDecl *CopyConstructor,
4534 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00004535 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00004536 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004537 !CopyConstructor->isUsed()) &&
4538 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Anders Carlsson63010a72010-04-23 16:24:12 +00004540 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004541 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004542
Douglas Gregor39957dc2010-05-01 15:04:51 +00004543 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004544
Anders Carlsson59b7f152010-05-01 16:39:01 +00004545 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4546 Diag(CurrentLocation, diag::note_member_synthesized_at)
4547 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4548 CopyConstructor->setInvalidDecl();
4549 } else {
4550 CopyConstructor->setUsed();
Anders Carlsson8e142cc2010-04-25 00:52:09 +00004551 }
Anders Carlsson59b7f152010-05-01 16:39:01 +00004552
4553 // FIXME: Once SetBaseOrMemberInitializers can handle copy initialization of
4554 // fields, this code below should be removed.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004555 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4556 FieldEnd = ClassDecl->field_end();
4557 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004558 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4559 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4560 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004561 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004562 CXXRecordDecl *FieldClassDecl
4563 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004564 if (CXXConstructorDecl *FieldCopyCtor =
John McCallb0207482010-03-16 06:11:48 +00004565 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4566 CheckDirectMemberAccess(Field->getLocation(),
4567 FieldCopyCtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004568 PDiag(diag::err_access_copy_field)
John McCallb0207482010-03-16 06:11:48 +00004569 << Field->getDeclName() << Field->getType());
4570
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00004571 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
John McCallb0207482010-03-16 06:11:48 +00004572 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004573 }
4574 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00004575}
4576
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004577Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004578Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00004579 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00004580 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004581 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004582 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004583 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004584
Douglas Gregor2f599792010-04-02 18:24:57 +00004585 // C++0x [class.copy]p34:
4586 // When certain criteria are met, an implementation is allowed to
4587 // omit the copy/move construction of a class object, even if the
4588 // copy/move constructor and/or destructor for the object have
4589 // side effects. [...]
4590 // - when a temporary class object that has not been bound to a
4591 // reference (12.2) would be copied/moved to a class object
4592 // with the same cv-unqualified type, the copy/move operation
4593 // can be omitted by constructing the temporary object
4594 // directly into the target of the omitted copy/move
4595 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4596 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4597 Elidable = SubExpr->isTemporaryObject() &&
4598 Context.hasSameUnqualifiedType(SubExpr->getType(),
4599 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004600 }
Mike Stump1eb44332009-09-09 15:08:12 +00004601
4602 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004603 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004604 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004605}
4606
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004607/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4608/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004609Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00004610Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4611 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00004612 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004613 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004614 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00004615 unsigned NumExprs = ExprArgs.size();
4616 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Douglas Gregor7edfb692009-11-23 12:27:39 +00004618 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004619 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00004620 Constructor, Elidable, Exprs, NumExprs,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004621 RequiresZeroInit, ConstructKind));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004622}
4623
Mike Stump1eb44332009-09-09 15:08:12 +00004624bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00004625 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004626 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00004627 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00004628 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00004629 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00004630 if (TempResult.isInvalid())
4631 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004632
Anders Carlssonda3f4e22009-08-25 05:12:04 +00004633 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004634 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00004635 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00004636 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Anders Carlssonfe2de492009-08-25 05:18:00 +00004638 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00004639}
4640
John McCall68c6c9a2010-02-02 09:10:11 +00004641void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4642 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00004643 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4644 !ClassDecl->hasTrivialDestructor()) {
John McCall4f9506a2010-02-02 08:45:54 +00004645 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4646 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00004647 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004648 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00004649 << VD->getDeclName()
4650 << VD->getType());
John McCall4f9506a2010-02-02 08:45:54 +00004651 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004652}
4653
Mike Stump1eb44332009-09-09 15:08:12 +00004654/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004655/// ActOnDeclarator, when a C++ direct initializer is present.
4656/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00004657void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4658 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00004659 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004660 SourceLocation *CommaLocs,
4661 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00004662 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00004663 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004664
4665 // If there is no declaration, there was an error parsing it. Just ignore
4666 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004667 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004668 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004669
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004670 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4671 if (!VDecl) {
4672 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4673 RealDecl->setInvalidDecl();
4674 return;
4675 }
4676
Douglas Gregor83ddad32009-08-26 21:14:46 +00004677 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004678 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004679 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4680 //
4681 // Clients that want to distinguish between the two forms, can check for
4682 // direct initializer using VarDecl::hasCXXDirectInitializer().
4683 // A major benefit is that clients that don't particularly care about which
4684 // exactly form was it (like the CodeGen) can handle both cases without
4685 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004686
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004687 // C++ 8.5p11:
4688 // The form of initialization (using parentheses or '=') is generally
4689 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004690 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00004691 QualType DeclInitType = VDecl->getType();
4692 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahanian680a3f32009-10-28 19:04:36 +00004693 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004694
Douglas Gregor4dffad62010-02-11 22:55:30 +00004695 if (!VDecl->getType()->isDependentType() &&
4696 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00004697 diag::err_typecheck_decl_incomplete_type)) {
4698 VDecl->setInvalidDecl();
4699 return;
4700 }
4701
Douglas Gregor90f93822009-12-22 22:17:25 +00004702 // The variable can not have an abstract class type.
4703 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4704 diag::err_abstract_type_in_decl,
4705 AbstractVariableType))
4706 VDecl->setInvalidDecl();
4707
Sebastian Redl31310a22010-02-01 20:16:42 +00004708 const VarDecl *Def;
4709 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004710 Diag(VDecl->getLocation(), diag::err_redefinition)
4711 << VDecl->getDeclName();
4712 Diag(Def->getLocation(), diag::note_previous_definition);
4713 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00004714 return;
4715 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00004716
4717 // If either the declaration has a dependent type or if any of the
4718 // expressions is type-dependent, we represent the initialization
4719 // via a ParenListExpr for later use during template instantiation.
4720 if (VDecl->getType()->isDependentType() ||
4721 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4722 // Let clients know that initialization was done with a direct initializer.
4723 VDecl->setCXXDirectInitializer(true);
4724
4725 // Store the initialization expressions as a ParenListExpr.
4726 unsigned NumExprs = Exprs.size();
4727 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4728 (Expr **)Exprs.release(),
4729 NumExprs, RParenLoc));
4730 return;
4731 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004732
4733 // Capture the variable that is being initialized and the style of
4734 // initialization.
4735 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4736
4737 // FIXME: Poor source location information.
4738 InitializationKind Kind
4739 = InitializationKind::CreateDirect(VDecl->getLocation(),
4740 LParenLoc, RParenLoc);
4741
4742 InitializationSequence InitSeq(*this, Entity, Kind,
4743 (Expr**)Exprs.get(), Exprs.size());
4744 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4745 if (Result.isInvalid()) {
4746 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004747 return;
4748 }
Douglas Gregor90f93822009-12-22 22:17:25 +00004749
4750 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00004751 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004752 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00004753
John McCall68c6c9a2010-02-02 09:10:11 +00004754 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4755 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00004756}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004757
Douglas Gregor39da0b82009-09-09 23:08:42 +00004758/// \brief Given a constructor and the set of arguments provided for the
4759/// constructor, convert the arguments and add any required default arguments
4760/// to form a proper call to this constructor.
4761///
4762/// \returns true if an error occurred, false otherwise.
4763bool
4764Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4765 MultiExprArg ArgsPtr,
4766 SourceLocation Loc,
4767 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4768 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4769 unsigned NumArgs = ArgsPtr.size();
4770 Expr **Args = (Expr **)ArgsPtr.get();
4771
4772 const FunctionProtoType *Proto
4773 = Constructor->getType()->getAs<FunctionProtoType>();
4774 assert(Proto && "Constructor without a prototype?");
4775 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00004776
4777 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004778 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00004779 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004780 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00004781 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00004782
4783 VariadicCallType CallType =
4784 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4785 llvm::SmallVector<Expr *, 8> AllArgs;
4786 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4787 Proto, 0, Args, NumArgs, AllArgs,
4788 CallType);
4789 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4790 ConvertedArgs.push_back(AllArgs[i]);
4791 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004792}
4793
Anders Carlsson20d45d22009-12-12 00:32:00 +00004794static inline bool
4795CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4796 const FunctionDecl *FnDecl) {
4797 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4798 if (isa<NamespaceDecl>(DC)) {
4799 return SemaRef.Diag(FnDecl->getLocation(),
4800 diag::err_operator_new_delete_declared_in_namespace)
4801 << FnDecl->getDeclName();
4802 }
4803
4804 if (isa<TranslationUnitDecl>(DC) &&
4805 FnDecl->getStorageClass() == FunctionDecl::Static) {
4806 return SemaRef.Diag(FnDecl->getLocation(),
4807 diag::err_operator_new_delete_declared_static)
4808 << FnDecl->getDeclName();
4809 }
4810
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00004811 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00004812}
4813
Anders Carlsson156c78e2009-12-13 17:53:43 +00004814static inline bool
4815CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4816 CanQualType ExpectedResultType,
4817 CanQualType ExpectedFirstParamType,
4818 unsigned DependentParamTypeDiag,
4819 unsigned InvalidParamTypeDiag) {
4820 QualType ResultType =
4821 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4822
4823 // Check that the result type is not dependent.
4824 if (ResultType->isDependentType())
4825 return SemaRef.Diag(FnDecl->getLocation(),
4826 diag::err_operator_new_delete_dependent_result_type)
4827 << FnDecl->getDeclName() << ExpectedResultType;
4828
4829 // Check that the result type is what we expect.
4830 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4831 return SemaRef.Diag(FnDecl->getLocation(),
4832 diag::err_operator_new_delete_invalid_result_type)
4833 << FnDecl->getDeclName() << ExpectedResultType;
4834
4835 // A function template must have at least 2 parameters.
4836 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4837 return SemaRef.Diag(FnDecl->getLocation(),
4838 diag::err_operator_new_delete_template_too_few_parameters)
4839 << FnDecl->getDeclName();
4840
4841 // The function decl must have at least 1 parameter.
4842 if (FnDecl->getNumParams() == 0)
4843 return SemaRef.Diag(FnDecl->getLocation(),
4844 diag::err_operator_new_delete_too_few_parameters)
4845 << FnDecl->getDeclName();
4846
4847 // Check the the first parameter type is not dependent.
4848 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4849 if (FirstParamType->isDependentType())
4850 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4851 << FnDecl->getDeclName() << ExpectedFirstParamType;
4852
4853 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00004854 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00004855 ExpectedFirstParamType)
4856 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4857 << FnDecl->getDeclName() << ExpectedFirstParamType;
4858
4859 return false;
4860}
4861
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004862static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00004863CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00004864 // C++ [basic.stc.dynamic.allocation]p1:
4865 // A program is ill-formed if an allocation function is declared in a
4866 // namespace scope other than global scope or declared static in global
4867 // scope.
4868 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4869 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00004870
4871 CanQualType SizeTy =
4872 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4873
4874 // C++ [basic.stc.dynamic.allocation]p1:
4875 // The return type shall be void*. The first parameter shall have type
4876 // std::size_t.
4877 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4878 SizeTy,
4879 diag::err_operator_new_dependent_param_type,
4880 diag::err_operator_new_param_type))
4881 return true;
4882
4883 // C++ [basic.stc.dynamic.allocation]p1:
4884 // The first parameter shall not have an associated default argument.
4885 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00004886 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00004887 diag::err_operator_new_default_arg)
4888 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4889
4890 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00004891}
4892
4893static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004894CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4895 // C++ [basic.stc.dynamic.deallocation]p1:
4896 // A program is ill-formed if deallocation functions are declared in a
4897 // namespace scope other than global scope or declared static in global
4898 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00004899 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4900 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004901
4902 // C++ [basic.stc.dynamic.deallocation]p2:
4903 // Each deallocation function shall return void and its first parameter
4904 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00004905 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4906 SemaRef.Context.VoidPtrTy,
4907 diag::err_operator_delete_dependent_param_type,
4908 diag::err_operator_delete_param_type))
4909 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004910
Anders Carlsson46991d62009-12-12 00:16:02 +00004911 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4912 if (FirstParamType->isDependentType())
4913 return SemaRef.Diag(FnDecl->getLocation(),
4914 diag::err_operator_delete_dependent_param_type)
4915 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4916
4917 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4918 SemaRef.Context.VoidPtrTy)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004919 return SemaRef.Diag(FnDecl->getLocation(),
4920 diag::err_operator_delete_param_type)
4921 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004922
4923 return false;
4924}
4925
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004926/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4927/// of this overloaded operator is well-formed. If so, returns false;
4928/// otherwise, emits appropriate diagnostics and returns true.
4929bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004930 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004931 "Expected an overloaded operator declaration");
4932
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004933 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4934
Mike Stump1eb44332009-09-09 15:08:12 +00004935 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004936 // The allocation and deallocation functions, operator new,
4937 // operator new[], operator delete and operator delete[], are
4938 // described completely in 3.7.3. The attributes and restrictions
4939 // found in the rest of this subclause do not apply to them unless
4940 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00004941 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00004942 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00004943
Anders Carlssona3ccda52009-12-12 00:26:23 +00004944 if (Op == OO_New || Op == OO_Array_New)
4945 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004946
4947 // C++ [over.oper]p6:
4948 // An operator function shall either be a non-static member
4949 // function or be a non-member function and have at least one
4950 // parameter whose type is a class, a reference to a class, an
4951 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004952 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4953 if (MethodDecl->isStatic())
4954 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004955 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004956 } else {
4957 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004958 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4959 ParamEnd = FnDecl->param_end();
4960 Param != ParamEnd; ++Param) {
4961 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00004962 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4963 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004964 ClassOrEnumParam = true;
4965 break;
4966 }
4967 }
4968
Douglas Gregor43c7bad2008-11-17 16:14:12 +00004969 if (!ClassOrEnumParam)
4970 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00004971 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004972 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004973 }
4974
4975 // C++ [over.oper]p8:
4976 // An operator function cannot have default arguments (8.3.6),
4977 // except where explicitly stated below.
4978 //
Mike Stump1eb44332009-09-09 15:08:12 +00004979 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004980 // (C++ [over.call]p1).
4981 if (Op != OO_Call) {
4982 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4983 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00004984 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00004985 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00004986 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00004987 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004988 }
4989 }
4990
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004991 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4992 { false, false, false }
4993#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4994 , { Unary, Binary, MemberOnly }
4995#include "clang/Basic/OperatorKinds.def"
4996 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00004997
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00004998 bool CanBeUnaryOperator = OperatorUses[Op][0];
4999 bool CanBeBinaryOperator = OperatorUses[Op][1];
5000 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005001
5002 // C++ [over.oper]p8:
5003 // [...] Operator functions cannot have more or fewer parameters
5004 // than the number required for the corresponding operator, as
5005 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005006 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005007 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005008 if (Op != OO_Call &&
5009 ((NumParams == 1 && !CanBeUnaryOperator) ||
5010 (NumParams == 2 && !CanBeBinaryOperator) ||
5011 (NumParams < 1) || (NumParams > 2))) {
5012 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005013 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005014 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005015 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005016 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005017 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005018 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005019 assert(CanBeBinaryOperator &&
5020 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005021 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005022 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005023
Chris Lattner416e46f2008-11-21 07:57:12 +00005024 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005025 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005026 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005027
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005028 // Overloaded operators other than operator() cannot be variadic.
5029 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005030 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005031 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005032 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005033 }
5034
5035 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005036 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5037 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005038 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005039 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005040 }
5041
5042 // C++ [over.inc]p1:
5043 // The user-defined function called operator++ implements the
5044 // prefix and postfix ++ operator. If this function is a member
5045 // function with no parameters, or a non-member function with one
5046 // parameter of class or enumeration type, it defines the prefix
5047 // increment operator ++ for objects of that type. If the function
5048 // is a member function with one parameter (which shall be of type
5049 // int) or a non-member function with two parameters (the second
5050 // of which shall be of type int), it defines the postfix
5051 // increment operator ++ for objects of that type.
5052 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5053 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5054 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005055 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005056 ParamIsInt = BT->getKind() == BuiltinType::Int;
5057
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005058 if (!ParamIsInt)
5059 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005060 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005061 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005062 }
5063
Sebastian Redl64b45f72009-01-05 20:52:13 +00005064 // Notify the class if it got an assignment operator.
5065 if (Op == OO_Equal) {
5066 // Would have returned earlier otherwise.
5067 assert(isa<CXXMethodDecl>(FnDecl) &&
5068 "Overloaded = not member, but not filtered.");
5069 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5070 Method->getParent()->addedAssignmentOperator(Context, Method);
5071 }
5072
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005073 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005074}
Chris Lattner5a003a42008-12-17 07:09:26 +00005075
Sean Hunta6c058d2010-01-13 09:01:02 +00005076/// CheckLiteralOperatorDeclaration - Check whether the declaration
5077/// of this literal operator function is well-formed. If so, returns
5078/// false; otherwise, emits appropriate diagnostics and returns true.
5079bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5080 DeclContext *DC = FnDecl->getDeclContext();
5081 Decl::Kind Kind = DC->getDeclKind();
5082 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5083 Kind != Decl::LinkageSpec) {
5084 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5085 << FnDecl->getDeclName();
5086 return true;
5087 }
5088
5089 bool Valid = false;
5090
Sean Hunt216c2782010-04-07 23:11:06 +00005091 // template <char...> type operator "" name() is the only valid template
5092 // signature, and the only valid signature with no parameters.
5093 if (FnDecl->param_size() == 0) {
5094 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5095 // Must have only one template parameter
5096 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5097 if (Params->size() == 1) {
5098 NonTypeTemplateParmDecl *PmDecl =
5099 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005100
Sean Hunt216c2782010-04-07 23:11:06 +00005101 // The template parameter must be a char parameter pack.
5102 // FIXME: This test will always fail because non-type parameter packs
5103 // have not been implemented.
5104 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5105 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5106 Valid = true;
5107 }
5108 }
5109 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005110 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005111 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5112
Sean Hunta6c058d2010-01-13 09:01:02 +00005113 QualType T = (*Param)->getType();
5114
Sean Hunt30019c02010-04-07 22:57:35 +00005115 // unsigned long long int, long double, and any character type are allowed
5116 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005117 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5118 Context.hasSameType(T, Context.LongDoubleTy) ||
5119 Context.hasSameType(T, Context.CharTy) ||
5120 Context.hasSameType(T, Context.WCharTy) ||
5121 Context.hasSameType(T, Context.Char16Ty) ||
5122 Context.hasSameType(T, Context.Char32Ty)) {
5123 if (++Param == FnDecl->param_end())
5124 Valid = true;
5125 goto FinishedParams;
5126 }
5127
Sean Hunt30019c02010-04-07 22:57:35 +00005128 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005129 const PointerType *PT = T->getAs<PointerType>();
5130 if (!PT)
5131 goto FinishedParams;
5132 T = PT->getPointeeType();
5133 if (!T.isConstQualified())
5134 goto FinishedParams;
5135 T = T.getUnqualifiedType();
5136
5137 // Move on to the second parameter;
5138 ++Param;
5139
5140 // If there is no second parameter, the first must be a const char *
5141 if (Param == FnDecl->param_end()) {
5142 if (Context.hasSameType(T, Context.CharTy))
5143 Valid = true;
5144 goto FinishedParams;
5145 }
5146
5147 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5148 // are allowed as the first parameter to a two-parameter function
5149 if (!(Context.hasSameType(T, Context.CharTy) ||
5150 Context.hasSameType(T, Context.WCharTy) ||
5151 Context.hasSameType(T, Context.Char16Ty) ||
5152 Context.hasSameType(T, Context.Char32Ty)))
5153 goto FinishedParams;
5154
5155 // The second and final parameter must be an std::size_t
5156 T = (*Param)->getType().getUnqualifiedType();
5157 if (Context.hasSameType(T, Context.getSizeType()) &&
5158 ++Param == FnDecl->param_end())
5159 Valid = true;
5160 }
5161
5162 // FIXME: This diagnostic is absolutely terrible.
5163FinishedParams:
5164 if (!Valid) {
5165 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5166 << FnDecl->getDeclName();
5167 return true;
5168 }
5169
5170 return false;
5171}
5172
Douglas Gregor074149e2009-01-05 19:45:36 +00005173/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5174/// linkage specification, including the language and (if present)
5175/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5176/// the location of the language string literal, which is provided
5177/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5178/// the '{' brace. Otherwise, this linkage specification does not
5179/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005180Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5181 SourceLocation ExternLoc,
5182 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00005183 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005184 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00005185 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005186 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005187 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00005188 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00005189 Language = LinkageSpecDecl::lang_cxx;
5190 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00005191 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005192 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00005193 }
Mike Stump1eb44332009-09-09 15:08:12 +00005194
Chris Lattnercc98eac2008-12-17 07:13:27 +00005195 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00005196
Douglas Gregor074149e2009-01-05 19:45:36 +00005197 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00005198 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00005199 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005200 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00005201 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005202 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00005203}
5204
Douglas Gregor074149e2009-01-05 19:45:36 +00005205/// ActOnFinishLinkageSpecification - Completely the definition of
5206/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5207/// valid, it's the position of the closing '}' brace in a linkage
5208/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005209Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5210 DeclPtrTy LinkageSpec,
5211 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00005212 if (LinkageSpec)
5213 PopDeclContext();
5214 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00005215}
5216
Douglas Gregord308e622009-05-18 20:51:54 +00005217/// \brief Perform semantic analysis for the variable declaration that
5218/// occurs within a C++ catch clause, returning the newly-created
5219/// variable.
5220VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00005221 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005222 IdentifierInfo *Name,
5223 SourceLocation Loc,
5224 SourceRange Range) {
5225 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005226
5227 // Arrays and functions decay.
5228 if (ExDeclType->isArrayType())
5229 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5230 else if (ExDeclType->isFunctionType())
5231 ExDeclType = Context.getPointerType(ExDeclType);
5232
5233 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5234 // The exception-declaration shall not denote a pointer or reference to an
5235 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005236 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00005237 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00005238 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005239 Invalid = true;
5240 }
Douglas Gregord308e622009-05-18 20:51:54 +00005241
Douglas Gregora2762912010-03-08 01:47:36 +00005242 // GCC allows catching pointers and references to incomplete types
5243 // as an extension; so do we, but we warn by default.
5244
Sebastian Redl4b07b292008-12-22 19:15:10 +00005245 QualType BaseType = ExDeclType;
5246 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005247 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00005248 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00005249 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005250 BaseType = Ptr->getPointeeType();
5251 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00005252 DK = diag::ext_catch_incomplete_ptr;
5253 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005254 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005255 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005256 BaseType = Ref->getPointeeType();
5257 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00005258 DK = diag::ext_catch_incomplete_ref;
5259 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005260 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00005261 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00005262 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5263 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00005264 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005265
Mike Stump1eb44332009-09-09 15:08:12 +00005266 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00005267 RequireNonAbstractType(Loc, ExDeclType,
5268 diag::err_abstract_type_in_decl,
5269 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00005270 Invalid = true;
5271
Mike Stump1eb44332009-09-09 15:08:12 +00005272 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005273 Name, ExDeclType, TInfo, VarDecl::None,
5274 VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00005275
Douglas Gregor6d182892010-03-05 23:38:39 +00005276 if (!Invalid) {
5277 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5278 // C++ [except.handle]p16:
5279 // The object declared in an exception-declaration or, if the
5280 // exception-declaration does not specify a name, a temporary (12.2) is
5281 // copy-initialized (8.5) from the exception object. [...]
5282 // The object is destroyed when the handler exits, after the destruction
5283 // of any automatic objects initialized within the handler.
5284 //
5285 // We just pretend to initialize the object with itself, then make sure
5286 // it can be destroyed later.
5287 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5288 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5289 Loc, ExDeclType, 0);
5290 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5291 SourceLocation());
5292 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5293 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5294 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5295 if (Result.isInvalid())
5296 Invalid = true;
5297 else
5298 FinalizeVarWithDestructor(ExDecl, RecordTy);
5299 }
5300 }
5301
Douglas Gregord308e622009-05-18 20:51:54 +00005302 if (Invalid)
5303 ExDecl->setInvalidDecl();
5304
5305 return ExDecl;
5306}
5307
5308/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5309/// handler.
5310Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCalla93c9342009-12-07 02:54:59 +00005311 TypeSourceInfo *TInfo = 0;
5312 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00005313
5314 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00005315 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00005316 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00005317 LookupOrdinaryName,
5318 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005319 // The scope should be freshly made just for us. There is just no way
5320 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005321 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00005322 if (PrevDecl->isTemplateParameter()) {
5323 // Maybe we will complain about the shadowed template parameter.
5324 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005325 }
5326 }
5327
Chris Lattnereaaebc72009-04-25 08:06:05 +00005328 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00005329 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5330 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00005331 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00005332 }
5333
John McCalla93c9342009-12-07 02:54:59 +00005334 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00005335 D.getIdentifier(),
5336 D.getIdentifierLoc(),
5337 D.getDeclSpec().getSourceRange());
5338
Chris Lattnereaaebc72009-04-25 08:06:05 +00005339 if (Invalid)
5340 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005341
Sebastian Redl4b07b292008-12-22 19:15:10 +00005342 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00005343 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00005344 PushOnScopeChains(ExDecl, S);
5345 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005346 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005347
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005348 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005349 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00005350}
Anders Carlssonfb311762009-03-14 00:25:26 +00005351
Mike Stump1eb44332009-09-09 15:08:12 +00005352Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005353 ExprArg assertexpr,
5354 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00005355 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005356 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00005357 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5358
Anders Carlssonc3082412009-03-14 00:33:21 +00005359 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5360 llvm::APSInt Value(32);
5361 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5362 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5363 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00005364 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00005365 }
Anders Carlssonfb311762009-03-14 00:25:26 +00005366
Anders Carlssonc3082412009-03-14 00:33:21 +00005367 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00005368 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00005369 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00005370 }
5371 }
Mike Stump1eb44332009-09-09 15:08:12 +00005372
Anders Carlsson77d81422009-03-15 17:35:16 +00005373 assertexpr.release();
5374 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005375 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00005376 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00005377
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005378 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005379 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00005380}
Sebastian Redl50de12f2009-03-24 22:27:57 +00005381
Douglas Gregor1d869352010-04-07 16:53:43 +00005382/// \brief Perform semantic analysis of the given friend type declaration.
5383///
5384/// \returns A friend declaration that.
5385FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5386 TypeSourceInfo *TSInfo) {
5387 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5388
5389 QualType T = TSInfo->getType();
5390 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5391
Douglas Gregor06245bf2010-04-07 17:57:12 +00005392 if (!getLangOptions().CPlusPlus0x) {
5393 // C++03 [class.friend]p2:
5394 // An elaborated-type-specifier shall be used in a friend declaration
5395 // for a class.*
5396 //
5397 // * The class-key of the elaborated-type-specifier is required.
5398 if (!ActiveTemplateInstantiations.empty()) {
5399 // Do not complain about the form of friend template types during
5400 // template instantiation; we will already have complained when the
5401 // template was declared.
5402 } else if (!T->isElaboratedTypeSpecifier()) {
5403 // If we evaluated the type to a record type, suggest putting
5404 // a tag in front.
5405 if (const RecordType *RT = T->getAs<RecordType>()) {
5406 RecordDecl *RD = RT->getDecl();
5407
5408 std::string InsertionText = std::string(" ") + RD->getKindName();
5409
5410 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5411 << (unsigned) RD->getTagKind()
5412 << T
5413 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5414 InsertionText);
5415 } else {
5416 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5417 << T
5418 << SourceRange(FriendLoc, TypeRange.getEnd());
5419 }
5420 } else if (T->getAs<EnumType>()) {
5421 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00005422 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00005423 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00005424 }
5425 }
5426
Douglas Gregor06245bf2010-04-07 17:57:12 +00005427 // C++0x [class.friend]p3:
5428 // If the type specifier in a friend declaration designates a (possibly
5429 // cv-qualified) class type, that class is declared as a friend; otherwise,
5430 // the friend declaration is ignored.
5431
5432 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5433 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00005434
5435 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5436}
5437
John McCalldd4a3b02009-09-16 22:47:08 +00005438/// Handle a friend type declaration. This works in tandem with
5439/// ActOnTag.
5440///
5441/// Notes on friend class templates:
5442///
5443/// We generally treat friend class declarations as if they were
5444/// declaring a class. So, for example, the elaborated type specifier
5445/// in a friend declaration is required to obey the restrictions of a
5446/// class-head (i.e. no typedefs in the scope chain), template
5447/// parameters are required to match up with simple template-ids, &c.
5448/// However, unlike when declaring a template specialization, it's
5449/// okay to refer to a template specialization without an empty
5450/// template parameter declaration, e.g.
5451/// friend class A<T>::B<unsigned>;
5452/// We permit this as a special case; if there are any template
5453/// parameters present at all, require proper matching, i.e.
5454/// template <> template <class T> friend class A<int>::B;
Chris Lattnerc7f19042009-10-25 17:47:27 +00005455Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00005456 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00005457 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00005458
5459 assert(DS.isFriendSpecified());
5460 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5461
John McCalldd4a3b02009-09-16 22:47:08 +00005462 // Try to convert the decl specifier to a type. This works for
5463 // friend templates because ActOnTag never produces a ClassTemplateDecl
5464 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00005465 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall32f2fb52010-03-25 18:04:51 +00005466 TypeSourceInfo *TSI;
5467 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattnerc7f19042009-10-25 17:47:27 +00005468 if (TheDeclarator.isInvalidType())
5469 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005470
Douglas Gregor1d869352010-04-07 16:53:43 +00005471 if (!TSI)
5472 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5473
John McCalldd4a3b02009-09-16 22:47:08 +00005474 // This is definitely an error in C++98. It's probably meant to
5475 // be forbidden in C++0x, too, but the specification is just
5476 // poorly written.
5477 //
5478 // The problem is with declarations like the following:
5479 // template <T> friend A<T>::foo;
5480 // where deciding whether a class C is a friend or not now hinges
5481 // on whether there exists an instantiation of A that causes
5482 // 'foo' to equal C. There are restrictions on class-heads
5483 // (which we declare (by fiat) elaborated friend declarations to
5484 // be) that makes this tractable.
5485 //
5486 // FIXME: handle "template <> friend class A<T>;", which
5487 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00005488 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00005489 Diag(Loc, diag::err_tagless_friend_type_template)
5490 << DS.getSourceRange();
5491 return DeclPtrTy();
5492 }
Douglas Gregor1d869352010-04-07 16:53:43 +00005493
John McCall02cace72009-08-28 07:59:38 +00005494 // C++98 [class.friend]p1: A friend of a class is a function
5495 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00005496 // This is fixed in DR77, which just barely didn't make the C++03
5497 // deadline. It's also a very silly restriction that seriously
5498 // affects inner classes and which nobody else seems to implement;
5499 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00005500 //
5501 // But note that we could warn about it: it's always useless to
5502 // friend one of your own members (it's not, however, worthless to
5503 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00005504
John McCalldd4a3b02009-09-16 22:47:08 +00005505 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00005506 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00005507 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00005508 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00005509 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00005510 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00005511 DS.getFriendSpecLoc());
5512 else
Douglas Gregor1d869352010-04-07 16:53:43 +00005513 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5514
5515 if (!D)
5516 return DeclPtrTy();
5517
John McCalldd4a3b02009-09-16 22:47:08 +00005518 D->setAccess(AS_public);
5519 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00005520
John McCalldd4a3b02009-09-16 22:47:08 +00005521 return DeclPtrTy::make(D);
John McCall02cace72009-08-28 07:59:38 +00005522}
5523
John McCallbbbcdd92009-09-11 21:02:39 +00005524Sema::DeclPtrTy
5525Sema::ActOnFriendFunctionDecl(Scope *S,
5526 Declarator &D,
5527 bool IsDefinition,
5528 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00005529 const DeclSpec &DS = D.getDeclSpec();
5530
5531 assert(DS.isFriendSpecified());
5532 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5533
5534 SourceLocation Loc = D.getIdentifierLoc();
John McCalla93c9342009-12-07 02:54:59 +00005535 TypeSourceInfo *TInfo = 0;
5536 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall67d1a672009-08-06 02:15:43 +00005537
5538 // C++ [class.friend]p1
5539 // A friend of a class is a function or class....
5540 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00005541 // It *doesn't* see through dependent types, which is correct
5542 // according to [temp.arg.type]p3:
5543 // If a declaration acquires a function type through a
5544 // type dependent on a template-parameter and this causes
5545 // a declaration that does not use the syntactic form of a
5546 // function declarator to have a function type, the program
5547 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00005548 if (!T->isFunctionType()) {
5549 Diag(Loc, diag::err_unexpected_friend);
5550
5551 // It might be worthwhile to try to recover by creating an
5552 // appropriate declaration.
5553 return DeclPtrTy();
5554 }
5555
5556 // C++ [namespace.memdef]p3
5557 // - If a friend declaration in a non-local class first declares a
5558 // class or function, the friend class or function is a member
5559 // of the innermost enclosing namespace.
5560 // - The name of the friend is not found by simple name lookup
5561 // until a matching declaration is provided in that namespace
5562 // scope (either before or after the class declaration granting
5563 // friendship).
5564 // - If a friend function is called, its name may be found by the
5565 // name lookup that considers functions from namespaces and
5566 // classes associated with the types of the function arguments.
5567 // - When looking for a prior declaration of a class or a function
5568 // declared as a friend, scopes outside the innermost enclosing
5569 // namespace scope are not considered.
5570
John McCall02cace72009-08-28 07:59:38 +00005571 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5572 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00005573 assert(Name);
5574
John McCall67d1a672009-08-06 02:15:43 +00005575 // The context we found the declaration in, or in which we should
5576 // create the declaration.
5577 DeclContext *DC;
5578
5579 // FIXME: handle local classes
5580
5581 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall68263142009-11-18 22:49:29 +00005582 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5583 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00005584 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5585 DC = computeDeclContext(ScopeQual);
5586
5587 // FIXME: handle dependent contexts
5588 if (!DC) return DeclPtrTy();
John McCall77bb1aa2010-05-01 00:40:08 +00005589 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00005590
John McCall68263142009-11-18 22:49:29 +00005591 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005592
5593 // If searching in that context implicitly found a declaration in
5594 // a different context, treat it like it wasn't found at all.
5595 // TODO: better diagnostics for this case. Suggesting the right
5596 // qualified scope would be nice...
John McCall68263142009-11-18 22:49:29 +00005597 // FIXME: getRepresentativeDecl() is not right here at all
5598 if (Previous.empty() ||
5599 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCall02cace72009-08-28 07:59:38 +00005600 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00005601 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5602 return DeclPtrTy();
5603 }
5604
5605 // C++ [class.friend]p1: A friend of a class is a function or
5606 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00005607 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00005608 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5609
John McCall67d1a672009-08-06 02:15:43 +00005610 // Otherwise walk out to the nearest namespace scope looking for matches.
5611 } else {
5612 // TODO: handle local class contexts.
5613
5614 DC = CurContext;
5615 while (true) {
5616 // Skip class contexts. If someone can cite chapter and verse
5617 // for this behavior, that would be nice --- it's what GCC and
5618 // EDG do, and it seems like a reasonable intent, but the spec
5619 // really only says that checks for unqualified existing
5620 // declarations should stop at the nearest enclosing namespace,
5621 // not that they should only consider the nearest enclosing
5622 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00005623 while (DC->isRecord())
5624 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00005625
John McCall68263142009-11-18 22:49:29 +00005626 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00005627
5628 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00005629 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00005630 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00005631
John McCall67d1a672009-08-06 02:15:43 +00005632 if (DC->isFileContext()) break;
5633 DC = DC->getParent();
5634 }
5635
5636 // C++ [class.friend]p1: A friend of a class is a function or
5637 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00005638 // C++0x changes this for both friend types and functions.
5639 // Most C++ 98 compilers do seem to give an error here, so
5640 // we do, too.
John McCall68263142009-11-18 22:49:29 +00005641 if (!Previous.empty() && DC->Equals(CurContext)
5642 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00005643 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5644 }
5645
Douglas Gregor182ddf02009-09-28 00:08:27 +00005646 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00005647 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005648 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5649 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5650 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00005651 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005652 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5653 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00005654 return DeclPtrTy();
5655 }
John McCall67d1a672009-08-06 02:15:43 +00005656 }
5657
Douglas Gregor182ddf02009-09-28 00:08:27 +00005658 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00005659 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00005660 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00005661 IsDefinition,
5662 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00005663 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00005664
Douglas Gregor182ddf02009-09-28 00:08:27 +00005665 assert(ND->getDeclContext() == DC);
5666 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00005667
John McCallab88d972009-08-31 22:39:49 +00005668 // Add the function declaration to the appropriate lookup tables,
5669 // adjusting the redeclarations list as necessary. We don't
5670 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00005671 //
John McCallab88d972009-08-31 22:39:49 +00005672 // Also update the scope-based lookup if the target context's
5673 // lookup context is in lexical scope.
5674 if (!CurContext->isDependentContext()) {
5675 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00005676 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005677 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00005678 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00005679 }
John McCall02cace72009-08-28 07:59:38 +00005680
5681 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00005682 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00005683 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00005684 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00005685 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00005686
Douglas Gregor182ddf02009-09-28 00:08:27 +00005687 return DeclPtrTy::make(ND);
Anders Carlsson00338362009-05-11 22:55:49 +00005688}
5689
Chris Lattnerb28317a2009-03-28 19:18:32 +00005690void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005691 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00005692
Chris Lattnerb28317a2009-03-28 19:18:32 +00005693 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00005694 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5695 if (!Fn) {
5696 Diag(DelLoc, diag::err_deleted_non_function);
5697 return;
5698 }
5699 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5700 Diag(DelLoc, diag::err_deleted_decl_not_first);
5701 Diag(Prev->getLocation(), diag::note_previous_declaration);
5702 // If the declaration wasn't the first, we delete the function anyway for
5703 // recovery.
5704 }
5705 Fn->setDeleted();
5706}
Sebastian Redl13e88542009-04-27 21:33:24 +00005707
5708static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5709 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5710 ++CI) {
5711 Stmt *SubStmt = *CI;
5712 if (!SubStmt)
5713 continue;
5714 if (isa<ReturnStmt>(SubStmt))
5715 Self.Diag(SubStmt->getSourceRange().getBegin(),
5716 diag::err_return_in_constructor_handler);
5717 if (!isa<Expr>(SubStmt))
5718 SearchForReturnInStmt(Self, SubStmt);
5719 }
5720}
5721
5722void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5723 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5724 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5725 SearchForReturnInStmt(*this, Handler);
5726 }
5727}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005728
Mike Stump1eb44332009-09-09 15:08:12 +00005729bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005730 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00005731 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5732 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005733
Chandler Carruth73857792010-02-15 11:53:20 +00005734 if (Context.hasSameType(NewTy, OldTy) ||
5735 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005737
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005738 // Check if the return types are covariant
5739 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00005740
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005741 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005742 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5743 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005744 NewClassTy = NewPT->getPointeeType();
5745 OldClassTy = OldPT->getPointeeType();
5746 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005747 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5748 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5749 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5750 NewClassTy = NewRT->getPointeeType();
5751 OldClassTy = OldRT->getPointeeType();
5752 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005753 }
5754 }
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005756 // The return types aren't either both pointers or references to a class type.
5757 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005758 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005759 diag::err_different_return_type_for_overriding_virtual_function)
5760 << New->getDeclName() << NewTy << OldTy;
5761 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005763 return true;
5764 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005765
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005766 // C++ [class.virtual]p6:
5767 // If the return type of D::f differs from the return type of B::f, the
5768 // class type in the return type of D::f shall be complete at the point of
5769 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00005770 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5771 if (!RT->isBeingDefined() &&
5772 RequireCompleteType(New->getLocation(), NewClassTy,
5773 PDiag(diag::err_covariant_return_incomplete)
5774 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005775 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00005776 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00005777
Douglas Gregora4923eb2009-11-16 21:35:15 +00005778 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005779 // Check if the new class derives from the old class.
5780 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5781 Diag(New->getLocation(),
5782 diag::err_covariant_return_not_derived)
5783 << New->getDeclName() << NewTy << OldTy;
5784 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5785 return true;
5786 }
Mike Stump1eb44332009-09-09 15:08:12 +00005787
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005788 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00005789 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00005790 diag::err_covariant_return_inaccessible_base,
5791 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5792 // FIXME: Should this point to the return type?
5793 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005794 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5795 return true;
5796 }
5797 }
Mike Stump1eb44332009-09-09 15:08:12 +00005798
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005799 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00005800 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005801 Diag(New->getLocation(),
5802 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005803 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005804 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5805 return true;
5806 };
Mike Stump1eb44332009-09-09 15:08:12 +00005807
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005808
5809 // The new class type must have the same or less qualifiers as the old type.
5810 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5811 Diag(New->getLocation(),
5812 diag::err_covariant_return_type_class_type_more_qualified)
5813 << New->getDeclName() << NewTy << OldTy;
5814 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5815 return true;
5816 };
Mike Stump1eb44332009-09-09 15:08:12 +00005817
Anders Carlssonc3a68b22009-05-14 19:52:19 +00005818 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00005819}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005820
Sean Huntbbd37c62009-11-21 08:43:09 +00005821bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5822 const CXXMethodDecl *Old)
5823{
5824 if (Old->hasAttr<FinalAttr>()) {
5825 Diag(New->getLocation(), diag::err_final_function_overridden)
5826 << New->getDeclName();
5827 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5828 return true;
5829 }
5830
5831 return false;
5832}
5833
Douglas Gregor4ba31362009-12-01 17:24:26 +00005834/// \brief Mark the given method pure.
5835///
5836/// \param Method the method to be marked pure.
5837///
5838/// \param InitRange the source range that covers the "0" initializer.
5839bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5840 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5841 Method->setPure();
5842
5843 // A class is abstract if at least one function is pure virtual.
5844 Method->getParent()->setAbstract(true);
5845 return false;
5846 }
5847
5848 if (!Method->isInvalidDecl())
5849 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5850 << Method->getDeclName() << InitRange;
5851 return true;
5852}
5853
John McCall731ad842009-12-19 09:28:58 +00005854/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5855/// an initializer for the out-of-line declaration 'Dcl'. The scope
5856/// is a fresh scope pushed for just this purpose.
5857///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005858/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5859/// static data member of class X, names should be looked up in the scope of
5860/// class X.
5861void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005862 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005863 Decl *D = Dcl.getAs<Decl>();
5864 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005865
John McCall731ad842009-12-19 09:28:58 +00005866 // We should only get called for declarations with scope specifiers, like:
5867 // int foo::bar;
5868 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005869 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005870}
5871
5872/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall731ad842009-12-19 09:28:58 +00005873/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005874void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005875 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00005876 Decl *D = Dcl.getAs<Decl>();
5877 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005878
John McCall731ad842009-12-19 09:28:58 +00005879 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00005880 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00005881}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005882
5883/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5884/// C++ if/switch/while/for statement.
5885/// e.g: "if (int x = f()) {...}"
5886Action::DeclResult
5887Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5888 // C++ 6.4p2:
5889 // The declarator shall not specify a function or an array.
5890 // The type-specifier-seq shall not contain typedef and shall not declare a
5891 // new class or enumeration.
5892 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5893 "Parser allowed 'typedef' as storage class of condition decl.");
5894
John McCalla93c9342009-12-07 02:54:59 +00005895 TypeSourceInfo *TInfo = 0;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005896 TagDecl *OwnedTag = 0;
John McCalla93c9342009-12-07 02:54:59 +00005897 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00005898
5899 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5900 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5901 // would be created and CXXConditionDeclExpr wants a VarDecl.
5902 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5903 << D.getSourceRange();
5904 return DeclResult();
5905 } else if (OwnedTag && OwnedTag->isDefinition()) {
5906 // The type-specifier-seq shall not declare a new class or enumeration.
5907 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5908 }
5909
5910 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5911 if (!Dcl)
5912 return DeclResult();
5913
5914 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5915 VD->setDeclaredInCondition(true);
5916 return Dcl;
5917}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005918
Anders Carlsson046c2942010-04-17 20:15:18 +00005919static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005920 // Ignore dependent types.
5921 if (MD->isDependentContext())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005922 return false;
Anders Carlssonf53df232009-12-07 04:35:11 +00005923
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005924 // Ignore declarations that are not definitions.
5925 if (!MD->isThisDeclarationADefinition())
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005926 return false;
5927
5928 CXXRecordDecl *RD = MD->getParent();
5929
5930 // Ignore classes without a vtable.
5931 if (!RD->isDynamicClass())
5932 return false;
5933
5934 switch (MD->getParent()->getTemplateSpecializationKind()) {
5935 case TSK_Undeclared:
5936 case TSK_ExplicitSpecialization:
5937 // Classes that aren't instantiations of templates don't need their
5938 // virtual methods marked until we see the definition of the key
5939 // function.
5940 break;
5941
5942 case TSK_ImplicitInstantiation:
5943 // This is a constructor of a class template; mark all of the virtual
5944 // members as referenced to ensure that they get instantiatied.
5945 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5946 return true;
5947 break;
5948
5949 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005950 return false;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005951
5952 case TSK_ExplicitInstantiationDefinition:
5953 // This is method of a explicit instantiation; mark all of the virtual
5954 // members as referenced to ensure that they get instantiatied.
5955 return true;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00005956 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005957
5958 // Consider only out-of-line definitions of member functions. When we see
5959 // an inline definition, it's too early to compute the key function.
5960 if (!MD->isOutOfLine())
5961 return false;
5962
5963 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5964
5965 // If there is no key function, we will need a copy of the vtable.
5966 if (!KeyFunction)
5967 return true;
5968
5969 // If this is the key function, we need to mark virtual members.
5970 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5971 return true;
5972
5973 return false;
5974}
5975
5976void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5977 CXXMethodDecl *MD) {
5978 CXXRecordDecl *RD = MD->getParent();
5979
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005980 // We will need to mark all of the virtual members as referenced to build the
5981 // vtable.
Anders Carlsson046c2942010-04-17 20:15:18 +00005982 if (!needsVTable(MD, Context))
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00005983 return;
5984
5985 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5986 if (kind == TSK_ImplicitInstantiation)
5987 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5988 else
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00005989 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssond6a637f2009-12-07 08:24:59 +00005990}
5991
5992bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5993 if (ClassesWithUnmarkedVirtualMembers.empty())
5994 return false;
5995
Douglas Gregor159ef1e2010-01-06 04:44:19 +00005996 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5997 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5998 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5999 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlssond6a637f2009-12-07 08:24:59 +00006000 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006001 }
6002
Anders Carlssond6a637f2009-12-07 08:24:59 +00006003 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006004}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006005
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006006void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6007 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006008 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6009 e = RD->method_end(); i != e; ++i) {
6010 CXXMethodDecl *MD = *i;
6011
6012 // C++ [basic.def.odr]p2:
6013 // [...] A virtual member function is used if it is not pure. [...]
6014 if (MD->isVirtual() && !MD->isPure())
6015 MarkDeclarationReferenced(Loc, MD);
6016 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006017
6018 // Only classes that have virtual bases need a VTT.
6019 if (RD->getNumVBases() == 0)
6020 return;
6021
6022 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6023 e = RD->bases_end(); i != e; ++i) {
6024 const CXXRecordDecl *Base =
6025 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6026 if (i->isVirtual())
6027 continue;
6028 if (Base->getNumVBases() == 0)
6029 continue;
6030 MarkVirtualMembersReferenced(Loc, Base);
6031 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006032}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006033
6034/// SetIvarInitializers - This routine builds initialization ASTs for the
6035/// Objective-C implementation whose ivars need be initialized.
6036void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6037 if (!getLangOptions().CPlusPlus)
6038 return;
6039 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6040 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6041 CollectIvarsToConstructOrDestruct(OID, ivars);
6042 if (ivars.empty())
6043 return;
6044 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6045 for (unsigned i = 0; i < ivars.size(); i++) {
6046 FieldDecl *Field = ivars[i];
6047 CXXBaseOrMemberInitializer *Member;
6048 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6049 InitializationKind InitKind =
6050 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6051
6052 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6053 Sema::OwningExprResult MemberInit =
6054 InitSeq.Perform(*this, InitEntity, InitKind,
6055 Sema::MultiExprArg(*this, 0, 0));
6056 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6057 // Note, MemberInit could actually come back empty if no initialization
6058 // is required (e.g., because it would call a trivial default constructor)
6059 if (!MemberInit.get() || MemberInit.isInvalid())
6060 continue;
6061
6062 Member =
6063 new (Context) CXXBaseOrMemberInitializer(Context,
6064 Field, SourceLocation(),
6065 SourceLocation(),
6066 MemberInit.takeAs<Expr>(),
6067 SourceLocation());
6068 AllToInit.push_back(Member);
6069 }
6070 ObjCImplementation->setIvarInitializers(Context,
6071 AllToInit.data(), AllToInit.size());
6072 }
6073}