blob: 58be7aecf0839ee95076117089a807fcb3992b93 [file] [log] [blame]
Chris Lattner199abbc2008-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 Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000026#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000031#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000032#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner58258242008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattnerb0d38442008-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 Kramer337e3a52009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000050
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 public:
Mike Stump11289f42009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 };
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000067 }
68
Chris Lattnerb0d38442008-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 Gregor5251f1b2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-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 Stump11289f42009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000094 }
Chris Lattner58258242008-04-10 02:22:51 +000095
Douglas Gregor8e12c382008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000098
Douglas Gregor97a9c812008-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 Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108}
109
Anders Carlssonc80a1272009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-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 Carlssonc80a1272009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlssonc80a1272009-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 Gregor85dabae2009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman5f101b92009-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 Carlsson4562f1f2009-08-25 03:18:48 +0000134 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136
Anders Carlsson6e997b22009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000144 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000145}
146
Chris Lattner58258242008-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 Lattner199abbc2008-04-08 05:04:30 +0000150void
Mike Stump11289f42009-09-09 15:08:12 +0000151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner83f095c2009-03-28 19:18:32 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlssonf1c26952009-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 Stump11289f42009-09-09 15:08:12 +0000175
Anders Carlssonc80a1272009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000177}
178
Douglas Gregor58354032008-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 Stump11289f42009-09-09 15:08:12 +0000183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner83f095c2009-03-28 19:18:32 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000192
Anders Carlsson84613c42009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000194}
195
Douglas Gregor4d87df52008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000205
Anders Carlsson84613c42009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207}
208
Douglas Gregorcaa8ace2008-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 Lattner83f095c2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-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 Gregor58354032008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-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 Gregor58354032008-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 Gregorcaa8ace2008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner199abbc2008-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 Gregor75a45ba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-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 Gregorc732aba2009-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 Lattner199abbc2008-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 Gregorc732aba2009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-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 Stump11289f42009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-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 Gregor75a45ba2009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000301 // Merge the old default argument into the new parameter
John McCallf3cd6652010-03-12 18:31:32 +0000302 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000303 if (OldParam->hasUninstantiatedDefaultArg())
304 NewParam->setUninstantiatedDefaultArg(
305 OldParam->getUninstantiatedDefaultArg());
306 else
307 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregorc732aba2009-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 Gregor62e10f02009-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 Gregor3362bde2009-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 Gregor62e10f02009-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 Gregorc732aba2009-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 Lattner199abbc2008-04-08 05:04:30 +0000358 }
359 }
360
Douglas Gregorf40863c2010-02-12 07:32:17 +0000361 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000363
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner199abbc2008-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 Carlsson5a532382009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-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 Stump11289f42009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 else
Mike Stump11289f42009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner199abbc2008-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 Carlsson84613c42009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregor556877c2008-04-13 21:30:24 +0000420
Douglas Gregor61956c42008-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 Kyrtzidis32a03792008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-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 Gregor1aa3edb2010-02-05 06:12:42 +0000436 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump11289f42009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000450 QualType BaseType,
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000484 return 0;
485
Eli Friedmanc96d4962009-08-15 21:55:26 +0000486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000488 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000489 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000493
Alexis Hunt96d5c762009-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 Gregore7488b92009-12-01 16:58:18 +0000497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000499 return 0;
500 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000501
Eli Friedman89c038e2009-12-05 23:03:49 +0000502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-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 Friedman89c038e2009-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 Carlssonae3c5cf2009-12-03 17:49:57 +0000524
Douglas Gregor463421d2009-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 Friedman89c038e2009-12-05 23:03:49 +0000528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000531 Class->setPOD(false);
532
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000533 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-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 Gregor8a273912009-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 Friedmanc96d4962009-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 Carlssonfe63dc52009-04-16 00:08:20 +0000551 } else {
552 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000553 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000554 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000555 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-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 Carlssonae3c5cf2009-12-03 17:49:57 +0000561 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-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 Carlssonae3c5cf2009-12-03 17:49:57 +0000567 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000568 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000569 }
Anders Carlsson6dc35752009-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 Carlssonae3c5cf2009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000575 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000576}
577
Douglas Gregor556877c2008-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 Stump11289f42009-09-09 15:08:12 +0000580/// example:
581/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000582/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000583Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000587 if (!classdecl)
588 return true;
589
Douglas Gregorc40290e2009-03-09 23:48:35 +0000590 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000591 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
592 if (!Class)
593 return true;
594
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000595 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
597 Virtual, Access,
598 BaseType, BaseLoc))
599 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000600
Douglas Gregor463421d2009-03-03 04:44:36 +0000601 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000602}
Douglas Gregor556877c2008-04-13 21:30:24 +0000603
Douglas Gregor463421d2009-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 Gregor29a92472008-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 Gregor9d6290b2008-10-23 18:13:27 +0000613 // that the key is always the unqualified canonical type of the base
614 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000615 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
616
617 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000618 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000619 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000620 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000621 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000622 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000623 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000624
Douglas Gregor29a92472008-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 Gregor463421d2009-03-03 04:44:36 +0000629 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000630 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000631 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000632 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000633
634 // Delete the duplicate base class specifier; we're going to
635 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000636 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000637
638 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000639 } else {
640 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 KnownBaseTypes[NewBaseType] = Bases[idx];
642 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000643 }
644 }
645
646 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000647 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-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 Gregorb77af8f2009-07-22 20:55:49 +0000652 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-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 Stump11289f42009-09-09 15:08:12 +0000660void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000661 unsigned NumBases) {
662 if (!ClassDecl || !Bases || !NumBases)
663 return;
664
665 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000666 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000667 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000668}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000669
John McCalle78aac42010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000684
685 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
686 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000687 return false;
688
John McCalle78aac42010-03-10 03:28:59 +0000689 CXXRecordDecl *BaseRD = GetClassForType(Base);
690 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000691 return false;
692
John McCall67da35c2010-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 Gregor36d1b142009-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 McCalle78aac42010-03-10 03:28:59 +0000703 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
704 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000705 return false;
706
John McCalle78aac42010-03-10 03:28:59 +0000707 CXXRecordDecl *BaseRD = GetClassForType(Base);
708 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000709 return false;
710
Douglas Gregor36d1b142009-10-06 17:59:45 +0000711 return DerivedRD->isDerivedFrom(BaseRD, Paths);
712}
713
Anders Carlssona70cff62010-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 Gregor36d1b142009-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 McCall1064d7e2010-03-16 05:22:47 +0000747 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000748 unsigned AmbigiousBaseConvID,
749 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000750 DeclarationName Name,
751 CXXBaseSpecifierArray *BasePath) {
Douglas Gregor36d1b142009-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 Carlssona70cff62010-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 Carlsson7afe4242010-04-24 17:11:09 +0000774 }
John McCall5b0829a2010-02-10 09:31:12 +0000775 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000776
777 // Build a base path if necessary.
778 if (BasePath)
779 BuildBasePathArray(Paths, *BasePath);
780 return false;
Douglas Gregor36d1b142009-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 Redl7c353682009-11-14 21:15:49 +0000808 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000809 CXXBaseSpecifierArray *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000810 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000811 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000812 IgnoreAccess ? 0
813 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000814 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000815 Loc, Range, DeclarationName(),
816 BasePath);
Douglas Gregor36d1b142009-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 Kyrtzidised983422008-07-01 10:37:29 +0000851//===----------------------------------------------------------------------===//
852// C++ class member Handling
853//===----------------------------------------------------------------------===//
854
Argyrios Kyrtzidised983422008-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 Lattnereb4373d2009-04-12 22:37:57 +0000858/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000859Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000860Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000861 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000862 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
863 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000864 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000865 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +0000870 bool isFunc = D.isFunctionDeclarator();
871
John McCall07e91c02009-08-06 02:15:43 +0000872 assert(!DS.isFriendSpecified());
873
Argyrios Kyrtzidised983422008-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 Redlccdfaba2008-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 Kyrtzidised983422008-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 Redlccdfaba2008-11-14 23:42:31 +0000885 case DeclSpec::SCS_mutable:
886 if (isFunc) {
887 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000888 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000889 else
Chris Lattner3b054132008-11-19 05:08:23 +0000890 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000891
Sebastian Redl8071edb2008-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 Redlccdfaba2008-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 Redl8071edb2008-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 Redlccdfaba2008-11-14 23:42:31 +0000909 D.getMutableDeclSpec().ClearStorageClassSpecs();
910 }
911 }
912 break;
Argyrios Kyrtzidised983422008-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 Kyrtzidis2e3e7562008-10-15 20:23:22 +0000922 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000923 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000924 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000925 // Check also for this case:
926 //
927 // typedef int f();
928 // f a;
929 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000930 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000931 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000932 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000933
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000936 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937
938 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000939 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000940 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000941 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
942 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000943 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000944 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000945 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000946 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000947 if (!Member) {
948 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000949 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000950 }
Chris Lattnerd26760a2009-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 Gregor212cab32009-03-11 20:22:50 +0000956 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-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 Stump11289f42009-09-09 15:08:12 +0000969 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000970 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnerd26760a2009-03-05 23:01:03 +0000973 DeleteExpr(BitWidth);
974 BitWidth = 0;
975 Member->setInvalidDecl();
976 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000977
978 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000979
Douglas Gregor3447e762009-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 Lattner73bf7b42009-03-05 22:45:59 +0000984 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000985
Douglas Gregor92751d42008-11-17 22:58:34 +0000986 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000987
Douglas Gregor0c880302009-03-11 23:00:04 +0000988 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000989 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000990 if (Deleted) // FIXME: Source location is not very good.
991 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000992
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000993 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000994 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000995 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000996 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000997 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998}
999
Douglas Gregor15e77a22009-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 Gregore8381c02008-11-05 04:29:56 +00001045/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001046Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001047Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001048 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001049 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001050 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001051 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001052 SourceLocation IdLoc,
1053 SourceLocation LParenLoc,
1054 ExprTy **Args, unsigned NumArgs,
1055 SourceLocation *CommaLocs,
1056 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001057 if (!ConstructorD)
1058 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001059
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001060 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001061
1062 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001063 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-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 Jahanianc1fc3ec2009-07-01 19:21:19 +00001084 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001085 // Look for a member, first.
1086 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001087 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001088 = ClassDecl->lookup(MemberOrBase);
1089 if (Result.first != Result.second)
1090 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001091
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001092 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001093
Eli Friedman8e1433b2009-07-29 19:44:27 +00001094 if (Member)
1095 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001096 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001097 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001098 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001099 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001100 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001101
1102 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001103 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-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 McCallda6841b2010-04-09 19:01:14 +00001112 // We don't want access-control diagnostics here.
1113 R.suppressDiagnostics();
1114
Douglas Gregora3b624a2010-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 Gregorbbdf20a2010-04-24 15:35:55 +00001124 BaseType = CheckTypenameType(ETK_None,
1125 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora3b624a2010-01-19 06:46:48 +00001126 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001127 if (BaseType.isNull())
1128 return true;
1129
Douglas Gregora3b624a2010-01-19 06:46:48 +00001130 R.clear();
1131 }
1132 }
1133
Douglas Gregor15e77a22009-12-31 09:10:24 +00001134 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001135 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001136 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1137 R.isSingleResult()) {
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001145 << FixItHint::CreateReplacement(R.getNameLoc(),
1146 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001147 Diag(Member->getLocation(), diag::note_previous_decl)
1148 << Member->getDeclName();
Douglas Gregor15e77a22009-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 Gregora771f462010-03-31 17:46:05 +00001164 << FixItHint::CreateReplacement(R.getNameLoc(),
1165 R.getLookupName().getAsString());
Douglas Gregor43a08572010-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 Gregor15e77a22009-12-31 09:10:24 +00001174 TyD = Type;
1175 }
1176 }
1177 }
1178
Douglas Gregora3b624a2010-01-19 06:46:48 +00001179 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-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 McCallb5a0d312009-12-21 10:41:20 +00001184 }
1185
Douglas Gregora3b624a2010-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 McCallb5a0d312009-12-21 10:41:20 +00001191
Douglas Gregora3b624a2010-01-19 06:46:48 +00001192 // FIXME: preserve source range information
1193 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1194 }
John McCallb5a0d312009-12-21 10:41:20 +00001195 }
1196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
John McCallbcd03502009-12-07 02:54:59 +00001198 if (!TInfo)
1199 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001200
John McCallbcd03502009-12-07 02:54:59 +00001201 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001202 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001203}
1204
John McCalle22a04a2009-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 Friedman8e1433b2009-07-29 19:44:27 +00001248Sema::MemInitResult
1249Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1250 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001251 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001252 SourceLocation RParenLoc) {
John McCalle22a04a2009-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 McCallc90f6d72009-11-04 23:13:52 +00001256 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-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 Friedman8e1433b2009-07-29 19:44:27 +00001270 bool HasDependentArg = false;
1271 for (unsigned i = 0; i < NumArgs; i++)
1272 HasDependentArg |= Args[i]->isTypeDependent();
1273
Eli Friedman8e1433b2009-07-29 19:44:27 +00001274 QualType FieldType = Member->getType();
1275 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1276 FieldType = Array->getElementType();
Douglas Gregor7ae2d772010-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 Gregore8381c02008-11-05 04:29:56 +00001296 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001297
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001298 if (Member->isInvalidDecl())
1299 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001300
Douglas Gregor7ae2d772010-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 Gregorc8c44b5d2009-12-02 22:36:29 +00001343 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001344 LParenLoc,
1345 MemberInit.takeAs<Expr>(),
1346 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001347}
1348
1349Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001350Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001351 Expr **Args, unsigned NumArgs,
1352 SourceLocation LParenLoc, SourceLocation RParenLoc,
1353 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001354 bool HasDependentArg = false;
1355 for (unsigned i = 0; i < NumArgs; i++)
1356 HasDependentArg |= Args[i]->isTypeDependent();
1357
John McCallbcd03502009-12-07 02:54:59 +00001358 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-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 Friedman8e1433b2009-07-29 19:44:27 +00001365
Douglas Gregor7ae2d772010-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 Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001373 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001374 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001375 LParenLoc,
1376 BaseInit.takeAs<Expr>(),
1377 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001378 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001379
Douglas Gregor7ae2d772010-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 McCall1e67dd62010-04-27 01:43:38 +00001410 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor7ae2d772010-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 Carlsson43c64af2010-04-21 19:52:01 +00001420 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-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 Carlsson1c0f8bb2010-04-12 00:51:03 +00001455 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001456 LParenLoc,
1457 Init.takeAs<Expr>(),
1458 RParenLoc);
1459 }
1460
1461 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001462 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001463 LParenLoc,
1464 BaseInit.takeAs<Expr>(),
1465 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001466}
1467
Anders Carlsson1b00e242010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001476static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001477BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001478 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001479 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001480 bool IsInheritedVirtualBase,
1481 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001482 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001483 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1484 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001485
Anders Carlsson1b00e242010-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 Carlssoncedc0a42010-04-20 23:11:20 +00001497
Anders Carlsson1b00e242010-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,
Douglas Gregored088b72010-05-03 15:43:53 +00001504 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001505
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001506 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001507 QualType ArgTy =
1508 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1509 ParamType.getQualifiers());
1510 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001511 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson36db0d92010-04-24 22:54:32 +00001512 /*isLvalue=*/true,
1513 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001514
Anders Carlsson1b00e242010-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 Carlssoncedc0a42010-04-20 23:11:20 +00001525
Anders Carlsson1b00e242010-04-23 03:10:23 +00001526 case IIK_Move:
1527 assert(false && "Unhandled initializer kind!");
1528 }
1529
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001530 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1531 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001532 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001533
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001534 CXXBaseInit =
Anders Carlssoncedc0a42010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001543 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001544}
1545
Anders Carlsson3c1db572010-04-23 02:15:47 +00001546static bool
1547BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001548 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001549 FieldDecl *Field,
1550 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlsson423f5d82010-04-23 16:04:08 +00001551 if (ImplicitInitKind == IIK_Copy) {
Anders Carlsson79111502010-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 Carlsson423f5d82010-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 Carlsson1b00e242010-04-23 03:10:23 +00001586 CXXMemberInit = 0;
1587 return false;
1588 }
1589
Anders Carlsson423f5d82010-04-23 16:04:08 +00001590 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1591
Anders Carlsson3c1db572010-04-23 02:15:47 +00001592 QualType FieldBaseElementType =
1593 SemaRef.Context.getBaseElementType(Field->getType());
1594
Anders Carlsson3c1db572010-04-23 02:15:47 +00001595 if (FieldBaseElementType->isRecordType()) {
1596 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001597 InitializationKind InitKind =
1598 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlsson3c1db572010-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 Carlssondca6be02010-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 Carlsson3c1db572010-04-23 02:15:47 +00001636
1637 // Nothing to initialize.
1638 CXXMemberInit = 0;
1639 return false;
1640}
1641
Eli Friedman9cf6b592009-11-09 19:20:36 +00001642bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001643Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001644 CXXBaseOrMemberInitializer **Initializers,
1645 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001646 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001647 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-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 Carlsson1b00e242010-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 Jahanian3501bce2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00001670 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001671 if (!ClassDecl)
1672 return true;
1673
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001674 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1675 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001676 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001678 for (unsigned i = 0; i < NumInitializers; i++) {
1679 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001680
1681 if (Member->isBaseInitializer())
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001682 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001683 else
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001684 AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001685 }
1686
Anders Carlsson43c64af2010-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 Carlssondb0a9652010-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 Carlsson43c64af2010-04-21 19:52:01 +00001703 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001704 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001705 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1706 VBase, IsInheritedVirtualBase,
1707 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001708 HadError = true;
1709 continue;
1710 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001711
Anders Carlssondb0a9652010-04-02 06:26:44 +00001712 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001713 }
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Anders Carlssondb0a9652010-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 Stump11289f42009-09-09 15:08:12 +00001721
Anders Carlssondb0a9652010-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 Carlsson6bd91c32010-04-23 02:00:02 +00001726 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001727 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1728 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001729 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001730 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001731 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001732 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001733
Anders Carlssondb0a9652010-04-02 06:26:44 +00001734 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001735 }
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Fariborz Jahanian3501bce2009-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 Stump11289f42009-09-09 15:08:12 +00001742 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001743 Field->getType()->getAs<RecordType>()) {
1744 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001745 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001746 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-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 Stump11289f42009-09-09 15:08:12 +00001765
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001766 if (AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001767 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001768
Anders Carlsson3c1db572010-04-23 02:15:47 +00001769 CXXBaseOrMemberInitializer *Member;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001770 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1771 *Field, Member)) {
Anders Carlsson3c1db572010-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 Jahanian3501bce2009-09-03 19:36:46 +00001778 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001779 }
Mike Stump11289f42009-09-09 15:08:12 +00001780
Fariborz Jahanian3501bce2009-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 McCalla6309952010-03-16 21:39:52 +00001786 memcpy(baseOrMemberInitializers, AllToInit.data(),
1787 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001788 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001789
John McCalla6309952010-03-16 21:39:52 +00001790 // Constructors implicitly reference the base and member
1791 // destructors.
1792 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1793 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001794 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001795
1796 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001797}
1798
Eli Friedman952c15d2009-07-21 19:28:10 +00001799static void *GetKeyForTopLevelField(FieldDecl *Field) {
1800 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001801 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-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 Carlsson7b3f2782010-04-02 05:42:15 +00001808static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1809 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001810}
1811
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001812static void *GetKeyForMember(ASTContext &Context,
1813 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001814 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001815 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001816 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001817
Eli Friedman952c15d2009-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 Carlssona942dcd2010-03-30 15:39:27 +00001820 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001821
Anders Carlssona942dcd2010-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 Carlsson83ac3122010-03-30 16:19:37 +00001827
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00001830 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-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 Carlsson83ac3122010-03-30 16:19:37 +00001840 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Anders Carlssona942dcd2010-03-30 15:39:27 +00001843 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001844}
1845
Anders Carlssone857b292010-04-02 03:37:03 +00001846static void
1847DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001848 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001849 CXXBaseOrMemberInitializer **Inits,
1850 unsigned NumInits) {
1851 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001852 return;
Mike Stump11289f42009-09-09 15:08:12 +00001853
John McCallbb7b6582010-04-10 07:37:23 +00001854 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1855 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001856 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001857
John McCallbb7b6582010-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 Stump11289f42009-09-09 15:08:12 +00001862
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001863 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1864
John McCallbb7b6582010-04-10 07:37:23 +00001865 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001866 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001867 ClassDecl->vbases_begin(),
1868 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001869 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001870
John McCallbb7b6582010-04-10 07:37:23 +00001871 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001872 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001873 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001874 if (Base->isVirtual())
1875 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001876 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
John McCallbb7b6582010-04-10 07:37:23 +00001879 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1881 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001882 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001883
John McCallbb7b6582010-04-10 07:37:23 +00001884 unsigned NumIdealInits = IdealInitKeys.size();
1885 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00001886
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00001896 break;
John McCallbb7b6582010-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 Carlssone0eebb32009-08-27 05:45:01 +00001921 break;
John McCallbb7b6582010-04-10 07:37:23 +00001922
1923 assert(IdealIndex != NumIdealInits &&
1924 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001925 }
John McCallbb7b6582010-04-10 07:37:23 +00001926
1927 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001928 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001929}
1930
John McCall23eebd92010-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 Carlssone857b292010-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 McCall23eebd92010-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 Carlsson7b3f2782010-04-02 05:42:15 +00002020 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002021
2022 // Mapping for the inconsistent anonymous-union initializers check.
2023 RedundantUnionMap MemberUnions;
2024
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002025 bool HadError = false;
2026 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002027 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002028
John McCall23eebd92010-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 Carlssone857b292010-04-02 03:37:03 +00002038 }
Anders Carlssone857b292010-04-02 03:37:03 +00002039 }
2040
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002041 if (HadError)
2042 return;
2043
Anders Carlssone857b292010-04-02 03:37:03 +00002044 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002045
2046 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002047}
2048
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002049void
John McCalla6309952010-03-16 21:39:52 +00002050Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2051 CXXRecordDecl *ClassDecl) {
2052 // Ignore dependent contexts.
2053 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002054 return;
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002060
Anders Carlssondee9a302009-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 McCall1064d7e2010-03-16 05:22:47 +00002076 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2077 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002078 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002079 << Field->getDeclName()
2080 << FieldType);
2081
John McCalla6309952010-03-16 21:39:52 +00002082 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002083 }
2084
John McCall1064d7e2010-03-16 05:22:47 +00002085 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2086
Anders Carlssondee9a302009-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 McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002094 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002095 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002096
2097 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002098 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002099 if (BaseClassDecl->hasTrivialDestructor())
2100 continue;
John McCall1064d7e2010-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 Gregor89336232010-03-29 23:34:08 +00002106 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002107 << Base->getType()
2108 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002109
John McCalla6309952010-03-16 21:39:52 +00002110 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002111 }
2112
2113 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002114 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2115 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-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 Carlssondee9a302009-11-17 04:44:12 +00002124 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002125 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002126 if (BaseClassDecl->hasTrivialDestructor())
2127 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002128
2129 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2130 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002131 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002132 << VBase->getType());
2133
John McCalla6309952010-03-16 21:39:52 +00002134 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002135 }
2136}
2137
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002138void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002139 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002140 return;
Mike Stump11289f42009-09-09 15:08:12 +00002141
Mike Stump11289f42009-09-09 15:08:12 +00002142 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002143 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002144 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002145}
2146
Mike Stump11289f42009-09-09 15:08:12 +00002147bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002148 unsigned DiagID, AbstractDiagSelID SelID,
2149 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-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 Stump11289f42009-09-09 15:08:12 +00002156}
2157
Anders Carlssoneabf7702009-08-27 00:13:57 +00002158bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2159 const PartialDiagnostic &PD,
2160 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002161 if (!getLangOptions().CPlusPlus)
2162 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002164 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002165 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002166 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002167
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002168 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002169 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002170 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002171 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002172
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002173 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002174 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002175 }
Mike Stump11289f42009-09-09 15:08:12 +00002176
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002177 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002178 if (!RT)
2179 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002180
John McCall67da35c2010-02-04 22:26:26 +00002181 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002182
Anders Carlssonb57738b2009-03-24 17:23:42 +00002183 if (CurrentRD && CurrentRD != RD)
2184 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002185
John McCall67da35c2010-02-04 22:26:26 +00002186 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002187 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002188 return false;
2189
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002190 if (!RD->isAbstract())
2191 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002192
Anders Carlssoneabf7702009-08-27 00:13:57 +00002193 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002194
Anders Carlsson576cc6f2009-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 Stump11289f42009-09-09 15:08:12 +00002199
Douglas Gregor4165bd62010-03-23 23:47:56 +00002200 CXXFinalOverriderMap FinalOverriders;
2201 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002202
Douglas Gregor4165bd62010-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 Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregor4165bd62010-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 Carlsson576cc6f2009-03-22 20:18:17 +00002226 }
2227
2228 if (!PureVirtualClassDiagSet)
2229 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2230 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002231
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002232 return true;
2233}
2234
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002235namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002236 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002237 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2238 Sema &SemaRef;
2239 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002240
Anders Carlssonb57738b2009-03-24 17:23:42 +00002241 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002242 bool Invalid = false;
2243
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002244 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2245 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002246 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002247
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002248 return Invalid;
2249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Anders Carlssonb57738b2009-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 Carlssonb5a27b42009-03-24 01:19:16 +00002256
Anders Carlssonb57738b2009-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 Stump11289f42009-09-09 15:08:12 +00002261 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002262 return VisitDeclContext(FD);
2263 }
Mike Stump11289f42009-09-09 15:08:12 +00002264
Anders Carlssonb57738b2009-03-24 17:23:42 +00002265 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002266 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002267 bool Invalid =
Anders Carlssonb57738b2009-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 Stump11289f42009-09-09 15:08:12 +00002273 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002274 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002275 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002276 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002277 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002278 VD->getOriginalType(),
2279 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002280 Sema::AbstractParamType,
2281 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002282 }
2283
2284 return Invalid;
2285 }
Mike Stump11289f42009-09-09 15:08:12 +00002286
Anders Carlssonb57738b2009-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 Stump11289f42009-09-09 15:08:12 +00002290
Anders Carlssonb57738b2009-03-24 17:23:42 +00002291 return false;
2292 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002293 };
2294}
2295
Douglas Gregorc99f1552009-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 Gregorb93b6062010-04-12 17:09:20 +00002299void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002300 if (!Record || Record->isInvalidDecl())
2301 return;
2302
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002303 if (!Record->isDependentType())
Douglas Gregorb93b6062010-04-12 17:09:20 +00002304 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002305
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002306 if (Record->isInvalidDecl())
2307 return;
2308
John McCall2cb94162010-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 Gregor4165bd62010-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 Gregorc99f1552009-12-03 18:33:45 +00002336 }
2337
Douglas Gregor4165bd62010-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 Gregorc99f1552009-12-03 18:33:45 +00002379 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-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 Kramer659d7fc2010-04-16 17:43:15 +00002391 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-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 Gregorc99f1552009-12-03 18:33:45 +00002404}
2405
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002406void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002407 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002408 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002409 SourceLocation RBrac,
2410 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002411 if (!TagDecl)
2412 return;
Mike Stump11289f42009-09-09 15:08:12 +00002413
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002414 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002415
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002416 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002417 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002418 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002419
Douglas Gregorb93b6062010-04-12 17:09:20 +00002420 CheckCompletedCXXClass(S,
Douglas Gregorc99f1552009-12-03 18:33:45 +00002421 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002422}
2423
Douglas Gregor05379422008-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 Gregorb93b6062010-04-12 17:09:20 +00002429///
2430/// The scope, if provided, is the class scope.
2431void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2432 CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002433 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002434 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002435
Sebastian Redl5068f77ac2009-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 Gregor05379422008-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 Stump11289f42009-09-09 15:08:12 +00002446 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002447 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002448 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002449 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002450 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002451 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002452 0, 0, false, 0,
2453 /*FIXME*/false, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002454 0, 0,
2455 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002456 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002457 /*isExplicit=*/false,
2458 /*isInline=*/true,
2459 /*isImplicitlyDeclared=*/true);
2460 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002461 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002462 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002463 if (S)
2464 PushOnScopeChains(DefaultCon, S, true);
2465 else
2466 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-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 Kremenekc23c7e62009-07-29 21:53:49 +00002489 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002490 HasConstCopyConstructor
Douglas Gregor05379422008-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 Kyrtzidiscfbfe782009-06-30 02:36:12 +00002498 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2499 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002500 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002501 QualType FieldType = (*Field)->getType();
2502 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2503 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002504 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002505 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002506 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002507 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002508 = FieldClassDecl->hasConstCopyConstructor(Context);
2509 }
2510 }
2511
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002512 // Otherwise, the implicitly declared copy constructor will have
2513 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002514 //
2515 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002516 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002517 if (HasConstCopyConstructor)
2518 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002519 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002520
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002521 // An implicitly-declared copy constructor is an inline public
2522 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002523 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002524 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002525 CXXConstructorDecl *CopyConstructor
2526 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002527 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002528 Context.getFunctionType(Context.VoidTy,
2529 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002530 false, 0,
2531 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002532 false, 0, 0,
2533 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002534 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002535 /*isExplicit=*/false,
2536 /*isInline=*/true,
2537 /*isImplicitlyDeclared=*/true);
2538 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002539 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002540 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-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 McCallbcd03502009-12-07 02:54:59 +00002546 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002547 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002548 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002549 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregorb93b6062010-04-12 17:09:20 +00002550 if (S)
2551 PushOnScopeChains(CopyConstructor, S, true);
2552 else
2553 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002554 }
2555
Sebastian Redlbaad4e72009-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 Redl1054fae2009-10-25 17:03:50 +00002578 assert(!Base->getType()->isDependentType() &&
2579 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002580 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002581 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002582 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002583 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002584 MD);
Sebastian Redlbaad4e72009-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 Kyrtzidiscfbfe782009-06-30 02:36:12 +00002591 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2592 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002593 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002594 QualType FieldType = (*Field)->getType();
2595 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2596 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002597 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002598 const CXXRecordDecl *FieldClassDecl
2599 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002600 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002601 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002602 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-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 Redl0f8b23f2009-03-16 23:22:08 +00002611 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002612 if (HasConstCopyAssignment)
2613 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002614 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-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 Gregor36c569f2010-02-21 22:15:06 +00002623 false, 0,
2624 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002625 false, 0, 0,
2626 FunctionType::ExtInfo()),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002627 /*TInfo=*/0, /*isStatic=*/false,
2628 /*StorageClassAsWritten=*/FunctionDecl::None,
2629 /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002630 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002631 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002632 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002633 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002634
2635 // Add the parameter to the operator.
2636 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2637 ClassDecl->getLocation(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00002638 /*Id=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002639 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002640 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002641 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002642 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-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 Gregorb93b6062010-04-12 17:09:20 +00002646 if (S)
2647 PushOnScopeChains(CopyAssignment, S, true);
2648 else
2649 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002650 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002651 }
2652
Douglas Gregor1349b452008-12-15 21:24:18 +00002653 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-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 McCall58f10c32010-03-11 09:03:00 +00002658 QualType Ty = Context.getFunctionType(Context.VoidTy,
2659 0, 0, false, 0,
2660 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002661 false, 0, 0, FunctionType::ExtInfo());
John McCall58f10c32010-03-11 09:03:00 +00002662
Mike Stump11289f42009-09-09 15:08:12 +00002663 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002664 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002665 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002666 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002667 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002668 /*isInline=*/true,
2669 /*isImplicitlyDeclared=*/true);
2670 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002671 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002672 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002673 if (S)
2674 PushOnScopeChains(Destructor, S, true);
2675 else
2676 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002677
2678 // This could be uniqued if it ever proves significant.
2679 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002680
2681 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002682 }
Douglas Gregor05379422008-11-03 17:51:48 +00002683}
2684
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002685void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-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 Gregore44a2ad2009-05-27 23:11:45 +00002697 return;
2698
Douglas Gregore44a2ad2009-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 McCall6df5fef2009-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 Gregor4d87df52008-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 Lattner83f095c2009-03-28 19:18:32 +00002730void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-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 Lattner83f095c2009-03-28 19:18:32 +00002738void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002739 if (!ParamD)
2740 return;
Mike Stump11289f42009-09-09 15:08:12 +00002741
Chris Lattner83f095c2009-03-28 19:18:32 +00002742 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-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 Lattner83f095c2009-03-28 19:18:32 +00002749 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-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 Lattner83f095c2009-03-28 19:18:32 +00002760void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002761 if (!MethodD)
2762 return;
Mike Stump11289f42009-09-09 15:08:12 +00002763
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002764 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002765
Chris Lattner83f095c2009-03-28 19:18:32 +00002766 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-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 Lattnerb41df4f2009-04-25 08:35:12 +00002772 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2773 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-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 Gregor831c93f2008-11-05 20:51:48 +00002780/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002781/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002782/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-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 Gregor831c93f2008-11-05 20:51:48 +00002788 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-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 Lattner38378bf2009-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 Gregor831c93f2008-11-05 20:51:48 +00002801 }
2802 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-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 Gregor831c93f2008-11-05 20:51:48 +00002808 SC = FunctionDecl::None;
2809 }
Mike Stump11289f42009-09-09 15:08:12 +00002810
Chris Lattner38378bf2009-04-25 08:28:21 +00002811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2812 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002813 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002814 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2815 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002816 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002817 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2818 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002819 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002820 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2821 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Douglas Gregor831c93f2008-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 McCall9dd450b2009-09-21 23:43:11 +00002829 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002830 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2831 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002832 Proto->isVariadic(), 0,
2833 Proto->hasExceptionSpec(),
2834 Proto->hasAnyExceptionSpec(),
2835 Proto->getNumExceptions(),
2836 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002837 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002838}
2839
Douglas Gregor4d87df52008-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 Lattnerb41df4f2009-04-25 08:35:12 +00002843void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002844 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002845 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2846 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002847 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-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 Gregorf4d17c42009-03-27 04:38:56 +00002854 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002855 ((Constructor->getNumParams() == 1) ||
2856 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002857 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2858 Constructor->getTemplateSpecializationKind()
2859 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-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 Gregor170512f2009-04-01 23:51:29 +00002863 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2864 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregora771f462010-03-31 17:46:05 +00002865 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002866
2867 // FIXME: Rather that making the constructor invalid, we should endeavor
2868 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002869 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002870 }
2871 }
Mike Stump11289f42009-09-09 15:08:12 +00002872
John McCall43314ab2010-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 Gregor4d87df52008-12-16 21:30:33 +00002879}
2880
Anders Carlsson26a807d2009-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 Carlssonf98849e2009-12-02 17:15:43 +00002883bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-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 Carlssonf98849e2009-12-02 17:15:43 +00002898 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002899 return true;
2900
2901 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002902 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002903
2904 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907static inline bool
Anders Carlsson5e965472009-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 Gregor831c93f2008-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 Lattner38378bf2009-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 Gregor831c93f2008-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 Gregor7861a802009-11-03 01:35:08 +00002927 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002928 if (isa<TypedefType>(DeclaratorType)) {
2929 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002930 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002931 D.setInvalidType();
Douglas Gregor831c93f2008-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 Lattner38378bf2009-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 Gregor831c93f2008-11-05 20:51:48 +00002947 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002948 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002949 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002950 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-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 Lattner3b054132008-11-19 05:08:23 +00002959 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2960 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2961 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Chris Lattner38378bf2009-04-25 08:28:21 +00002964 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2965 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002966 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002967 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2968 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002969 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002970 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2971 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002972 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002973 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2974 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002975 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002976 }
2977
2978 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002979 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002980 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2981
2982 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002983 FTI.freeArgs();
2984 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002985 }
2986
Mike Stump11289f42009-09-09 15:08:12 +00002987 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002988 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002989 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002990 D.setInvalidType();
2991 }
Douglas Gregor831c93f2008-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 Gregor36c569f2010-02-21 22:15:06 +00002998 // FIXME: Exceptions!
2999 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003000 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003001}
3002
Douglas Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003009void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003010 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003011 // C++ [class.conv.fct]p1:
3012 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003013 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003014 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003015 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-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 Gregordbc5daf2008-11-07 20:08:42 +00003021 SC = FunctionDecl::None;
3022 }
John McCall212fa2e2010-04-13 00:04:31 +00003023
3024 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3025
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003026 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-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 Lattner3b054132008-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 McCall212fa2e2010-04-13 00:04:31 +00003038 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003039 }
3040
John McCall212fa2e2010-04-13 00:04:31 +00003041 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3042
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003043 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003044 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003045 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3046
3047 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003048 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003049 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003050 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003051 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003052 D.setInvalidType();
3053 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003054
John McCall212fa2e2010-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 Gregordbc5daf2008-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 Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003070 D.setInvalidType();
Douglas Gregordbc5daf2008-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 Lattnerb41df4f2009-04-25 08:35:12 +00003074 D.setInvalidType();
Douglas Gregordbc5daf2008-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 Stump11289f42009-09-09 15:08:12 +00003079 // return type.
John McCall212fa2e2010-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 Gregordbc5daf2008-11-07 20:08:42 +00003089
Douglas Gregor5fb53972009-01-14 15:45:31 +00003090 // C++0x explicit conversion operators.
3091 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003092 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003093 diag::warn_explicit_conversion_functions)
3094 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003095}
3096
Douglas Gregordbc5daf2008-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 Lattner83f095c2009-03-28 19:18:32 +00003101Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003102 assert(Conversion && "Expected to receive a conversion function declaration");
3103
Douglas Gregor4287b372008-12-12 08:25:50 +00003104 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105
3106 // Make sure we aren't redeclaring the conversion function.
3107 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-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 Stump87c57ac2009-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 Stump11289f42009-09-09 15:08:12 +00003117 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003118 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003119 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003120 ConvType = ConvTypeRef->getPointeeType();
3121 if (ConvType->isRecordType()) {
3122 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3123 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003124 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003125 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003126 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003127 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003128 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003129 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003130 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003131 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003132 }
3133
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003134 if (Conversion->getPrimaryTemplate()) {
3135 // ignore specializations
3136 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003137 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-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 McCalld14a8642009-11-21 08:51:07 +00003145 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003146 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003147 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003148 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003149 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003150 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003151 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003152
Chris Lattner83f095c2009-03-28 19:18:32 +00003153 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003154}
3155
Argyrios Kyrtzidis08114892008-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 Lattner83f095c2009-03-28 19:18:32 +00003162Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3163 SourceLocation IdentLoc,
3164 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003165 SourceLocation LBrace,
3166 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-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 Carlssona7bcade2010-02-07 01:09:23 +00003173 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3174
Argyrios Kyrtzidis08114892008-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 McCall9f3059a2009-10-09 21:13:30 +00003183 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003184 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003185 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003186
Douglas Gregor91f84212008-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 Kyrtzidis08114892008-04-27 13:50:30 +00003193
Mike Stump11289f42009-09-09 15:08:12 +00003194 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003195 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003196 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003197 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003198 }
Douglas Gregor91f84212008-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 Gregor87f54062009-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 Stump11289f42009-09-09 15:08:12 +00003221 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003222
3223 PushOnScopeChains(Namespc, DeclRegionScope);
3224 } else {
John McCall4fa53422009-10-01 00:25:31 +00003225 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003226 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-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 McCall4fa53422009-10-01 00:25:31 +00003247
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003248 CurContext->addDecl(Namespc);
3249
John McCall4fa53422009-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 McCall0db42252009-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 Kyrtzidis08114892008-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 Stump87c57ac2009-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 Gregor91f84212008-12-11 16:49:14 +00003286 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003287 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003288}
3289
Sebastian Redla6602e92009-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 Kyrtzidis08114892008-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 Lattner83f095c2009-03-28 19:18:32 +00003300void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3301 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-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 Kyrtzidis9a1191c2008-10-06 17:10:33 +00003307
Chris Lattner83f095c2009-03-28 19:18:32 +00003308Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3309 SourceLocation UsingLoc,
3310 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003311 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003312 SourceLocation IdentLoc,
3313 IdentifierInfo *NamespcName,
3314 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003315 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3316 assert(NamespcName && "Invalid NamespcName.");
3317 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003318 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003319
Douglas Gregor889ceb72009-02-03 19:21:40 +00003320 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003321
Douglas Gregor34074322009-01-14 22:20:51 +00003322 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003323 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3324 LookupParsedName(R, S, &SS);
3325 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003326 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003327
John McCall9f3059a2009-10-09 21:13:30 +00003328 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003329 NamedDecl *Named = R.getFoundDecl();
3330 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3331 && "expected namespace decl");
Douglas Gregor889ceb72009-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 Friedman44b83ee2009-08-05 19:21:58 +00003339 // namespace. [Note: in this context, "contains" means "contains
3340 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003341
3342 // Find enclosing context containing both using-directive and
3343 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003344 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003345 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3346 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3347 CommonAncestor = CommonAncestor->getParent();
3348
Sebastian Redla6602e92009-11-23 15:34:23 +00003349 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003350 SS.getRange(),
3351 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003352 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003353 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003354 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003355 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003356 }
3357
Douglas Gregor889ceb72009-02-03 19:21:40 +00003358 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003359 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003360 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-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 Kyrtzidiscfbfe782009-06-30 02:36:12 +00003368 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-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 Lattner83f095c2009-03-28 19:18:32 +00003372 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003373}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003374
Douglas Gregorfec52632009-06-20 00:51:54 +00003375
3376Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003377 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003378 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003379 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003380 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003381 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003382 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003383 bool IsTypeName,
3384 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003385 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003386
Douglas Gregor220f4272009-11-04 16:30:06 +00003387 switch (Name.getKind()) {
3388 case UnqualifiedId::IK_Identifier:
3389 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003390 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003391 case UnqualifiedId::IK_ConversionFunctionId:
3392 break;
3393
3394 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003395 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003396 // C++0x inherited constructors.
3397 if (getLangOptions().CPlusPlus0x) break;
3398
Douglas Gregor220f4272009-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 McCall3969e302009-12-08 07:46:18 +00003415 if (!TargetName)
3416 return DeclPtrTy();
3417
John McCalla0097262009-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 Gregora771f462010-03-31 17:46:05 +00003426 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003427 }
3428
John McCall3f746822009-11-17 05:59:44 +00003429 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003430 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003431 TargetName, AttrList,
3432 /* IsInstantiation */ false,
3433 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003434 if (UD)
3435 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003436
Anders Carlsson696a3f12009-08-28 05:40:36 +00003437 return DeclPtrTy::make(UD);
3438}
3439
John McCall84d87672009-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 McCalla17e83e2009-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 McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003525 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003542 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003557 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003566 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-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 McCall3f746822009-11-17 05:59:44 +00003572/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003573UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003574 UsingDecl *UD,
3575 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003576
3577 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-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 McCall3f746822009-11-17 05:59:44 +00003582 }
3583
3584 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003585 = UsingShadowDecl::Create(Context, CurContext,
3586 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003587 UD->addShadowDecl(Shadow);
3588
3589 if (S)
John McCall3969e302009-12-08 07:46:18 +00003590 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003591 else
John McCall3969e302009-12-08 07:46:18 +00003592 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003593 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003594
John McCallda4458e2010-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 McCall3969e302009-12-08 07:46:18 +00003600 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3601 Shadow->setInvalidDecl();
3602
John McCall84d87672009-12-10 09:41:52 +00003603 return Shadow;
3604}
John McCall3969e302009-12-08 07:46:18 +00003605
John McCall84d87672009-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 McCallda4458e2010-03-31 01:36:47 +00003634 if (Shadow->getDeclName().getNameKind() ==
3635 DeclarationName::CXXConversionFunctionName)
3636 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3637
John McCall84d87672009-12-10 09:41:52 +00003638 // Remove it from the DeclContext...
3639 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003640
John McCall84d87672009-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 McCall3969e302009-12-08 07:46:18 +00003645 }
3646
John McCall84d87672009-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 McCallda4458e2010-03-31 01:36:47 +00003651 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003652}
3653
John McCalle61f2ba2009-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 McCall3f746822009-11-17 05:59:44 +00003659NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3660 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003661 CXXScopeSpec &SS,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003662 SourceLocation IdentLoc,
3663 DeclarationName Name,
3664 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003665 bool IsInstantiation,
3666 bool IsTypeName,
3667 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003668 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3669 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003670
Anders Carlssonf038fc22009-08-28 05:49:21 +00003671 // FIXME: We ignore attributes for now.
3672 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003673
Anders Carlsson59140b32009-08-28 03:16:11 +00003674 if (SS.isEmpty()) {
3675 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003676 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003677 }
Mike Stump11289f42009-09-09 15:08:12 +00003678
John McCall84d87672009-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 Stump11289f42009-09-09 15:08:12 +00003700 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003701 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3702
John McCall84d87672009-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 McCallb96ec562009-12-04 22:46:56 +00003708 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3709 return 0;
3710
John McCall84c16cf2009-11-12 03:15:40 +00003711 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003712 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003713 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003714 if (IsTypeName) {
John McCallb96ec562009-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 McCalle61f2ba2009-11-18 02:36:19 +00003719 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003720 } else {
3721 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3722 UsingLoc, SS.getRange(), NNS,
3723 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003724 }
John McCallb96ec562009-12-04 22:46:56 +00003725 } else {
3726 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3727 SS.getRange(), UsingLoc, NNS, Name,
3728 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003729 }
John McCallb96ec562009-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 Stump11289f42009-09-09 15:08:12 +00003735
John McCall0b66eb32010-05-01 00:40:08 +00003736 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003737 UD->setInvalidDecl();
3738 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003739 }
3740
John McCall3969e302009-12-08 07:46:18 +00003741 // Look up the target name.
3742
John McCall27b18f82009-11-17 02:14:36 +00003743 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003744
John McCall3969e302009-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 McCalle61f2ba2009-11-18 02:36:19 +00003749 if (!IsInstantiation)
3750 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003751
John McCall27b18f82009-11-17 02:14:36 +00003752 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003753
John McCall9f3059a2009-10-09 21:13:30 +00003754 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003755 Diag(IdentLoc, diag::err_no_member)
3756 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003757 UD->setInvalidDecl();
3758 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003759 }
3760
John McCallb96ec562009-12-04 22:46:56 +00003761 if (R.isAmbiguous()) {
3762 UD->setInvalidDecl();
3763 return UD;
3764 }
Mike Stump11289f42009-09-09 15:08:12 +00003765
John McCalle61f2ba2009-11-18 02:36:19 +00003766 if (IsTypeName) {
3767 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003768 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003773 UD->setInvalidDecl();
3774 return UD;
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003780 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-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 McCallb96ec562009-12-04 22:46:56 +00003783 UD->setInvalidDecl();
3784 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003785 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003786 }
3787
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003788 // C++0x N2914 [namespace.udecl]p6:
3789 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003790 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003791 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3792 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003793 UD->setInvalidDecl();
3794 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
John McCall84d87672009-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 McCall3f746822009-11-17 05:59:44 +00003801
3802 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003803}
3804
John McCall84d87672009-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 McCalle29c5cd2009-12-10 19:51:03 +00003855 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003856 return true;
3857 }
3858
3859 return false;
3860}
3861
John McCall3969e302009-12-08 07:46:18 +00003862
John McCallb96ec562009-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 McCall3969e302009-12-08 07:46:18 +00003869 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003870
John McCall3969e302009-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 McCallb96ec562009-12-04 22:46:56 +00003992}
3993
Mike Stump11289f42009-09-09 15:08:12 +00003994Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003995 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003996 SourceLocation AliasLoc,
3997 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003998 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003999 SourceLocation IdentLoc,
4000 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004001
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004002 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004003 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4004 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004005
Anders Carlssondca83c42009-03-28 06:23:46 +00004006 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004007 NamedDecl *PrevDecl
4008 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4009 ForRedeclaration);
4010 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4011 PrevDecl = 0;
4012
4013 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004014 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004015 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004016 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004017 // FIXME: At some point, we'll want to create the (redundant)
4018 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004019 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004020 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004021 return DeclPtrTy();
4022 }
Mike Stump11289f42009-09-09 15:08:12 +00004023
Anders Carlssondca83c42009-03-28 06:23:46 +00004024 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4025 diag::err_redefinition_different_kind;
4026 Diag(AliasLoc, DiagID) << Alias;
4027 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004028 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004029 }
4030
John McCall27b18f82009-11-17 02:14:36 +00004031 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004032 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004033
John McCall9f3059a2009-10-09 21:13:30 +00004034 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00004035 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004036 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00004037 }
Mike Stump11289f42009-09-09 15:08:12 +00004038
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004039 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004040 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4041 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004042 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004043 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004044
John McCalld8d0d432010-02-16 06:53:13 +00004045 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004046 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004047}
4048
Douglas Gregora57478e2010-05-01 15:04:51 +00004049namespace {
4050 /// \brief Scoped object used to handle the state changes required in Sema
4051 /// to implicitly define the body of a C++ member function;
4052 class ImplicitlyDefinedFunctionScope {
4053 Sema &S;
4054 DeclContext *PreviousContext;
4055
4056 public:
4057 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4058 : S(S), PreviousContext(S.CurContext)
4059 {
4060 S.CurContext = Method;
4061 S.PushFunctionScope();
4062 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4063 }
4064
4065 ~ImplicitlyDefinedFunctionScope() {
4066 S.PopExpressionEvaluationContext();
4067 S.PopFunctionOrBlockScope();
4068 S.CurContext = PreviousContext;
4069 }
4070 };
4071}
4072
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004073void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4074 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004075 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4076 !Constructor->isUsed()) &&
4077 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004078
Anders Carlsson423f5d82010-04-23 16:04:08 +00004079 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004080 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004081
Douglas Gregora57478e2010-05-01 15:04:51 +00004082 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004083 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004084 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004085 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004086 Constructor->setInvalidDecl();
4087 } else {
4088 Constructor->setUsed();
4089 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004090}
4091
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004092void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004093 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004094 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4095 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004096 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004097 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004098
Douglas Gregora57478e2010-05-01 15:04:51 +00004099 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004100
John McCalla6309952010-03-16 21:39:52 +00004101 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4102 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004103
Anders Carlsson26a807d2009-11-30 21:24:50 +00004104 // FIXME: If CheckDestructor fails, we should emit a note about where the
4105 // implicit destructor was needed.
4106 if (CheckDestructor(Destructor)) {
4107 Diag(CurrentLocation, diag::note_member_synthesized_at)
4108 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4109
4110 Destructor->setInvalidDecl();
4111 return;
4112 }
4113
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004114 Destructor->setUsed();
4115}
4116
Douglas Gregorb139cd52010-05-01 20:49:11 +00004117/// \brief Builds a statement that copies the given entity from \p From to
4118/// \c To.
4119///
4120/// This routine is used to copy the members of a class with an
4121/// implicitly-declared copy assignment operator. When the entities being
4122/// copied are arrays, this routine builds for loops to copy them.
4123///
4124/// \param S The Sema object used for type-checking.
4125///
4126/// \param Loc The location where the implicit copy is being generated.
4127///
4128/// \param T The type of the expressions being copied. Both expressions must
4129/// have this type.
4130///
4131/// \param To The expression we are copying to.
4132///
4133/// \param From The expression we are copying from.
4134///
4135/// \param Depth Internal parameter recording the depth of the recursion.
4136///
4137/// \returns A statement or a loop that copies the expressions.
4138static Sema::OwningStmtResult
4139BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4140 Sema::OwningExprResult To, Sema::OwningExprResult From,
4141 unsigned Depth = 0) {
4142 typedef Sema::OwningStmtResult OwningStmtResult;
4143 typedef Sema::OwningExprResult OwningExprResult;
4144
4145 // C++0x [class.copy]p30:
4146 // Each subobject is assigned in the manner appropriate to its type:
4147 //
4148 // - if the subobject is of class type, the copy assignment operator
4149 // for the class is used (as if by explicit qualification; that is,
4150 // ignoring any possible virtual overriding functions in more derived
4151 // classes);
4152 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4153 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4154
4155 // Look for operator=.
4156 DeclarationName Name
4157 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4158 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4159 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4160
4161 // Filter out any result that isn't a copy-assignment operator.
4162 LookupResult::Filter F = OpLookup.makeFilter();
4163 while (F.hasNext()) {
4164 NamedDecl *D = F.next();
4165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4166 if (Method->isCopyAssignmentOperator())
4167 continue;
4168
4169 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004170 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004171 F.done();
4172
4173 // Create the nested-name-specifier that will be used to qualify the
4174 // reference to operator=; this is required to suppress the virtual
4175 // call mechanism.
4176 CXXScopeSpec SS;
4177 SS.setRange(Loc);
4178 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4179 T.getTypePtr()));
4180
4181 // Create the reference to operator=.
4182 OwningExprResult OpEqualRef
4183 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4184 /*FirstQualifierInScope=*/0, OpLookup,
4185 /*TemplateArgs=*/0,
4186 /*SuppressQualifierCheck=*/true);
4187 if (OpEqualRef.isInvalid())
4188 return S.StmtError();
4189
4190 // Build the call to the assignment operator.
4191 Expr *FromE = From.takeAs<Expr>();
4192 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4193 OpEqualRef.takeAs<Expr>(),
4194 Loc, &FromE, 1, 0, Loc);
4195 if (Call.isInvalid())
4196 return S.StmtError();
4197
4198 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004199 }
John McCallab8c2732010-03-16 06:11:48 +00004200
Douglas Gregorb139cd52010-05-01 20:49:11 +00004201 // - if the subobject is of scalar type, the built-in assignment
4202 // operator is used.
4203 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4204 if (!ArrayTy) {
4205 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4206 BinaryOperator::Assign,
4207 To.takeAs<Expr>(),
4208 From.takeAs<Expr>());
4209 if (Assignment.isInvalid())
4210 return S.StmtError();
4211
4212 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004213 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004214
4215 // - if the subobject is an array, each element is assigned, in the
4216 // manner appropriate to the element type;
4217
4218 // Construct a loop over the array bounds, e.g.,
4219 //
4220 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4221 //
4222 // that will copy each of the array elements.
4223 QualType SizeType = S.Context.getSizeType();
4224
4225 // Create the iteration variable.
4226 IdentifierInfo *IterationVarName = 0;
4227 {
4228 llvm::SmallString<8> Str;
4229 llvm::raw_svector_ostream OS(Str);
4230 OS << "__i" << Depth;
4231 IterationVarName = &S.Context.Idents.get(OS.str());
4232 }
4233 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4234 IterationVarName, SizeType,
4235 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4236 VarDecl::None, VarDecl::None);
4237
4238 // Initialize the iteration variable to zero.
4239 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4240 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4241
4242 // Create a reference to the iteration variable; we'll use this several
4243 // times throughout.
4244 Expr *IterationVarRef
4245 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4246 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4247
4248 // Create the DeclStmt that holds the iteration variable.
4249 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4250
4251 // Create the comparison against the array bound.
4252 llvm::APInt Upper = ArrayTy->getSize();
4253 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4254 OwningExprResult Comparison
4255 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4256 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4257 BinaryOperator::NE, S.Context.BoolTy, Loc));
4258
4259 // Create the pre-increment of the iteration variable.
4260 OwningExprResult Increment
4261 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4262 UnaryOperator::PreInc,
4263 SizeType, Loc));
4264
4265 // Subscript the "from" and "to" expressions with the iteration variable.
4266 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4267 S.Owned(IterationVarRef->Retain()),
4268 Loc);
4269 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4270 S.Owned(IterationVarRef->Retain()),
4271 Loc);
4272 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4273 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4274
4275 // Build the copy for an individual element of the array.
4276 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4277 ArrayTy->getElementType(),
4278 move(To), move(From), Depth+1);
4279 if (Copy.isInvalid()) {
4280 InitStmt->Destroy(S.Context);
4281 return S.StmtError();
4282 }
4283
4284 // Construct the loop that copies all elements of this array.
4285 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4286 S.MakeFullExpr(Comparison),
4287 Sema::DeclPtrTy(),
4288 S.MakeFullExpr(Increment),
4289 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004290}
4291
Douglas Gregorb139cd52010-05-01 20:49:11 +00004292void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4293 CXXMethodDecl *CopyAssignOperator) {
4294 assert((CopyAssignOperator->isImplicit() &&
4295 CopyAssignOperator->isOverloadedOperator() &&
4296 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4297 !CopyAssignOperator->isUsed()) &&
4298 "DefineImplicitCopyAssignment called for wrong function");
4299
4300 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4301
4302 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4303 CopyAssignOperator->setInvalidDecl();
4304 return;
4305 }
4306
4307 CopyAssignOperator->setUsed();
4308
4309 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4310
4311 // C++0x [class.copy]p30:
4312 // The implicitly-defined or explicitly-defaulted copy assignment operator
4313 // for a non-union class X performs memberwise copy assignment of its
4314 // subobjects. The direct base classes of X are assigned first, in the
4315 // order of their declaration in the base-specifier-list, and then the
4316 // immediate non-static data members of X are assigned, in the order in
4317 // which they were declared in the class definition.
4318
4319 // The statements that form the synthesized function body.
4320 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4321
4322 // The parameter for the "other" object, which we are copying from.
4323 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4324 Qualifiers OtherQuals = Other->getType().getQualifiers();
4325 QualType OtherRefType = Other->getType();
4326 if (const LValueReferenceType *OtherRef
4327 = OtherRefType->getAs<LValueReferenceType>()) {
4328 OtherRefType = OtherRef->getPointeeType();
4329 OtherQuals = OtherRefType.getQualifiers();
4330 }
4331
4332 // Our location for everything implicitly-generated.
4333 SourceLocation Loc = CopyAssignOperator->getLocation();
4334
4335 // Construct a reference to the "other" object. We'll be using this
4336 // throughout the generated ASTs.
4337 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4338 assert(OtherRef && "Reference to parameter cannot fail!");
4339
4340 // Construct the "this" pointer. We'll be using this throughout the generated
4341 // ASTs.
4342 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4343 assert(This && "Reference to this cannot fail!");
4344
4345 // Assign base classes.
4346 bool Invalid = false;
4347 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4348 E = ClassDecl->bases_end(); Base != E; ++Base) {
4349 // Form the assignment:
4350 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4351 QualType BaseType = Base->getType().getUnqualifiedType();
4352 CXXRecordDecl *BaseClassDecl = 0;
4353 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4354 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4355 else {
4356 Invalid = true;
4357 continue;
4358 }
4359
4360 // Construct the "from" expression, which is an implicit cast to the
4361 // appropriately-qualified base type.
4362 Expr *From = OtherRef->Retain();
4363 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4364 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4365 CXXBaseSpecifierArray(Base));
4366
4367 // Dereference "this".
4368 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4369 Owned(This->Retain()));
4370
4371 // Implicitly cast "this" to the appropriately-qualified base type.
4372 Expr *ToE = To.takeAs<Expr>();
4373 ImpCastExprToType(ToE,
4374 Context.getCVRQualifiedType(BaseType,
4375 CopyAssignOperator->getTypeQualifiers()),
4376 CastExpr::CK_UncheckedDerivedToBase,
4377 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4378 To = Owned(ToE);
4379
4380 // Build the copy.
4381 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
4382 move(To), Owned(From));
4383 if (Copy.isInvalid()) {
4384 Invalid = true;
4385 continue;
4386 }
4387
4388 // Success! Record the copy.
4389 Statements.push_back(Copy.takeAs<Expr>());
4390 }
4391
4392 // \brief Reference to the __builtin_memcpy function.
4393 Expr *BuiltinMemCpyRef = 0;
4394
4395 // Assign non-static members.
4396 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4397 FieldEnd = ClassDecl->field_end();
4398 Field != FieldEnd; ++Field) {
4399 // Check for members of reference type; we can't copy those.
4400 if (Field->getType()->isReferenceType()) {
4401 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4402 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4403 Diag(Field->getLocation(), diag::note_declared_at);
4404 Diag(Loc, diag::note_first_required_here);
4405 Invalid = true;
4406 continue;
4407 }
4408
4409 // Check for members of const-qualified, non-class type.
4410 QualType BaseType = Context.getBaseElementType(Field->getType());
4411 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4412 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4413 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4414 Diag(Field->getLocation(), diag::note_declared_at);
4415 Diag(Loc, diag::note_first_required_here);
4416 Invalid = true;
4417 continue;
4418 }
4419
4420 QualType FieldType = Field->getType().getNonReferenceType();
4421
4422 // Build references to the field in the object we're copying from and to.
4423 CXXScopeSpec SS; // Intentionally empty
4424 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4425 LookupMemberName);
4426 MemberLookup.addDecl(*Field);
4427 MemberLookup.resolveKind();
4428 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4429 OtherRefType,
4430 Loc, /*IsArrow=*/false,
4431 SS, 0, MemberLookup, 0);
4432 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4433 This->getType(),
4434 Loc, /*IsArrow=*/true,
4435 SS, 0, MemberLookup, 0);
4436 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4437 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4438
4439 // If the field should be copied with __builtin_memcpy rather than via
4440 // explicit assignments, do so. This optimization only applies for arrays
4441 // of scalars and arrays of class type with trivial copy-assignment
4442 // operators.
4443 if (FieldType->isArrayType() &&
4444 (!BaseType->isRecordType() ||
4445 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4446 ->hasTrivialCopyAssignment())) {
4447 // Compute the size of the memory buffer to be copied.
4448 QualType SizeType = Context.getSizeType();
4449 llvm::APInt Size(Context.getTypeSize(SizeType),
4450 Context.getTypeSizeInChars(BaseType).getQuantity());
4451 for (const ConstantArrayType *Array
4452 = Context.getAsConstantArrayType(FieldType);
4453 Array;
4454 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4455 llvm::APInt ArraySize = Array->getSize();
4456 ArraySize.zextOrTrunc(Size.getBitWidth());
4457 Size *= ArraySize;
4458 }
4459
4460 // Take the address of the field references for "from" and "to".
4461 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4462 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4463
4464 // Create a reference to the __builtin_memcpy builtin function.
4465 if (!BuiltinMemCpyRef) {
4466 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4467 LookupOrdinaryName);
4468 LookupName(R, TUScope, true);
4469
4470 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4471 if (!BuiltinMemCpy) {
4472 // Something went horribly wrong earlier, and we will have complained
4473 // about it.
4474 Invalid = true;
4475 continue;
4476 }
4477
4478 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4479 BuiltinMemCpy->getType(),
4480 Loc, 0).takeAs<Expr>();
4481 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4482 }
4483
4484 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4485 CallArgs.push_back(To.takeAs<Expr>());
4486 CallArgs.push_back(From.takeAs<Expr>());
4487 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4488 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4489 Commas.push_back(Loc);
4490 Commas.push_back(Loc);
4491 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4492 Owned(BuiltinMemCpyRef->Retain()),
4493 Loc, move_arg(CallArgs),
4494 Commas.data(), Loc);
4495 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4496 Statements.push_back(Call.takeAs<Expr>());
4497 continue;
4498 }
4499
4500 // Build the copy of this field.
4501 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
4502 move(To), move(From));
4503 if (Copy.isInvalid()) {
4504 Invalid = true;
4505 continue;
4506 }
4507
4508 // Success! Record the copy.
4509 Statements.push_back(Copy.takeAs<Stmt>());
4510 }
4511
4512 if (!Invalid) {
4513 // Add a "return *this;"
4514 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4515 Owned(This->Retain()));
4516
4517 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4518 if (Return.isInvalid())
4519 Invalid = true;
4520 else {
4521 Statements.push_back(Return.takeAs<Stmt>());
4522 }
4523 }
4524
4525 if (Invalid) {
4526 CopyAssignOperator->setInvalidDecl();
4527 return;
4528 }
4529
4530 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4531 /*isStmtExpr=*/false);
4532 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4533 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004534}
4535
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004536void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4537 CXXConstructorDecl *CopyConstructor,
4538 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00004539 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00004540 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004541 !CopyConstructor->isUsed()) &&
4542 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004543
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00004544 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004545 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004546
Douglas Gregora57478e2010-05-01 15:04:51 +00004547 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004548
Anders Carlsson79111502010-05-01 16:39:01 +00004549 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4550 Diag(CurrentLocation, diag::note_member_synthesized_at)
4551 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4552 CopyConstructor->setInvalidDecl();
4553 } else {
4554 CopyConstructor->setUsed();
Anders Carlsson53e1ba92010-04-25 00:52:09 +00004555 }
Anders Carlsson79111502010-05-01 16:39:01 +00004556
4557 // FIXME: Once SetBaseOrMemberInitializers can handle copy initialization of
4558 // fields, this code below should be removed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004559 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4560 FieldEnd = ClassDecl->field_end();
4561 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004562 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4563 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4564 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004565 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004566 CXXRecordDecl *FieldClassDecl
4567 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004568 if (CXXConstructorDecl *FieldCopyCtor =
John McCallab8c2732010-03-16 06:11:48 +00004569 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4570 CheckDirectMemberAccess(Field->getLocation(),
4571 FieldCopyCtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004572 PDiag(diag::err_access_copy_field)
John McCallab8c2732010-03-16 06:11:48 +00004573 << Field->getDeclName() << Field->getType());
4574
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00004575 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
John McCallab8c2732010-03-16 06:11:48 +00004576 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004577 }
4578 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004579}
4580
Anders Carlsson6eb55572009-08-25 05:12:04 +00004581Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004582Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00004583 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004584 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004585 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004586 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00004587 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00004588
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004589 // C++0x [class.copy]p34:
4590 // When certain criteria are met, an implementation is allowed to
4591 // omit the copy/move construction of a class object, even if the
4592 // copy/move constructor and/or destructor for the object have
4593 // side effects. [...]
4594 // - when a temporary class object that has not been bound to a
4595 // reference (12.2) would be copied/moved to a class object
4596 // with the same cv-unqualified type, the copy/move operation
4597 // can be omitted by constructing the temporary object
4598 // directly into the target of the omitted copy/move
4599 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4600 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4601 Elidable = SubExpr->isTemporaryObject() &&
4602 Context.hasSameUnqualifiedType(SubExpr->getType(),
4603 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00004604 }
Mike Stump11289f42009-09-09 15:08:12 +00004605
4606 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004607 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004608 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00004609}
4610
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004611/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4612/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004613Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004614Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4615 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004616 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004617 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004618 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004619 unsigned NumExprs = ExprArgs.size();
4620 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004621
Douglas Gregor27381f32009-11-23 12:27:39 +00004622 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004623 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004624 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004625 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004626}
4627
Mike Stump11289f42009-09-09 15:08:12 +00004628bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004629 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004630 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004631 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004632 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004633 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004634 if (TempResult.isInvalid())
4635 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004636
Anders Carlsson6eb55572009-08-25 05:12:04 +00004637 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004638 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004639 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004640 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004641
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004642 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004643}
4644
John McCall03c48482010-02-02 09:10:11 +00004645void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4646 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004647 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4648 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004649 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4650 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00004651 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00004652 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00004653 << VD->getDeclName()
4654 << VD->getType());
John McCall6781b052010-02-02 08:45:54 +00004655 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004656}
4657
Mike Stump11289f42009-09-09 15:08:12 +00004658/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004659/// ActOnDeclarator, when a C++ direct initializer is present.
4660/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004661void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4662 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004663 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004664 SourceLocation *CommaLocs,
4665 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004666 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004667 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004668
4669 // If there is no declaration, there was an error parsing it. Just ignore
4670 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004671 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004672 return;
Mike Stump11289f42009-09-09 15:08:12 +00004673
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004674 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4675 if (!VDecl) {
4676 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4677 RealDecl->setInvalidDecl();
4678 return;
4679 }
4680
Douglas Gregor402250f2009-08-26 21:14:46 +00004681 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004682 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004683 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4684 //
4685 // Clients that want to distinguish between the two forms, can check for
4686 // direct initializer using VarDecl::hasCXXDirectInitializer().
4687 // A major benefit is that clients that don't particularly care about which
4688 // exactly form was it (like the CodeGen) can handle both cases without
4689 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004690
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004691 // C++ 8.5p11:
4692 // The form of initialization (using parentheses or '=') is generally
4693 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004694 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004695 QualType DeclInitType = VDecl->getType();
4696 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004697 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004698
Douglas Gregor50dc2192010-02-11 22:55:30 +00004699 if (!VDecl->getType()->isDependentType() &&
4700 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004701 diag::err_typecheck_decl_incomplete_type)) {
4702 VDecl->setInvalidDecl();
4703 return;
4704 }
4705
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004706 // The variable can not have an abstract class type.
4707 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4708 diag::err_abstract_type_in_decl,
4709 AbstractVariableType))
4710 VDecl->setInvalidDecl();
4711
Sebastian Redl5ca79842010-02-01 20:16:42 +00004712 const VarDecl *Def;
4713 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004714 Diag(VDecl->getLocation(), diag::err_redefinition)
4715 << VDecl->getDeclName();
4716 Diag(Def->getLocation(), diag::note_previous_definition);
4717 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004718 return;
4719 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004720
4721 // If either the declaration has a dependent type or if any of the
4722 // expressions is type-dependent, we represent the initialization
4723 // via a ParenListExpr for later use during template instantiation.
4724 if (VDecl->getType()->isDependentType() ||
4725 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4726 // Let clients know that initialization was done with a direct initializer.
4727 VDecl->setCXXDirectInitializer(true);
4728
4729 // Store the initialization expressions as a ParenListExpr.
4730 unsigned NumExprs = Exprs.size();
4731 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4732 (Expr **)Exprs.release(),
4733 NumExprs, RParenLoc));
4734 return;
4735 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004736
4737 // Capture the variable that is being initialized and the style of
4738 // initialization.
4739 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4740
4741 // FIXME: Poor source location information.
4742 InitializationKind Kind
4743 = InitializationKind::CreateDirect(VDecl->getLocation(),
4744 LParenLoc, RParenLoc);
4745
4746 InitializationSequence InitSeq(*this, Entity, Kind,
4747 (Expr**)Exprs.get(), Exprs.size());
4748 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4749 if (Result.isInvalid()) {
4750 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004751 return;
4752 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004753
4754 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004755 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004756 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004757
John McCall03c48482010-02-02 09:10:11 +00004758 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4759 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004760}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004761
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004762/// \brief Given a constructor and the set of arguments provided for the
4763/// constructor, convert the arguments and add any required default arguments
4764/// to form a proper call to this constructor.
4765///
4766/// \returns true if an error occurred, false otherwise.
4767bool
4768Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4769 MultiExprArg ArgsPtr,
4770 SourceLocation Loc,
4771 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4772 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4773 unsigned NumArgs = ArgsPtr.size();
4774 Expr **Args = (Expr **)ArgsPtr.get();
4775
4776 const FunctionProtoType *Proto
4777 = Constructor->getType()->getAs<FunctionProtoType>();
4778 assert(Proto && "Constructor without a prototype?");
4779 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004780
4781 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004782 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004783 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004784 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004785 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004786
4787 VariadicCallType CallType =
4788 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4789 llvm::SmallVector<Expr *, 8> AllArgs;
4790 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4791 Proto, 0, Args, NumArgs, AllArgs,
4792 CallType);
4793 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4794 ConvertedArgs.push_back(AllArgs[i]);
4795 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004796}
4797
Anders Carlssone363c8e2009-12-12 00:32:00 +00004798static inline bool
4799CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4800 const FunctionDecl *FnDecl) {
4801 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4802 if (isa<NamespaceDecl>(DC)) {
4803 return SemaRef.Diag(FnDecl->getLocation(),
4804 diag::err_operator_new_delete_declared_in_namespace)
4805 << FnDecl->getDeclName();
4806 }
4807
4808 if (isa<TranslationUnitDecl>(DC) &&
4809 FnDecl->getStorageClass() == FunctionDecl::Static) {
4810 return SemaRef.Diag(FnDecl->getLocation(),
4811 diag::err_operator_new_delete_declared_static)
4812 << FnDecl->getDeclName();
4813 }
4814
Anders Carlsson60659a82009-12-12 02:43:16 +00004815 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004816}
4817
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004818static inline bool
4819CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4820 CanQualType ExpectedResultType,
4821 CanQualType ExpectedFirstParamType,
4822 unsigned DependentParamTypeDiag,
4823 unsigned InvalidParamTypeDiag) {
4824 QualType ResultType =
4825 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4826
4827 // Check that the result type is not dependent.
4828 if (ResultType->isDependentType())
4829 return SemaRef.Diag(FnDecl->getLocation(),
4830 diag::err_operator_new_delete_dependent_result_type)
4831 << FnDecl->getDeclName() << ExpectedResultType;
4832
4833 // Check that the result type is what we expect.
4834 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4835 return SemaRef.Diag(FnDecl->getLocation(),
4836 diag::err_operator_new_delete_invalid_result_type)
4837 << FnDecl->getDeclName() << ExpectedResultType;
4838
4839 // A function template must have at least 2 parameters.
4840 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4841 return SemaRef.Diag(FnDecl->getLocation(),
4842 diag::err_operator_new_delete_template_too_few_parameters)
4843 << FnDecl->getDeclName();
4844
4845 // The function decl must have at least 1 parameter.
4846 if (FnDecl->getNumParams() == 0)
4847 return SemaRef.Diag(FnDecl->getLocation(),
4848 diag::err_operator_new_delete_too_few_parameters)
4849 << FnDecl->getDeclName();
4850
4851 // Check the the first parameter type is not dependent.
4852 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4853 if (FirstParamType->isDependentType())
4854 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4855 << FnDecl->getDeclName() << ExpectedFirstParamType;
4856
4857 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004858 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004859 ExpectedFirstParamType)
4860 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4861 << FnDecl->getDeclName() << ExpectedFirstParamType;
4862
4863 return false;
4864}
4865
Anders Carlsson12308f42009-12-11 23:23:22 +00004866static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004867CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004868 // C++ [basic.stc.dynamic.allocation]p1:
4869 // A program is ill-formed if an allocation function is declared in a
4870 // namespace scope other than global scope or declared static in global
4871 // scope.
4872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4873 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004874
4875 CanQualType SizeTy =
4876 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4877
4878 // C++ [basic.stc.dynamic.allocation]p1:
4879 // The return type shall be void*. The first parameter shall have type
4880 // std::size_t.
4881 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4882 SizeTy,
4883 diag::err_operator_new_dependent_param_type,
4884 diag::err_operator_new_param_type))
4885 return true;
4886
4887 // C++ [basic.stc.dynamic.allocation]p1:
4888 // The first parameter shall not have an associated default argument.
4889 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004890 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004891 diag::err_operator_new_default_arg)
4892 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4893
4894 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004895}
4896
4897static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004898CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4899 // C++ [basic.stc.dynamic.deallocation]p1:
4900 // A program is ill-formed if deallocation functions are declared in a
4901 // namespace scope other than global scope or declared static in global
4902 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004903 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4904 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004905
4906 // C++ [basic.stc.dynamic.deallocation]p2:
4907 // Each deallocation function shall return void and its first parameter
4908 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004909 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4910 SemaRef.Context.VoidPtrTy,
4911 diag::err_operator_delete_dependent_param_type,
4912 diag::err_operator_delete_param_type))
4913 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004914
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004915 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4916 if (FirstParamType->isDependentType())
4917 return SemaRef.Diag(FnDecl->getLocation(),
4918 diag::err_operator_delete_dependent_param_type)
4919 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4920
4921 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4922 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004923 return SemaRef.Diag(FnDecl->getLocation(),
4924 diag::err_operator_delete_param_type)
4925 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004926
4927 return false;
4928}
4929
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004930/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4931/// of this overloaded operator is well-formed. If so, returns false;
4932/// otherwise, emits appropriate diagnostics and returns true.
4933bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004934 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004935 "Expected an overloaded operator declaration");
4936
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004937 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4938
Mike Stump11289f42009-09-09 15:08:12 +00004939 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004940 // The allocation and deallocation functions, operator new,
4941 // operator new[], operator delete and operator delete[], are
4942 // described completely in 3.7.3. The attributes and restrictions
4943 // found in the rest of this subclause do not apply to them unless
4944 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004945 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004946 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004947
Anders Carlsson22f443f2009-12-12 00:26:23 +00004948 if (Op == OO_New || Op == OO_Array_New)
4949 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004950
4951 // C++ [over.oper]p6:
4952 // An operator function shall either be a non-static member
4953 // function or be a non-member function and have at least one
4954 // parameter whose type is a class, a reference to a class, an
4955 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004956 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4957 if (MethodDecl->isStatic())
4958 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004959 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004960 } else {
4961 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004962 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4963 ParamEnd = FnDecl->param_end();
4964 Param != ParamEnd; ++Param) {
4965 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004966 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4967 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004968 ClassOrEnumParam = true;
4969 break;
4970 }
4971 }
4972
Douglas Gregord69246b2008-11-17 16:14:12 +00004973 if (!ClassOrEnumParam)
4974 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004975 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004976 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004977 }
4978
4979 // C++ [over.oper]p8:
4980 // An operator function cannot have default arguments (8.3.6),
4981 // except where explicitly stated below.
4982 //
Mike Stump11289f42009-09-09 15:08:12 +00004983 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004984 // (C++ [over.call]p1).
4985 if (Op != OO_Call) {
4986 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4987 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004988 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004989 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004990 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004991 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004992 }
4993 }
4994
Douglas Gregor6cf08062008-11-10 13:38:07 +00004995 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4996 { false, false, false }
4997#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4998 , { Unary, Binary, MemberOnly }
4999#include "clang/Basic/OperatorKinds.def"
5000 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005001
Douglas Gregor6cf08062008-11-10 13:38:07 +00005002 bool CanBeUnaryOperator = OperatorUses[Op][0];
5003 bool CanBeBinaryOperator = OperatorUses[Op][1];
5004 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005005
5006 // C++ [over.oper]p8:
5007 // [...] Operator functions cannot have more or fewer parameters
5008 // than the number required for the corresponding operator, as
5009 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005010 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005011 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005012 if (Op != OO_Call &&
5013 ((NumParams == 1 && !CanBeUnaryOperator) ||
5014 (NumParams == 2 && !CanBeBinaryOperator) ||
5015 (NumParams < 1) || (NumParams > 2))) {
5016 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005017 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005018 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005019 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005020 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005021 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005022 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005023 assert(CanBeBinaryOperator &&
5024 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005025 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005026 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005027
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005028 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005029 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005030 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005031
Douglas Gregord69246b2008-11-17 16:14:12 +00005032 // Overloaded operators other than operator() cannot be variadic.
5033 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005034 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005035 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005036 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005037 }
5038
5039 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005040 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5041 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005042 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005043 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005044 }
5045
5046 // C++ [over.inc]p1:
5047 // The user-defined function called operator++ implements the
5048 // prefix and postfix ++ operator. If this function is a member
5049 // function with no parameters, or a non-member function with one
5050 // parameter of class or enumeration type, it defines the prefix
5051 // increment operator ++ for objects of that type. If the function
5052 // is a member function with one parameter (which shall be of type
5053 // int) or a non-member function with two parameters (the second
5054 // of which shall be of type int), it defines the postfix
5055 // increment operator ++ for objects of that type.
5056 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5057 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5058 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005059 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005060 ParamIsInt = BT->getKind() == BuiltinType::Int;
5061
Chris Lattner2b786902008-11-21 07:50:02 +00005062 if (!ParamIsInt)
5063 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005064 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005065 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005066 }
5067
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005068 // Notify the class if it got an assignment operator.
5069 if (Op == OO_Equal) {
5070 // Would have returned earlier otherwise.
5071 assert(isa<CXXMethodDecl>(FnDecl) &&
5072 "Overloaded = not member, but not filtered.");
5073 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5074 Method->getParent()->addedAssignmentOperator(Context, Method);
5075 }
5076
Douglas Gregord69246b2008-11-17 16:14:12 +00005077 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005078}
Chris Lattner3b024a32008-12-17 07:09:26 +00005079
Alexis Huntc88db062010-01-13 09:01:02 +00005080/// CheckLiteralOperatorDeclaration - Check whether the declaration
5081/// of this literal operator function is well-formed. If so, returns
5082/// false; otherwise, emits appropriate diagnostics and returns true.
5083bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5084 DeclContext *DC = FnDecl->getDeclContext();
5085 Decl::Kind Kind = DC->getDeclKind();
5086 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5087 Kind != Decl::LinkageSpec) {
5088 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5089 << FnDecl->getDeclName();
5090 return true;
5091 }
5092
5093 bool Valid = false;
5094
Alexis Hunt7dd26172010-04-07 23:11:06 +00005095 // template <char...> type operator "" name() is the only valid template
5096 // signature, and the only valid signature with no parameters.
5097 if (FnDecl->param_size() == 0) {
5098 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5099 // Must have only one template parameter
5100 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5101 if (Params->size() == 1) {
5102 NonTypeTemplateParmDecl *PmDecl =
5103 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005104
Alexis Hunt7dd26172010-04-07 23:11:06 +00005105 // The template parameter must be a char parameter pack.
5106 // FIXME: This test will always fail because non-type parameter packs
5107 // have not been implemented.
5108 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5109 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5110 Valid = true;
5111 }
5112 }
5113 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005114 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005115 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5116
Alexis Huntc88db062010-01-13 09:01:02 +00005117 QualType T = (*Param)->getType();
5118
Alexis Hunt079a6f72010-04-07 22:57:35 +00005119 // unsigned long long int, long double, and any character type are allowed
5120 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005121 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5122 Context.hasSameType(T, Context.LongDoubleTy) ||
5123 Context.hasSameType(T, Context.CharTy) ||
5124 Context.hasSameType(T, Context.WCharTy) ||
5125 Context.hasSameType(T, Context.Char16Ty) ||
5126 Context.hasSameType(T, Context.Char32Ty)) {
5127 if (++Param == FnDecl->param_end())
5128 Valid = true;
5129 goto FinishedParams;
5130 }
5131
Alexis Hunt079a6f72010-04-07 22:57:35 +00005132 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005133 const PointerType *PT = T->getAs<PointerType>();
5134 if (!PT)
5135 goto FinishedParams;
5136 T = PT->getPointeeType();
5137 if (!T.isConstQualified())
5138 goto FinishedParams;
5139 T = T.getUnqualifiedType();
5140
5141 // Move on to the second parameter;
5142 ++Param;
5143
5144 // If there is no second parameter, the first must be a const char *
5145 if (Param == FnDecl->param_end()) {
5146 if (Context.hasSameType(T, Context.CharTy))
5147 Valid = true;
5148 goto FinishedParams;
5149 }
5150
5151 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5152 // are allowed as the first parameter to a two-parameter function
5153 if (!(Context.hasSameType(T, Context.CharTy) ||
5154 Context.hasSameType(T, Context.WCharTy) ||
5155 Context.hasSameType(T, Context.Char16Ty) ||
5156 Context.hasSameType(T, Context.Char32Ty)))
5157 goto FinishedParams;
5158
5159 // The second and final parameter must be an std::size_t
5160 T = (*Param)->getType().getUnqualifiedType();
5161 if (Context.hasSameType(T, Context.getSizeType()) &&
5162 ++Param == FnDecl->param_end())
5163 Valid = true;
5164 }
5165
5166 // FIXME: This diagnostic is absolutely terrible.
5167FinishedParams:
5168 if (!Valid) {
5169 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5170 << FnDecl->getDeclName();
5171 return true;
5172 }
5173
5174 return false;
5175}
5176
Douglas Gregor07665a62009-01-05 19:45:36 +00005177/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5178/// linkage specification, including the language and (if present)
5179/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5180/// the location of the language string literal, which is provided
5181/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5182/// the '{' brace. Otherwise, this linkage specification does not
5183/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005184Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5185 SourceLocation ExternLoc,
5186 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005187 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005188 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005189 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005190 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005191 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005192 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005193 Language = LinkageSpecDecl::lang_cxx;
5194 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005195 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005196 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005197 }
Mike Stump11289f42009-09-09 15:08:12 +00005198
Chris Lattner438e5012008-12-17 07:13:27 +00005199 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005200
Douglas Gregor07665a62009-01-05 19:45:36 +00005201 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005202 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005203 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005204 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005205 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005206 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005207}
5208
Douglas Gregor07665a62009-01-05 19:45:36 +00005209/// ActOnFinishLinkageSpecification - Completely the definition of
5210/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5211/// valid, it's the position of the closing '}' brace in a linkage
5212/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005213Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5214 DeclPtrTy LinkageSpec,
5215 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005216 if (LinkageSpec)
5217 PopDeclContext();
5218 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005219}
5220
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005221/// \brief Perform semantic analysis for the variable declaration that
5222/// occurs within a C++ catch clause, returning the newly-created
5223/// variable.
5224VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005225 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005226 IdentifierInfo *Name,
5227 SourceLocation Loc,
5228 SourceRange Range) {
5229 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005230
5231 // Arrays and functions decay.
5232 if (ExDeclType->isArrayType())
5233 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5234 else if (ExDeclType->isFunctionType())
5235 ExDeclType = Context.getPointerType(ExDeclType);
5236
5237 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5238 // The exception-declaration shall not denote a pointer or reference to an
5239 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005240 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005241 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005242 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005243 Invalid = true;
5244 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005245
Douglas Gregor104ee002010-03-08 01:47:36 +00005246 // GCC allows catching pointers and references to incomplete types
5247 // as an extension; so do we, but we warn by default.
5248
Sebastian Redl54c04d42008-12-22 19:15:10 +00005249 QualType BaseType = ExDeclType;
5250 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005251 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005252 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005253 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005254 BaseType = Ptr->getPointeeType();
5255 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005256 DK = diag::ext_catch_incomplete_ptr;
5257 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005258 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005259 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005260 BaseType = Ref->getPointeeType();
5261 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005262 DK = diag::ext_catch_incomplete_ref;
5263 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005264 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005265 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005266 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5267 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005268 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005269
Mike Stump11289f42009-09-09 15:08:12 +00005270 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005271 RequireNonAbstractType(Loc, ExDeclType,
5272 diag::err_abstract_type_in_decl,
5273 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005274 Invalid = true;
5275
Mike Stump11289f42009-09-09 15:08:12 +00005276 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005277 Name, ExDeclType, TInfo, VarDecl::None,
5278 VarDecl::None);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005279
Douglas Gregor6de584c2010-03-05 23:38:39 +00005280 if (!Invalid) {
5281 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5282 // C++ [except.handle]p16:
5283 // The object declared in an exception-declaration or, if the
5284 // exception-declaration does not specify a name, a temporary (12.2) is
5285 // copy-initialized (8.5) from the exception object. [...]
5286 // The object is destroyed when the handler exits, after the destruction
5287 // of any automatic objects initialized within the handler.
5288 //
5289 // We just pretend to initialize the object with itself, then make sure
5290 // it can be destroyed later.
5291 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5292 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5293 Loc, ExDeclType, 0);
5294 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5295 SourceLocation());
5296 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5297 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5298 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5299 if (Result.isInvalid())
5300 Invalid = true;
5301 else
5302 FinalizeVarWithDestructor(ExDecl, RecordTy);
5303 }
5304 }
5305
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005306 if (Invalid)
5307 ExDecl->setInvalidDecl();
5308
5309 return ExDecl;
5310}
5311
5312/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5313/// handler.
5314Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005315 TypeSourceInfo *TInfo = 0;
5316 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005317
5318 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005319 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005320 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00005321 LookupOrdinaryName,
5322 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005323 // The scope should be freshly made just for us. There is just no way
5324 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005325 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005326 if (PrevDecl->isTemplateParameter()) {
5327 // Maybe we will complain about the shadowed template parameter.
5328 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005329 }
5330 }
5331
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005332 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005333 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5334 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005335 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005336 }
5337
John McCallbcd03502009-12-07 02:54:59 +00005338 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005339 D.getIdentifier(),
5340 D.getIdentifierLoc(),
5341 D.getDeclSpec().getSourceRange());
5342
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005343 if (Invalid)
5344 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005345
Sebastian Redl54c04d42008-12-22 19:15:10 +00005346 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005347 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005348 PushOnScopeChains(ExDecl, S);
5349 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005350 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005351
Douglas Gregor758a8692009-06-17 21:51:59 +00005352 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005353 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005354}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005355
Mike Stump11289f42009-09-09 15:08:12 +00005356Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005357 ExprArg assertexpr,
5358 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005359 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005360 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005361 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5362
Anders Carlsson54b26982009-03-14 00:33:21 +00005363 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5364 llvm::APSInt Value(32);
5365 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5366 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5367 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005368 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005369 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005370
Anders Carlsson54b26982009-03-14 00:33:21 +00005371 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005372 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005373 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005374 }
5375 }
Mike Stump11289f42009-09-09 15:08:12 +00005376
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005377 assertexpr.release();
5378 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005379 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005380 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005381
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005382 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005383 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005384}
Sebastian Redlf769df52009-03-24 22:27:57 +00005385
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005386/// \brief Perform semantic analysis of the given friend type declaration.
5387///
5388/// \returns A friend declaration that.
5389FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5390 TypeSourceInfo *TSInfo) {
5391 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5392
5393 QualType T = TSInfo->getType();
5394 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5395
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005396 if (!getLangOptions().CPlusPlus0x) {
5397 // C++03 [class.friend]p2:
5398 // An elaborated-type-specifier shall be used in a friend declaration
5399 // for a class.*
5400 //
5401 // * The class-key of the elaborated-type-specifier is required.
5402 if (!ActiveTemplateInstantiations.empty()) {
5403 // Do not complain about the form of friend template types during
5404 // template instantiation; we will already have complained when the
5405 // template was declared.
5406 } else if (!T->isElaboratedTypeSpecifier()) {
5407 // If we evaluated the type to a record type, suggest putting
5408 // a tag in front.
5409 if (const RecordType *RT = T->getAs<RecordType>()) {
5410 RecordDecl *RD = RT->getDecl();
5411
5412 std::string InsertionText = std::string(" ") + RD->getKindName();
5413
5414 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5415 << (unsigned) RD->getTagKind()
5416 << T
5417 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5418 InsertionText);
5419 } else {
5420 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5421 << T
5422 << SourceRange(FriendLoc, TypeRange.getEnd());
5423 }
5424 } else if (T->getAs<EnumType>()) {
5425 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005426 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005427 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005428 }
5429 }
5430
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005431 // C++0x [class.friend]p3:
5432 // If the type specifier in a friend declaration designates a (possibly
5433 // cv-qualified) class type, that class is declared as a friend; otherwise,
5434 // the friend declaration is ignored.
5435
5436 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5437 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005438
5439 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5440}
5441
John McCall11083da2009-09-16 22:47:08 +00005442/// Handle a friend type declaration. This works in tandem with
5443/// ActOnTag.
5444///
5445/// Notes on friend class templates:
5446///
5447/// We generally treat friend class declarations as if they were
5448/// declaring a class. So, for example, the elaborated type specifier
5449/// in a friend declaration is required to obey the restrictions of a
5450/// class-head (i.e. no typedefs in the scope chain), template
5451/// parameters are required to match up with simple template-ids, &c.
5452/// However, unlike when declaring a template specialization, it's
5453/// okay to refer to a template specialization without an empty
5454/// template parameter declaration, e.g.
5455/// friend class A<T>::B<unsigned>;
5456/// We permit this as a special case; if there are any template
5457/// parameters present at all, require proper matching, i.e.
5458/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005459Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005460 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005461 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005462
5463 assert(DS.isFriendSpecified());
5464 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5465
John McCall11083da2009-09-16 22:47:08 +00005466 // Try to convert the decl specifier to a type. This works for
5467 // friend templates because ActOnTag never produces a ClassTemplateDecl
5468 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005469 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall15ad0962010-03-25 18:04:51 +00005470 TypeSourceInfo *TSI;
5471 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005472 if (TheDeclarator.isInvalidType())
5473 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005474
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005475 if (!TSI)
5476 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5477
John McCall11083da2009-09-16 22:47:08 +00005478 // This is definitely an error in C++98. It's probably meant to
5479 // be forbidden in C++0x, too, but the specification is just
5480 // poorly written.
5481 //
5482 // The problem is with declarations like the following:
5483 // template <T> friend A<T>::foo;
5484 // where deciding whether a class C is a friend or not now hinges
5485 // on whether there exists an instantiation of A that causes
5486 // 'foo' to equal C. There are restrictions on class-heads
5487 // (which we declare (by fiat) elaborated friend declarations to
5488 // be) that makes this tractable.
5489 //
5490 // FIXME: handle "template <> friend class A<T>;", which
5491 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00005492 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00005493 Diag(Loc, diag::err_tagless_friend_type_template)
5494 << DS.getSourceRange();
5495 return DeclPtrTy();
5496 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005497
John McCallaa74a0c2009-08-28 07:59:38 +00005498 // C++98 [class.friend]p1: A friend of a class is a function
5499 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005500 // This is fixed in DR77, which just barely didn't make the C++03
5501 // deadline. It's also a very silly restriction that seriously
5502 // affects inner classes and which nobody else seems to implement;
5503 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00005504 //
5505 // But note that we could warn about it: it's always useless to
5506 // friend one of your own members (it's not, however, worthless to
5507 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00005508
John McCall11083da2009-09-16 22:47:08 +00005509 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005510 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00005511 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005512 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00005513 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00005514 TSI,
John McCall11083da2009-09-16 22:47:08 +00005515 DS.getFriendSpecLoc());
5516 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005517 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5518
5519 if (!D)
5520 return DeclPtrTy();
5521
John McCall11083da2009-09-16 22:47:08 +00005522 D->setAccess(AS_public);
5523 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005524
John McCall11083da2009-09-16 22:47:08 +00005525 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005526}
5527
John McCall2f212b32009-09-11 21:02:39 +00005528Sema::DeclPtrTy
5529Sema::ActOnFriendFunctionDecl(Scope *S,
5530 Declarator &D,
5531 bool IsDefinition,
5532 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005533 const DeclSpec &DS = D.getDeclSpec();
5534
5535 assert(DS.isFriendSpecified());
5536 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5537
5538 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005539 TypeSourceInfo *TInfo = 0;
5540 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005541
5542 // C++ [class.friend]p1
5543 // A friend of a class is a function or class....
5544 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005545 // It *doesn't* see through dependent types, which is correct
5546 // according to [temp.arg.type]p3:
5547 // If a declaration acquires a function type through a
5548 // type dependent on a template-parameter and this causes
5549 // a declaration that does not use the syntactic form of a
5550 // function declarator to have a function type, the program
5551 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005552 if (!T->isFunctionType()) {
5553 Diag(Loc, diag::err_unexpected_friend);
5554
5555 // It might be worthwhile to try to recover by creating an
5556 // appropriate declaration.
5557 return DeclPtrTy();
5558 }
5559
5560 // C++ [namespace.memdef]p3
5561 // - If a friend declaration in a non-local class first declares a
5562 // class or function, the friend class or function is a member
5563 // of the innermost enclosing namespace.
5564 // - The name of the friend is not found by simple name lookup
5565 // until a matching declaration is provided in that namespace
5566 // scope (either before or after the class declaration granting
5567 // friendship).
5568 // - If a friend function is called, its name may be found by the
5569 // name lookup that considers functions from namespaces and
5570 // classes associated with the types of the function arguments.
5571 // - When looking for a prior declaration of a class or a function
5572 // declared as a friend, scopes outside the innermost enclosing
5573 // namespace scope are not considered.
5574
John McCallaa74a0c2009-08-28 07:59:38 +00005575 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5576 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005577 assert(Name);
5578
John McCall07e91c02009-08-06 02:15:43 +00005579 // The context we found the declaration in, or in which we should
5580 // create the declaration.
5581 DeclContext *DC;
5582
5583 // FIXME: handle local classes
5584
5585 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005586 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5587 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005588 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5589 DC = computeDeclContext(ScopeQual);
5590
5591 // FIXME: handle dependent contexts
5592 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00005593 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005594
John McCall1f82f242009-11-18 22:49:29 +00005595 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005596
5597 // If searching in that context implicitly found a declaration in
5598 // a different context, treat it like it wasn't found at all.
5599 // TODO: better diagnostics for this case. Suggesting the right
5600 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005601 // FIXME: getRepresentativeDecl() is not right here at all
5602 if (Previous.empty() ||
5603 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005604 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005605 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5606 return DeclPtrTy();
5607 }
5608
5609 // C++ [class.friend]p1: A friend of a class is a function or
5610 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005611 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005612 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5613
John McCall07e91c02009-08-06 02:15:43 +00005614 // Otherwise walk out to the nearest namespace scope looking for matches.
5615 } else {
5616 // TODO: handle local class contexts.
5617
5618 DC = CurContext;
5619 while (true) {
5620 // Skip class contexts. If someone can cite chapter and verse
5621 // for this behavior, that would be nice --- it's what GCC and
5622 // EDG do, and it seems like a reasonable intent, but the spec
5623 // really only says that checks for unqualified existing
5624 // declarations should stop at the nearest enclosing namespace,
5625 // not that they should only consider the nearest enclosing
5626 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005627 while (DC->isRecord())
5628 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005629
John McCall1f82f242009-11-18 22:49:29 +00005630 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005631
5632 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005633 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005634 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005635
John McCall07e91c02009-08-06 02:15:43 +00005636 if (DC->isFileContext()) break;
5637 DC = DC->getParent();
5638 }
5639
5640 // C++ [class.friend]p1: A friend of a class is a function or
5641 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005642 // C++0x changes this for both friend types and functions.
5643 // Most C++ 98 compilers do seem to give an error here, so
5644 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005645 if (!Previous.empty() && DC->Equals(CurContext)
5646 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005647 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5648 }
5649
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005650 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005651 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005652 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5653 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5654 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005655 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005656 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5657 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005658 return DeclPtrTy();
5659 }
John McCall07e91c02009-08-06 02:15:43 +00005660 }
5661
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005662 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005663 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005664 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005665 IsDefinition,
5666 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005667 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005668
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005669 assert(ND->getDeclContext() == DC);
5670 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005671
John McCall759e32b2009-08-31 22:39:49 +00005672 // Add the function declaration to the appropriate lookup tables,
5673 // adjusting the redeclarations list as necessary. We don't
5674 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005675 //
John McCall759e32b2009-08-31 22:39:49 +00005676 // Also update the scope-based lookup if the target context's
5677 // lookup context is in lexical scope.
5678 if (!CurContext->isDependentContext()) {
5679 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005680 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005681 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005682 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005683 }
John McCallaa74a0c2009-08-28 07:59:38 +00005684
5685 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005686 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005687 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005688 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005689 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005690
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005691 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005692}
5693
Chris Lattner83f095c2009-03-28 19:18:32 +00005694void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005695 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005696
Chris Lattner83f095c2009-03-28 19:18:32 +00005697 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005698 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5699 if (!Fn) {
5700 Diag(DelLoc, diag::err_deleted_non_function);
5701 return;
5702 }
5703 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5704 Diag(DelLoc, diag::err_deleted_decl_not_first);
5705 Diag(Prev->getLocation(), diag::note_previous_declaration);
5706 // If the declaration wasn't the first, we delete the function anyway for
5707 // recovery.
5708 }
5709 Fn->setDeleted();
5710}
Sebastian Redl4c018662009-04-27 21:33:24 +00005711
5712static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5713 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5714 ++CI) {
5715 Stmt *SubStmt = *CI;
5716 if (!SubStmt)
5717 continue;
5718 if (isa<ReturnStmt>(SubStmt))
5719 Self.Diag(SubStmt->getSourceRange().getBegin(),
5720 diag::err_return_in_constructor_handler);
5721 if (!isa<Expr>(SubStmt))
5722 SearchForReturnInStmt(Self, SubStmt);
5723 }
5724}
5725
5726void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5727 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5728 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5729 SearchForReturnInStmt(*this, Handler);
5730 }
5731}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005732
Mike Stump11289f42009-09-09 15:08:12 +00005733bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005734 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005735 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5736 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005737
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005738 if (Context.hasSameType(NewTy, OldTy) ||
5739 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005740 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005741
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005742 // Check if the return types are covariant
5743 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005744
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005745 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005746 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5747 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005748 NewClassTy = NewPT->getPointeeType();
5749 OldClassTy = OldPT->getPointeeType();
5750 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005751 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5752 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5753 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5754 NewClassTy = NewRT->getPointeeType();
5755 OldClassTy = OldRT->getPointeeType();
5756 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005757 }
5758 }
Mike Stump11289f42009-09-09 15:08:12 +00005759
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005760 // The return types aren't either both pointers or references to a class type.
5761 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005762 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005763 diag::err_different_return_type_for_overriding_virtual_function)
5764 << New->getDeclName() << NewTy << OldTy;
5765 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005766
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005767 return true;
5768 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005769
Anders Carlssone60365b2009-12-31 18:34:24 +00005770 // C++ [class.virtual]p6:
5771 // If the return type of D::f differs from the return type of B::f, the
5772 // class type in the return type of D::f shall be complete at the point of
5773 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005774 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5775 if (!RT->isBeingDefined() &&
5776 RequireCompleteType(New->getLocation(), NewClassTy,
5777 PDiag(diag::err_covariant_return_incomplete)
5778 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005779 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005780 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005781
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005782 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005783 // Check if the new class derives from the old class.
5784 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5785 Diag(New->getLocation(),
5786 diag::err_covariant_return_not_derived)
5787 << New->getDeclName() << NewTy << OldTy;
5788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5789 return true;
5790 }
Mike Stump11289f42009-09-09 15:08:12 +00005791
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005792 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00005793 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00005794 diag::err_covariant_return_inaccessible_base,
5795 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5796 // FIXME: Should this point to the return type?
5797 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005798 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5799 return true;
5800 }
5801 }
Mike Stump11289f42009-09-09 15:08:12 +00005802
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005803 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005804 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005805 Diag(New->getLocation(),
5806 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005807 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005808 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5809 return true;
5810 };
Mike Stump11289f42009-09-09 15:08:12 +00005811
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005812
5813 // The new class type must have the same or less qualifiers as the old type.
5814 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5815 Diag(New->getLocation(),
5816 diag::err_covariant_return_type_class_type_more_qualified)
5817 << New->getDeclName() << NewTy << OldTy;
5818 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5819 return true;
5820 };
Mike Stump11289f42009-09-09 15:08:12 +00005821
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005822 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005823}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005824
Alexis Hunt96d5c762009-11-21 08:43:09 +00005825bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5826 const CXXMethodDecl *Old)
5827{
5828 if (Old->hasAttr<FinalAttr>()) {
5829 Diag(New->getLocation(), diag::err_final_function_overridden)
5830 << New->getDeclName();
5831 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5832 return true;
5833 }
5834
5835 return false;
5836}
5837
Douglas Gregor21920e372009-12-01 17:24:26 +00005838/// \brief Mark the given method pure.
5839///
5840/// \param Method the method to be marked pure.
5841///
5842/// \param InitRange the source range that covers the "0" initializer.
5843bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5844 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5845 Method->setPure();
5846
5847 // A class is abstract if at least one function is pure virtual.
5848 Method->getParent()->setAbstract(true);
5849 return false;
5850 }
5851
5852 if (!Method->isInvalidDecl())
5853 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5854 << Method->getDeclName() << InitRange;
5855 return true;
5856}
5857
John McCall1f4ee7b2009-12-19 09:28:58 +00005858/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5859/// an initializer for the out-of-line declaration 'Dcl'. The scope
5860/// is a fresh scope pushed for just this purpose.
5861///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005862/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5863/// static data member of class X, names should be looked up in the scope of
5864/// class X.
5865void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005866 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005867 Decl *D = Dcl.getAs<Decl>();
5868 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005869
John McCall1f4ee7b2009-12-19 09:28:58 +00005870 // We should only get called for declarations with scope specifiers, like:
5871 // int foo::bar;
5872 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005873 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005874}
5875
5876/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005877/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005878void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005879 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005880 Decl *D = Dcl.getAs<Decl>();
5881 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005882
John McCall1f4ee7b2009-12-19 09:28:58 +00005883 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005884 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005885}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005886
5887/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5888/// C++ if/switch/while/for statement.
5889/// e.g: "if (int x = f()) {...}"
5890Action::DeclResult
5891Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5892 // C++ 6.4p2:
5893 // The declarator shall not specify a function or an array.
5894 // The type-specifier-seq shall not contain typedef and shall not declare a
5895 // new class or enumeration.
5896 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5897 "Parser allowed 'typedef' as storage class of condition decl.");
5898
John McCallbcd03502009-12-07 02:54:59 +00005899 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005900 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005901 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005902
5903 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5904 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5905 // would be created and CXXConditionDeclExpr wants a VarDecl.
5906 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5907 << D.getSourceRange();
5908 return DeclResult();
5909 } else if (OwnedTag && OwnedTag->isDefinition()) {
5910 // The type-specifier-seq shall not declare a new class or enumeration.
5911 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5912 }
5913
5914 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5915 if (!Dcl)
5916 return DeclResult();
5917
5918 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5919 VD->setDeclaredInCondition(true);
5920 return Dcl;
5921}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005922
Anders Carlsson11e51402010-04-17 20:15:18 +00005923static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005924 // Ignore dependent types.
5925 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005926 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005927
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005928 // Ignore declarations that are not definitions.
5929 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005930 return false;
5931
5932 CXXRecordDecl *RD = MD->getParent();
5933
5934 // Ignore classes without a vtable.
5935 if (!RD->isDynamicClass())
5936 return false;
5937
5938 switch (MD->getParent()->getTemplateSpecializationKind()) {
5939 case TSK_Undeclared:
5940 case TSK_ExplicitSpecialization:
5941 // Classes that aren't instantiations of templates don't need their
5942 // virtual methods marked until we see the definition of the key
5943 // function.
5944 break;
5945
5946 case TSK_ImplicitInstantiation:
5947 // This is a constructor of a class template; mark all of the virtual
5948 // members as referenced to ensure that they get instantiatied.
5949 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5950 return true;
5951 break;
5952
5953 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola8d04f062010-03-22 23:12:48 +00005954 return false;
Rafael Espindola70e040d2010-03-02 21:28:26 +00005955
5956 case TSK_ExplicitInstantiationDefinition:
5957 // This is method of a explicit instantiation; mark all of the virtual
5958 // members as referenced to ensure that they get instantiatied.
5959 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005960 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00005961
5962 // Consider only out-of-line definitions of member functions. When we see
5963 // an inline definition, it's too early to compute the key function.
5964 if (!MD->isOutOfLine())
5965 return false;
5966
5967 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5968
5969 // If there is no key function, we will need a copy of the vtable.
5970 if (!KeyFunction)
5971 return true;
5972
5973 // If this is the key function, we need to mark virtual members.
5974 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5975 return true;
5976
5977 return false;
5978}
5979
5980void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5981 CXXMethodDecl *MD) {
5982 CXXRecordDecl *RD = MD->getParent();
5983
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005984 // We will need to mark all of the virtual members as referenced to build the
5985 // vtable.
Anders Carlsson11e51402010-04-17 20:15:18 +00005986 if (!needsVTable(MD, Context))
Rafael Espindolae7113ca2010-03-10 02:19:29 +00005987 return;
5988
5989 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5990 if (kind == TSK_ImplicitInstantiation)
5991 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5992 else
Rafael Espindola70e040d2010-03-02 21:28:26 +00005993 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson82fccd02009-12-07 08:24:59 +00005994}
5995
5996bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5997 if (ClassesWithUnmarkedVirtualMembers.empty())
5998 return false;
5999
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006000 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
6001 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
6002 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
6003 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00006004 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006005 }
6006
Anders Carlsson82fccd02009-12-07 08:24:59 +00006007 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006008}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006009
Rafael Espindola5b334082010-03-26 00:36:59 +00006010void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6011 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006012 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6013 e = RD->method_end(); i != e; ++i) {
6014 CXXMethodDecl *MD = *i;
6015
6016 // C++ [basic.def.odr]p2:
6017 // [...] A virtual member function is used if it is not pure. [...]
6018 if (MD->isVirtual() && !MD->isPure())
6019 MarkDeclarationReferenced(Loc, MD);
6020 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006021
6022 // Only classes that have virtual bases need a VTT.
6023 if (RD->getNumVBases() == 0)
6024 return;
6025
6026 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6027 e = RD->bases_end(); i != e; ++i) {
6028 const CXXRecordDecl *Base =
6029 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6030 if (i->isVirtual())
6031 continue;
6032 if (Base->getNumVBases() == 0)
6033 continue;
6034 MarkVirtualMembersReferenced(Loc, Base);
6035 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006036}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006037
6038/// SetIvarInitializers - This routine builds initialization ASTs for the
6039/// Objective-C implementation whose ivars need be initialized.
6040void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6041 if (!getLangOptions().CPlusPlus)
6042 return;
6043 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6044 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6045 CollectIvarsToConstructOrDestruct(OID, ivars);
6046 if (ivars.empty())
6047 return;
6048 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6049 for (unsigned i = 0; i < ivars.size(); i++) {
6050 FieldDecl *Field = ivars[i];
6051 CXXBaseOrMemberInitializer *Member;
6052 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6053 InitializationKind InitKind =
6054 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6055
6056 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6057 Sema::OwningExprResult MemberInit =
6058 InitSeq.Perform(*this, InitEntity, InitKind,
6059 Sema::MultiExprArg(*this, 0, 0));
6060 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6061 // Note, MemberInit could actually come back empty if no initialization
6062 // is required (e.g., because it would call a trivial default constructor)
6063 if (!MemberInit.get() || MemberInit.isInvalid())
6064 continue;
6065
6066 Member =
6067 new (Context) CXXBaseOrMemberInitializer(Context,
6068 Field, SourceLocation(),
6069 SourceLocation(),
6070 MemberInit.takeAs<Expr>(),
6071 SourceLocation());
6072 AllToInit.push_back(Member);
6073 }
6074 ObjCImplementation->setIvarInitializers(Context,
6075 AllToInit.data(), AllToInit.size());
6076 }
6077}